kysely 0.18.0 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +22 -17
  2. package/dist/cjs/dialect/database-introspector.d.ts +13 -0
  3. package/dist/cjs/dialect/mysql/mysql-dialect-config.d.ts +24 -207
  4. package/dist/cjs/dialect/mysql/mysql-dialect.d.ts +26 -3
  5. package/dist/cjs/dialect/mysql/mysql-dialect.js +27 -5
  6. package/dist/cjs/dialect/mysql/mysql-driver.d.ts +13 -4
  7. package/dist/cjs/dialect/mysql/mysql-driver.js +33 -51
  8. package/dist/cjs/dialect/mysql/mysql-introspector.d.ts +11 -1
  9. package/dist/cjs/dialect/mysql/mysql-introspector.js +29 -7
  10. package/dist/cjs/dialect/postgres/postgres-dialect-config.d.ts +25 -89
  11. package/dist/cjs/dialect/postgres/postgres-dialect.d.ts +25 -5
  12. package/dist/cjs/dialect/postgres/postgres-dialect.js +26 -7
  13. package/dist/cjs/dialect/postgres/postgres-driver.d.ts +12 -3
  14. package/dist/cjs/dialect/postgres/postgres-driver.js +21 -39
  15. package/dist/cjs/dialect/postgres/postgres-introspector.d.ts +11 -1
  16. package/dist/cjs/dialect/postgres/postgres-introspector.js +15 -4
  17. package/dist/cjs/dialect/sqlite/sqlite-dialect-config.d.ts +25 -28
  18. package/dist/cjs/dialect/sqlite/sqlite-dialect.d.ts +19 -3
  19. package/dist/cjs/dialect/sqlite/sqlite-dialect.js +19 -3
  20. package/dist/cjs/dialect/sqlite/sqlite-driver.js +3 -37
  21. package/dist/cjs/dialect/sqlite/sqlite-introspector.d.ts +11 -1
  22. package/dist/cjs/dialect/sqlite/sqlite-introspector.js +11 -4
  23. package/dist/cjs/index.d.ts +153 -2
  24. package/dist/cjs/index.js +147 -3
  25. package/dist/cjs/migration/file-migration-provider.d.ts +21 -5
  26. package/dist/cjs/migration/file-migration-provider.js +14 -13
  27. package/dist/cjs/migration/migrator.d.ts +44 -2
  28. package/dist/cjs/migration/migrator.js +77 -18
  29. package/dist/cjs/plugin/noop-plugin.d.ts +42 -0
  30. package/dist/cjs/plugin/noop-plugin.js +12 -0
  31. package/dist/cjs/query-creator.d.ts +9 -0
  32. package/dist/cjs/query-creator.js +18 -0
  33. package/dist/cjs/schema/alter-table-builder.d.ts +2 -5
  34. package/dist/cjs/schema/alter-table-builder.js +3 -7
  35. package/dist/cjs/schema/schema.d.ts +9 -0
  36. package/dist/cjs/schema/schema.js +12 -0
  37. package/dist/cjs/util/column-type.d.ts +9 -1
  38. package/dist/cjs/util/stack-trace-utils.d.ts +1 -0
  39. package/dist/cjs/util/stack-trace-utils.js +17 -0
  40. package/dist/esm/dialect/database-introspector.d.ts +13 -0
  41. package/dist/esm/dialect/mysql/mysql-dialect-config.d.ts +24 -207
  42. package/dist/esm/dialect/mysql/mysql-dialect.d.ts +26 -3
  43. package/dist/esm/dialect/mysql/mysql-dialect.js +27 -5
  44. package/dist/esm/dialect/mysql/mysql-driver.d.ts +13 -4
  45. package/dist/esm/dialect/mysql/mysql-driver.js +33 -51
  46. package/dist/esm/dialect/mysql/mysql-introspector.d.ts +11 -1
  47. package/dist/esm/dialect/mysql/mysql-introspector.js +30 -8
  48. package/dist/esm/dialect/postgres/postgres-dialect-config.d.ts +25 -89
  49. package/dist/esm/dialect/postgres/postgres-dialect.d.ts +25 -5
  50. package/dist/esm/dialect/postgres/postgres-dialect.js +26 -7
  51. package/dist/esm/dialect/postgres/postgres-driver.d.ts +12 -3
  52. package/dist/esm/dialect/postgres/postgres-driver.js +21 -39
  53. package/dist/esm/dialect/postgres/postgres-introspector.d.ts +11 -1
  54. package/dist/esm/dialect/postgres/postgres-introspector.js +16 -5
  55. package/dist/esm/dialect/sqlite/sqlite-dialect-config.d.ts +25 -28
  56. package/dist/esm/dialect/sqlite/sqlite-dialect.d.ts +19 -3
  57. package/dist/esm/dialect/sqlite/sqlite-dialect.js +19 -3
  58. package/dist/esm/dialect/sqlite/sqlite-driver.js +4 -38
  59. package/dist/esm/dialect/sqlite/sqlite-introspector.d.ts +11 -1
  60. package/dist/esm/dialect/sqlite/sqlite-introspector.js +12 -5
  61. package/dist/esm/index.d.ts +153 -2
  62. package/dist/esm/index.js +142 -2
  63. package/dist/esm/migration/file-migration-provider.d.ts +21 -5
  64. package/dist/esm/migration/file-migration-provider.js +14 -13
  65. package/dist/esm/migration/migrator.d.ts +44 -2
  66. package/dist/esm/migration/migrator.js +76 -17
  67. package/dist/esm/plugin/noop-plugin.d.ts +42 -0
  68. package/dist/esm/plugin/noop-plugin.js +9 -0
  69. package/dist/esm/query-creator.d.ts +9 -0
  70. package/dist/esm/query-creator.js +18 -0
  71. package/dist/esm/schema/alter-table-builder.d.ts +2 -5
  72. package/dist/esm/schema/alter-table-builder.js +4 -8
  73. package/dist/esm/schema/schema.d.ts +9 -0
  74. package/dist/esm/schema/schema.js +12 -0
  75. package/dist/esm/util/column-type.d.ts +9 -1
  76. package/dist/esm/util/stack-trace-utils.d.ts +1 -0
  77. package/dist/esm/util/stack-trace-utils.js +14 -0
  78. package/package.json +10 -15
  79. package/dist/cjs/index-nodeless.d.ts +0 -152
  80. package/dist/cjs/index-nodeless.js +0 -153
  81. package/dist/esm/index-nodeless.d.ts +0 -152
  82. package/dist/esm/index-nodeless.js +0 -142
@@ -1,103 +1,39 @@
1
- /// <reference types="node" />
2
- import * as stream from 'stream';
3
- import { ConnectionOptions } from 'tls';
4
1
  import { DatabaseConnection } from '../../driver/database-connection.js';
5
2
  /**
6
3
  * Config for the PostgreSQL dialect.
7
- *
8
- * This interface is equal to `pg` library's `Pool` config:
9
- *
10
- * https://node-postgres.com/api/pool
11
- * https://node-postgres.com/api/client
12
4
  */
13
5
  export interface PostgresDialectConfig {
14
6
  /**
15
- * defaults process.env.PGUSER || process.env.USER.
16
- */
17
- user?: string;
18
- /**
19
- * default process.env.PGDATABASE || process.env.USER
20
- */
21
- database?: string;
22
- /**
23
- * default process.env.PGPASSWORD
24
- */
25
- password?: string | (() => string | Promise<string>);
26
- /**
27
- * default process.env.PGPORT
28
- */
29
- port?: number;
30
- /**
31
- * default process.env.PGHOST
32
- */
33
- host?: string;
34
- /**
35
- * e.g. postgres:*user:password@host:5432/database
36
- */
37
- connectionString?: string;
38
- /**
39
- * passed directly to node.TLSSocket, supports all tls.connect options
40
- */
41
- ssl?: boolean | ConnectionOptions;
42
- /**
43
- * Number of milliseconds to wait before timing out when connecting a new client
44
- * by default this is 0 which means no timeout.
45
- */
46
- connectionTimeoutMillis?: number;
47
- /**
48
- * Maximum number of clients the pool should contain. by default this is set to 10.
49
- */
50
- max?: number;
51
- /**
52
- * Minimum number of clients the pool should contain
53
- */
54
- min?: number;
55
- /**
56
- * Number of milliseconds a client must sit idle in the pool and not be checked out
57
- * before it is disconnected from the backend and discarded.
7
+ * A postgres Pool instance or a function that returns one.
58
8
  *
59
- * default is 10000 (10 seconds) - set to 0 to disable auto-disconnection of idle clients.
60
- */
61
- idleTimeoutMillis?: number;
62
- /**
63
- * Default behavior is the pool will keep clients open & connected to the backend
64
- * until idleTimeoutMillis expire for each client and node will maintain a ref
65
- * to the socket on the client, keeping the event loop alive until all clients are closed
66
- * after being idle or the pool is manually shutdown with `pool.end()`.
9
+ * If a function is provided, it's called once when the first query is executed.
67
10
  *
68
- * Setting `allowExitOnIdle: true` in the config will allow the node event loop to exit
69
- * as soon as all clients in the pool are idle, even if their socket is still open
70
- * to the PostgreSQL server. This can be handy in scripts & tests
71
- * where you don't want to wait for your clients to go idle before your process exits.
72
- */
73
- allowExitOnIdle?: boolean;
74
- log?: (...messages: any[]) => void;
75
- /**
76
- * Number of milliseconds before a statement in query will time out, default is no timeout.
11
+ * https://node-postgres.com/api/pool
77
12
  */
78
- statement_timeout?: false | number;
79
- /**
80
- * Number of milliseconds before terminating any session with an open idle transaction.
81
- * Default is no timeout.
82
- */
83
- idle_in_transaction_session_timeout?: number;
84
- /**
85
- * Number of milliseconds before a query call will timeout, default is no timeout.
86
- */
87
- query_timeout?: number;
88
- /**
89
- * The name of the application that created this Client instance.
90
- */
91
- application_name?: string;
13
+ pool: PostgresPool | (() => Promise<PostgresPool>);
92
14
  /**
93
15
  * Called once for each created connection.
94
- *
95
- * This is a Kysely specific feature and does not come from the `pg` module.
96
16
  */
97
17
  onCreateConnection?: (connection: DatabaseConnection) => Promise<void>;
98
- keepAlive?: boolean;
99
- keepAliveInitialDelayMillis?: number;
100
- types?: any;
101
- stream?: stream.Duplex;
102
- parseInputDatesAsUTC?: boolean;
18
+ }
19
+ /**
20
+ * This interface is the subset of pg driver's `Pool` class that
21
+ * kysely needs.
22
+ *
23
+ * We don't use the type from `pg` here to not have a dependency to it.
24
+ *
25
+ * https://node-postgres.com/api/pool
26
+ */
27
+ export interface PostgresPool {
28
+ connect(): Promise<PostgresPoolClient>;
29
+ end(): Promise<void>;
30
+ }
31
+ export interface PostgresPoolClient {
32
+ query<R>(sql: string, parameters: ReadonlyArray<unknown>): Promise<PostgresQueryResult<R>>;
33
+ release(): void;
34
+ }
35
+ export interface PostgresQueryResult<R> {
36
+ command: 'UPDATE' | 'DELETE' | 'INSERT' | 'SELECT';
37
+ rowCount: number;
38
+ rows: R[];
103
39
  }
@@ -8,12 +8,32 @@ import { PostgresDialectConfig } from './postgres-dialect-config.js';
8
8
  /**
9
9
  * PostgreSQL dialect that uses the [pg](https://node-postgres.com/) library.
10
10
  *
11
- * The {@link PostgresDialectConfig | configuration} passed to the constructor
12
- * is given as-is to the pg library's [Pool](https://node-postgres.com/api/pool)
13
- * constructor. See the following two links for more documentation:
11
+ * The constructor takes an instance of {@link PostgresDialectConfig}.
14
12
  *
15
- * https://node-postgres.com/api/pool
16
- * https://node-postgres.com/api/client
13
+ * ```ts
14
+ * import { Pool } from 'pg'
15
+ *
16
+ * new PostgresDialect({
17
+ * pool: new Pool({
18
+ * database: 'some_db',
19
+ * host: 'localhost',
20
+ * })
21
+ * })
22
+ * ```
23
+ *
24
+ * If you want the pool to only be created once it's first used, `pool`
25
+ * can be a function:
26
+ *
27
+ * ```ts
28
+ * import { Pool } from 'pg'
29
+ *
30
+ * new PostgresDialect({
31
+ * pool: async () => new Pool({
32
+ * database: 'some_db',
33
+ * host: 'localhost',
34
+ * })
35
+ * })
36
+ * ```
17
37
  */
18
38
  export declare class PostgresDialect implements Dialect {
19
39
  #private;
@@ -3,21 +3,40 @@ import { PostgresDriver } from './postgres-driver.js';
3
3
  import { PostgresIntrospector } from './postgres-introspector.js';
4
4
  import { PostgresQueryCompiler } from './postgres-query-compiler.js';
5
5
  import { PostgresAdapter } from './postgres-adapter.js';
6
- import { freeze } from '../../util/object-utils.js';
7
6
  /**
8
7
  * PostgreSQL dialect that uses the [pg](https://node-postgres.com/) library.
9
8
  *
10
- * The {@link PostgresDialectConfig | configuration} passed to the constructor
11
- * is given as-is to the pg library's [Pool](https://node-postgres.com/api/pool)
12
- * constructor. See the following two links for more documentation:
9
+ * The constructor takes an instance of {@link PostgresDialectConfig}.
13
10
  *
14
- * https://node-postgres.com/api/pool
15
- * https://node-postgres.com/api/client
11
+ * ```ts
12
+ * import { Pool } from 'pg'
13
+ *
14
+ * new PostgresDialect({
15
+ * pool: new Pool({
16
+ * database: 'some_db',
17
+ * host: 'localhost',
18
+ * })
19
+ * })
20
+ * ```
21
+ *
22
+ * If you want the pool to only be created once it's first used, `pool`
23
+ * can be a function:
24
+ *
25
+ * ```ts
26
+ * import { Pool } from 'pg'
27
+ *
28
+ * new PostgresDialect({
29
+ * pool: async () => new Pool({
30
+ * database: 'some_db',
31
+ * host: 'localhost',
32
+ * })
33
+ * })
34
+ * ```
16
35
  */
17
36
  export class PostgresDialect {
18
37
  #config;
19
38
  constructor(config) {
20
- this.#config = freeze({ ...config });
39
+ this.#config = config;
21
40
  }
22
41
  createDriver() {
23
42
  return new PostgresDriver(this.#config);
@@ -1,6 +1,8 @@
1
- import { DatabaseConnection } from '../../driver/database-connection.js';
1
+ import { DatabaseConnection, QueryResult } from '../../driver/database-connection.js';
2
2
  import { Driver, TransactionSettings } from '../../driver/driver.js';
3
- import { PostgresDialectConfig } from './postgres-dialect-config.js';
3
+ import { CompiledQuery } from '../../query-compiler/compiled-query.js';
4
+ import { PostgresDialectConfig, PostgresPoolClient } from './postgres-dialect-config.js';
5
+ declare const PRIVATE_RELEASE_METHOD: unique symbol;
4
6
  export declare class PostgresDriver implements Driver {
5
7
  #private;
6
8
  constructor(config: PostgresDialectConfig);
@@ -35,9 +37,16 @@ export declare class PostgresDriver implements Driver {
35
37
  /**
36
38
  * Releases a connection back to the pool.
37
39
  */
38
- releaseConnection(connection: DatabaseConnection): Promise<void>;
40
+ releaseConnection(connection: PostgresConnection): Promise<void>;
39
41
  /**
40
42
  * Destroys the driver and releases all resources.
41
43
  */
42
44
  destroy(): Promise<void>;
43
45
  }
46
+ declare class PostgresConnection implements DatabaseConnection {
47
+ #private;
48
+ constructor(client: PostgresPoolClient);
49
+ executeQuery<O>(compiledQuery: CompiledQuery): Promise<QueryResult<O>>;
50
+ [PRIVATE_RELEASE_METHOD](): void;
51
+ }
52
+ export {};
@@ -1,24 +1,19 @@
1
1
  /// <reference types="./postgres-driver.d.ts" />
2
2
  import { CompiledQuery } from '../../query-compiler/compiled-query.js';
3
3
  import { isFunction, freeze } from '../../util/object-utils.js';
4
+ import { extendStackTrace } from '../../util/stack-trace-utils.js';
4
5
  const PRIVATE_RELEASE_METHOD = Symbol();
5
6
  export class PostgresDriver {
6
7
  #config;
7
8
  #connections = new WeakMap();
8
- #pool = null;
9
+ #pool;
9
10
  constructor(config) {
10
11
  this.#config = freeze({ ...config });
11
12
  }
12
13
  async init() {
13
- // Import the `pg` module here instead at the top of the file
14
- // so that this file can be loaded by node without `pg` driver
15
- // installed. As you can see, there IS an import from `pg` at the
16
- // top level too, but that's only for types. It doesn't get compiled
17
- // into javascript. You can check the built javascript code.
18
- const PoolConstructor = await importPgPool();
19
- // Use the `pg` module's own pool. All drivers should use the
20
- // pool provided by the database library if possible.
21
- this.#pool = new PoolConstructor(this.#config);
14
+ this.#pool = isFunction(this.#config.pool)
15
+ ? await this.#config.pool()
16
+ : this.#config.pool;
22
17
  }
23
18
  async acquireConnection() {
24
19
  const client = await this.#pool.connect();
@@ -29,7 +24,7 @@ export class PostgresDriver {
29
24
  // The driver must take care of calling `onCreateConnection` when a new
30
25
  // connection is created. The `pg` module doesn't provide an async hook
31
26
  // for the connection creation. We need to call the method explicitly.
32
- if (this.#config.onCreateConnection) {
27
+ if (this.#config?.onCreateConnection) {
33
28
  await this.#config.onCreateConnection(connection);
34
29
  }
35
30
  }
@@ -50,52 +45,39 @@ export class PostgresDriver {
50
45
  await connection.executeQuery(CompiledQuery.raw('rollback'));
51
46
  }
52
47
  async releaseConnection(connection) {
53
- const pgConnection = connection;
54
- pgConnection[PRIVATE_RELEASE_METHOD]();
48
+ connection[PRIVATE_RELEASE_METHOD]();
55
49
  }
56
50
  async destroy() {
57
51
  if (this.#pool) {
58
52
  const pool = this.#pool;
59
- this.#pool = null;
53
+ this.#pool = undefined;
60
54
  await pool.end();
61
55
  }
62
56
  }
63
57
  }
64
- async function importPgPool() {
65
- try {
66
- // The imported module name must be a string literal to make
67
- // some bundlers work. So don't move this code behind a helper
68
- // for example.
69
- const pgModule = await import('pg');
70
- if (isFunction(pgModule.Pool)) {
71
- return pgModule.Pool;
72
- }
73
- else {
74
- return pgModule.default.Pool;
75
- }
76
- }
77
- catch (error) {
78
- throw new Error('Postgres client not installed. Please run `npm install pg`');
79
- }
80
- }
81
58
  class PostgresConnection {
82
59
  #client;
83
60
  constructor(client) {
84
61
  this.#client = client;
85
62
  }
86
63
  async executeQuery(compiledQuery) {
87
- const result = await this.#client.query(compiledQuery.sql, [
88
- ...compiledQuery.parameters,
89
- ]);
90
- if (result.command === 'UPDATE' || result.command === 'DELETE') {
64
+ try {
65
+ const result = await this.#client.query(compiledQuery.sql, [
66
+ ...compiledQuery.parameters,
67
+ ]);
68
+ if (result.command === 'UPDATE' || result.command === 'DELETE') {
69
+ return {
70
+ numUpdatedOrDeletedRows: BigInt(result.rowCount),
71
+ rows: result.rows ?? [],
72
+ };
73
+ }
91
74
  return {
92
- numUpdatedOrDeletedRows: BigInt(result.rowCount),
93
75
  rows: result.rows ?? [],
94
76
  };
95
77
  }
96
- return {
97
- rows: result.rows ?? [],
98
- };
78
+ catch (err) {
79
+ throw extendStackTrace(err, new Error());
80
+ }
99
81
  }
100
82
  [PRIVATE_RELEASE_METHOD]() {
101
83
  this.#client.release();
@@ -1,10 +1,20 @@
1
- import { DatabaseIntrospector, DatabaseMetadata, DatabaseMetadataOptions } from '../database-introspector.js';
1
+ import { DatabaseIntrospector, DatabaseMetadata, DatabaseMetadataOptions, SchemaMetadata, TableMetadata } from '../database-introspector.js';
2
2
  import { Kysely } from '../../kysely.js';
3
3
  export declare class PostgresIntrospector implements DatabaseIntrospector {
4
4
  #private;
5
5
  constructor(db: Kysely<any>);
6
+ /**
7
+ * Get schema metadata.
8
+ */
9
+ getSchemas(): Promise<SchemaMetadata[]>;
10
+ /**
11
+ * Get table metadata.
12
+ */
13
+ getTables(options?: DatabaseMetadataOptions): Promise<TableMetadata[]>;
6
14
  /**
7
15
  * Get the database metadata such as table and column names.
16
+ *
17
+ * @deprecated Use getTables() instead.
8
18
  */
9
19
  getMetadata(options?: DatabaseMetadataOptions): Promise<DatabaseMetadata>;
10
20
  }
@@ -1,12 +1,20 @@
1
1
  /// <reference types="./postgres-introspector.d.ts" />
2
- import { MIGRATION_LOCK_TABLE, MIGRATION_TABLE, } from '../../migration/migrator.js';
2
+ import { DEFAULT_MIGRATION_LOCK_TABLE, DEFAULT_MIGRATION_TABLE, } from '../../migration/migrator.js';
3
3
  import { freeze } from '../../util/object-utils.js';
4
4
  export class PostgresIntrospector {
5
5
  #db;
6
6
  constructor(db) {
7
7
  this.#db = db;
8
8
  }
9
- async getMetadata(options = { withInternalKyselyTables: false }) {
9
+ async getSchemas() {
10
+ let rawSchemas = await this.#db
11
+ .selectFrom('pg_catalog.pg_namespace')
12
+ .select('nspname')
13
+ .castTo()
14
+ .execute();
15
+ return rawSchemas.map((it) => ({ name: it.nspname }));
16
+ }
17
+ async getTables(options = { withInternalKyselyTables: false }) {
10
18
  let query = this.#db
11
19
  .selectFrom('pg_catalog.pg_attribute as a')
12
20
  .innerJoin('pg_catalog.pg_class as c', 'a.attrelid', 'c.oid')
@@ -26,12 +34,15 @@ export class PostgresIntrospector {
26
34
  .castTo();
27
35
  if (!options.withInternalKyselyTables) {
28
36
  query = query
29
- .where('t.tablename', '!=', MIGRATION_TABLE)
30
- .where('t.tablename', '!=', MIGRATION_LOCK_TABLE);
37
+ .where('t.tablename', '!=', DEFAULT_MIGRATION_TABLE)
38
+ .where('t.tablename', '!=', DEFAULT_MIGRATION_LOCK_TABLE);
31
39
  }
32
40
  const rawColumns = await query.execute();
41
+ return this.#parseTableMetadata(rawColumns);
42
+ }
43
+ async getMetadata(options) {
33
44
  return {
34
- tables: this.#parseTableMetadata(rawColumns),
45
+ tables: await this.getTables(options),
35
46
  };
36
47
  }
37
48
  #parseTableMetadata(columns) {
@@ -1,39 +1,16 @@
1
1
  import { DatabaseConnection } from '../../driver/database-connection.js';
2
2
  /**
3
3
  * Config for the SQLite dialect.
4
- *
5
- * This interface is equal to `better-sqlite3` library's `Databse` class's constructor parameters.
6
- *
7
- * https://github.com/JoshuaWise/better-sqlite3/blob/master/docs/api.md#new-databasepath-options
8
4
  */
9
5
  export interface SqliteDialectConfig {
10
6
  /**
11
- * The database file path.
7
+ * An sqlite Database instance or a function that returns one.
12
8
  *
13
- * This is passed as the first argument for the [Database](https://github.com/JoshuaWise/better-sqlite3/blob/master/docs/api.md#new-databasepath-options)
14
- * class constructor.
15
- */
16
- databasePath: string;
17
- /**
18
- * Open the database connection in readonly mode (default: false)
19
- */
20
- readonly?: boolean;
21
- /**
22
- * If the database does not exist, an Error will be thrown instead of creating a new file.
23
- * This option is ignored for in-memory, temporary, or readonly database connections
24
- * (default: false)
25
- */
26
- fileMustExist?: boolean;
27
- /**
28
- * The number of milliseconds to wait when executing queries on a locked database,
29
- * before throwing a SQLITE_BUSY error (default: 5000)
30
- */
31
- timeout?: number;
32
- /**
33
- * Provide a function that gets called with every SQL string executed by the database connection
34
- * (default: null)
9
+ * If a function is provided, it's called once when the first query is executed.
10
+ *
11
+ * https://github.com/JoshuaWise/better-sqlite3/blob/master/docs/api.md#new-databasepath-options
35
12
  */
36
- verbose?: (sql: string) => void;
13
+ database: SqliteDatabase | (() => Promise<SqliteDatabase>);
37
14
  /**
38
15
  * Called once when the first query is executed.
39
16
  *
@@ -41,3 +18,23 @@ export interface SqliteDialectConfig {
41
18
  */
42
19
  onCreateConnection?: (connection: DatabaseConnection) => Promise<void>;
43
20
  }
21
+ /**
22
+ * This interface is the subset of better-sqlite3 driver's `Database` class that
23
+ * kysely needs.
24
+ *
25
+ * We don't use the type from `better-sqlite3` here to not have a dependency to it.
26
+ *
27
+ * https://github.com/JoshuaWise/better-sqlite3/blob/master/docs/api.md#new-databasepath-options
28
+ */
29
+ export interface SqliteDatabase {
30
+ close(): void;
31
+ prepare(sql: string): SqliteStatement;
32
+ }
33
+ export interface SqliteStatement {
34
+ readonly reader: boolean;
35
+ all(parameters: ReadonlyArray<unknown>): unknown[];
36
+ run(parameters: ReadonlyArray<unknown>): {
37
+ changes: number | bigint;
38
+ lastInsertRowid: number | bigint;
39
+ };
40
+ }
@@ -8,9 +8,25 @@ import { SqliteDialectConfig } from './sqlite-dialect-config.js';
8
8
  /**
9
9
  * SQLite dialect that uses the [better-sqlite3](https://github.com/JoshuaWise/better-sqlite3) library.
10
10
  *
11
- * The {@link SqliteDialectConfig | configuration} is used to construct an instance of
12
- * [Database](https://github.com/JoshuaWise/better-sqlite3/blob/master/docs/api.md#new-databasepath-options)
13
- * class. The configuration values are passed directly to the `Database` constructor.
11
+ * The constructor takes an instance of {@link SqliteDialectConfig}.
12
+ *
13
+ * ```ts
14
+ * import Database from 'better-sqlite3'
15
+ *
16
+ * new SqliteDialect({
17
+ * database: new Database('db.sqlite')
18
+ * })
19
+ * ```
20
+ *
21
+ * If you want the pool to only be created once it's first used, `database`
22
+ * can be a function:
23
+ *
24
+ * ```ts
25
+ * import Database from 'better-sqlite3'
26
+ *
27
+ * new SqliteDialect({
28
+ * database: async () => new Database('db.sqlite')
29
+ * })
14
30
  */
15
31
  export declare class SqliteDialect implements Dialect {
16
32
  #private;
@@ -7,9 +7,25 @@ import { freeze } from '../../util/object-utils.js';
7
7
  /**
8
8
  * SQLite dialect that uses the [better-sqlite3](https://github.com/JoshuaWise/better-sqlite3) library.
9
9
  *
10
- * The {@link SqliteDialectConfig | configuration} is used to construct an instance of
11
- * [Database](https://github.com/JoshuaWise/better-sqlite3/blob/master/docs/api.md#new-databasepath-options)
12
- * class. The configuration values are passed directly to the `Database` constructor.
10
+ * The constructor takes an instance of {@link SqliteDialectConfig}.
11
+ *
12
+ * ```ts
13
+ * import Database from 'better-sqlite3'
14
+ *
15
+ * new SqliteDialect({
16
+ * database: new Database('db.sqlite')
17
+ * })
18
+ * ```
19
+ *
20
+ * If you want the pool to only be created once it's first used, `database`
21
+ * can be a function:
22
+ *
23
+ * ```ts
24
+ * import Database from 'better-sqlite3'
25
+ *
26
+ * new SqliteDialect({
27
+ * database: async () => new Database('db.sqlite')
28
+ * })
13
29
  */
14
30
  export class SqliteDialect {
15
31
  #config;
@@ -1,6 +1,6 @@
1
1
  /// <reference types="./sqlite-driver.d.ts" />
2
2
  import { CompiledQuery } from '../../query-compiler/compiled-query.js';
3
- import { freeze, isBoolean, isFunction, isNumber, } from '../../util/object-utils.js';
3
+ import { freeze, isFunction } from '../../util/object-utils.js';
4
4
  export class SqliteDriver {
5
5
  #config;
6
6
  #connectionMutex = new ConnectionMutex();
@@ -10,26 +10,9 @@ export class SqliteDriver {
10
10
  this.#config = freeze({ ...config });
11
11
  }
12
12
  async init() {
13
- // Import the `better-sqlite3` module here instead at the top of the file
14
- // so that this file can be loaded by node without `better-sqlite3` driver
15
- // installed. As you can see, there IS an import from `better-sqlite3` at
16
- // the top level too, but that's only for types. It doesn't get compiled
17
- // into javascript. You can check the built javascript code.
18
- const DatabaseConstructor = await importBetterSqlite3Database();
19
- const options = {};
20
- if (isBoolean(this.#config.readonly)) {
21
- options.readonly = this.#config.readonly;
22
- }
23
- if (isBoolean(this.#config.fileMustExist)) {
24
- options.fileMustExist = this.#config.fileMustExist;
25
- }
26
- if (isNumber(this.#config.timeout)) {
27
- options.timeout = this.#config.timeout;
28
- }
29
- if (isFunction(this.#config.verbose)) {
30
- options.verbose = this.#config.verbose;
31
- }
32
- this.#db = new DatabaseConstructor(this.#config.databasePath, options);
13
+ this.#db = isFunction(this.#config.database)
14
+ ? await this.#config.database()
15
+ : this.#config.database;
33
16
  this.#connection = new SqliteConnection(this.#db);
34
17
  if (this.#config.onCreateConnection) {
35
18
  await this.#config.onCreateConnection(this.#connection);
@@ -57,23 +40,6 @@ export class SqliteDriver {
57
40
  this.#db?.close();
58
41
  }
59
42
  }
60
- async function importBetterSqlite3Database() {
61
- try {
62
- // The imported module name must be a string literal to make
63
- // some bundlers work. So don't move this code behind a helper
64
- // for example.
65
- const sqliteModule = await import('better-sqlite3');
66
- if (isFunction(sqliteModule)) {
67
- return sqliteModule;
68
- }
69
- else {
70
- return sqliteModule.default;
71
- }
72
- }
73
- catch (error) {
74
- throw new Error('SQLite client not installed. Please run `npm install better-sqlite3`');
75
- }
76
- }
77
43
  class SqliteConnection {
78
44
  #db;
79
45
  constructor(db) {
@@ -1,10 +1,20 @@
1
- import { DatabaseIntrospector, DatabaseMetadata, DatabaseMetadataOptions } from '../database-introspector.js';
1
+ import { DatabaseIntrospector, DatabaseMetadata, DatabaseMetadataOptions, SchemaMetadata, TableMetadata } from '../database-introspector.js';
2
2
  import { Kysely } from '../../kysely.js';
3
3
  export declare class SqliteIntrospector implements DatabaseIntrospector {
4
4
  #private;
5
5
  constructor(db: Kysely<any>);
6
+ /**
7
+ * Get schema metadata.
8
+ */
9
+ getSchemas(): Promise<SchemaMetadata[]>;
10
+ /**
11
+ * Get table metadata.
12
+ */
13
+ getTables(options?: DatabaseMetadataOptions): Promise<TableMetadata[]>;
6
14
  /**
7
15
  * Get the database metadata such as table and column names.
16
+ *
17
+ * @deprecated Use getTables() instead.
8
18
  */
9
19
  getMetadata(options?: DatabaseMetadataOptions): Promise<DatabaseMetadata>;
10
20
  }
@@ -1,12 +1,16 @@
1
1
  /// <reference types="./sqlite-introspector.d.ts" />
2
- import { MIGRATION_LOCK_TABLE, MIGRATION_TABLE, } from '../../migration/migrator.js';
2
+ import { DEFAULT_MIGRATION_LOCK_TABLE, DEFAULT_MIGRATION_TABLE, } from '../../migration/migrator.js';
3
3
  import { sql } from '../../raw-builder/sql.js';
4
4
  export class SqliteIntrospector {
5
5
  #db;
6
6
  constructor(db) {
7
7
  this.#db = db;
8
8
  }
9
- async getMetadata(options = { withInternalKyselyTables: false }) {
9
+ async getSchemas() {
10
+ // Sqlite doesn't support schemas.
11
+ return [];
12
+ }
13
+ async getTables(options = { withInternalKyselyTables: false }) {
10
14
  let query = this.#db
11
15
  .selectFrom('sqlite_schema')
12
16
  .where('type', '=', 'table')
@@ -15,12 +19,15 @@ export class SqliteIntrospector {
15
19
  .castTo();
16
20
  if (!options.withInternalKyselyTables) {
17
21
  query = query
18
- .where('name', '!=', MIGRATION_TABLE)
19
- .where('name', '!=', MIGRATION_LOCK_TABLE);
22
+ .where('name', '!=', DEFAULT_MIGRATION_TABLE)
23
+ .where('name', '!=', DEFAULT_MIGRATION_LOCK_TABLE);
20
24
  }
21
25
  const tables = await query.execute();
26
+ return Promise.all(tables.map(({ name }) => this.#getTableMetadata(name)));
27
+ }
28
+ async getMetadata(options) {
22
29
  return {
23
- tables: await Promise.all(tables.map(({ name }) => this.#getTableMetadata(name))),
30
+ tables: await this.getTables(options),
24
31
  };
25
32
  }
26
33
  async #getTableMetadata(table) {