Skip to content

Commit

Permalink
add numAffectedRows @ D1Connection.executeQuery. (aidenwallis#14)
Browse files Browse the repository at this point in the history
* add `numAffectedRows` @ `D1Connection.executeQuery`.

* bump kysely to 0.23.x.
  • Loading branch information
igalklebanov authored and adam-the committed Aug 20, 2023
1 parent 188931f commit 1a84616
Show file tree
Hide file tree
Showing 3 changed files with 163 additions and 17 deletions.
28 changes: 14 additions & 14 deletions example/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"deploy": "wrangler publish"
},
"dependencies": {
"kysely": "^0.22.0",
"kysely-d1": "^0.0.5"
"kysely": "^0.23.3",
"kysely-d1": "^0.0.6"
}
}
148 changes: 147 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,149 @@
export * from './d1-dialect';
// Marked as unstable as the D1 HTTP API is currently undocumented and may change.
export { D1APIDialect as unstable_D1APIDialect, D1DialectConfig as unstable_D1DialectConfig } from './d1-api-dialect';
export { D1APIDialect as unstable_D1APIDialect, D1DialectConfig as unstable_D1DialectConfig } from './d1-api-dialect';

import { D1Database } from '@cloudflare/workers-types';
import {
CompiledQuery,
DatabaseConnection,
DatabaseIntrospector,
Dialect,
Driver,
Kysely,
SqliteAdapter,
SqliteIntrospector,
SqliteQueryCompiler,
QueryCompiler,
QueryResult,
} from 'kysely';

/**
* Config for the D1 dialect. Pass your D1 instance to this object that you bound in `wrangler.toml`.
*/
export interface D1DialectConfig {
database: D1Database;
}

/**
* D1 dialect that adds support for [Cloudflare D1][0] in [Kysely][1].
* The constructor takes the instance of your D1 database that you bound in `wrangler.toml`.
*
* ```typescript
* new D1Dialect({
* database: env.DB,
* })
* ```
*
* [0]: https://blog.cloudflare.com/introducing-d1/
* [1]: https://github.com/koskimas/kysely
*/
export class D1Dialect implements Dialect {
#config: D1DialectConfig;

constructor(config: D1DialectConfig) {
this.#config = config;
}

createAdapter() {
return new SqliteAdapter();
}

createDriver(): Driver {
return new D1Driver(this.#config);
}

createQueryCompiler(): QueryCompiler {
return new SqliteQueryCompiler();
}

createIntrospector(db: Kysely<any>): DatabaseIntrospector {
return new SqliteIntrospector(db);
}
}

class D1Driver implements Driver {
#config: D1DialectConfig;

constructor(config: D1DialectConfig) {
this.#config = config;
}

async init(): Promise<void> {}

async acquireConnection(): Promise<DatabaseConnection> {
return new D1Connection(this.#config);
}

async beginTransaction(conn: D1Connection): Promise<void> {
return await conn.beginTransaction();
}

async commitTransaction(conn: D1Connection): Promise<void> {
return await conn.commitTransaction();
}

async rollbackTransaction(conn: D1Connection): Promise<void> {
return await conn.rollbackTransaction();
}

async releaseConnection(_conn: D1Connection): Promise<void> {}

async destroy(): Promise<void> {}
}

class D1Connection implements DatabaseConnection {
#config: D1DialectConfig;
// #transactionClient?: D1Connection

constructor(config: D1DialectConfig) {
this.#config = config;
}

async executeQuery<O>(compiledQuery: CompiledQuery): Promise<QueryResult<O>> {
// Transactions are not supported yet.
// if (this.#transactionClient) return this.#transactionClient.executeQuery(compiledQuery)

const result = await this.#config.database
.prepare(compiledQuery.sql)
.bind(...compiledQuery.parameters)
.all();
if (result.error) {
throw new Error(result.error);
}

const numAffectedRows = result.meta.rows_read + result.meta.rows_written;
const lastRow = result.results[result.results.length - 1];

return {
insertId: lastRow?.id === undefined || lastRow?.id === null ? undefined : BigInt(lastRow.id as number),
rows: (result?.results as O[]) || [],
numAffectedRows,
// @ts-ignore deprecated in kysely >= 0.23, keep for backward compatibility.
numUpdatedOrDeletedRows: numAffectedRows,
};
}

async beginTransaction() {
// this.#transactionClient = this.#transactionClient ?? new PlanetScaleConnection(this.#config)
// this.#transactionClient.#conn.execute('BEGIN')
throw new Error('Transactions are not supported yet.');
}

async commitTransaction() {
// if (!this.#transactionClient) throw new Error('No transaction to commit')
// this.#transactionClient.#conn.execute('COMMIT')
// this.#transactionClient = undefined
throw new Error('Transactions are not supported yet.');
}

async rollbackTransaction() {
// if (!this.#transactionClient) throw new Error('No transaction to rollback')
// this.#transactionClient.#conn.execute('ROLLBACK')
// this.#transactionClient = undefined
throw new Error('Transactions are not supported yet.');
}

async *streamQuery<O>(_compiledQuery: CompiledQuery, _chunkSize: number): AsyncIterableIterator<QueryResult<O>> {
throw new Error('D1 Driver does not support streaming');
}
}

0 comments on commit 1a84616

Please sign in to comment.