nitro-sqlite-drizzle 0.0.0-stage → 11.0.0-alpha.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.
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Marc Rousavy & Christoph Pader
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ of this software and associated documentation files (the "Software"), to deal
6
+ in the Software without restriction, including without limitation the rights
7
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the Software is
9
+ furnished to do so, subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,90 @@
1
- # Temporary Holding Version
1
+ # nitro-sqlite-drizzle
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [Drizzle ORM](https://orm.drizzle.team) driver for `nitro-sqlite`.
4
+
5
+ ## Installation
6
+
7
+ Install the 11.0.0 alpha from the `alpha` tag with `nitro-sqlite` and `drizzle-orm`. The app's React version must also be installed. Save exact versions: npm otherwise saves `^11.0.0-alpha.0`, which also matches the older `11.0.0-nitro-v1.x` builds.
8
+
9
+ ```sh
10
+ bun add --exact nitro-sqlite@alpha nitro-sqlite-drizzle@alpha drizzle-orm@0.45.4
11
+ ```
12
+
13
+ See the [companion installation guide](../../../../docs/content/docs/integrations/orms/index.mdx) for the other integrations.
14
+
15
+
16
+ ## Usage
17
+
18
+ ```ts
19
+ import { sqliteTable, integer, text } from 'drizzle-orm/sqlite-core'
20
+ import { open } from 'nitro-sqlite'
21
+ import { drizzle } from 'nitro-sqlite-drizzle'
22
+
23
+ const users = sqliteTable('users', {
24
+ id: integer('id').primaryKey(),
25
+ name: text('name').notNull(),
26
+ })
27
+
28
+ const db = drizzle(open({ name: 'app.sqlite' }))
29
+
30
+ await db.insert(users).values({ id: 1, name: 'Ada' })
31
+ const rows = await db.select().from(users)
32
+ ```
33
+
34
+ Every query is asynchronous. Inside `db.transaction()`, run queries through `tx`: a query awaited through `db` waits for the transaction and never completes.
35
+
36
+ See the [Drizzle ORM integration guide](../../../../docs/content/docs/integrations/orms/drizzle.mdx) for migrations, `useMigrations`, and transactions.
37
+
38
+
39
+ ## Migrations
40
+
41
+ SQLite schema changes are SQL statements. Drizzle Kit bundles them with an ordered
42
+ journal, and the driver records each completed migration in `__drizzle_migrations`.
43
+ Pending migrations run in one transaction. A failure rolls them back together.
44
+
45
+ Generate a bundled `migrations.js` module with Drizzle Kit, then pass that module
46
+ to the driver. Configure your app's bundler to import its `.sql` files as strings.
47
+
48
+ ```ts
49
+ import { migrate } from 'nitro-sqlite-drizzle'
50
+ import migrations from './drizzle/migrations'
51
+
52
+ await migrate(db, migrations)
53
+ ```
54
+
55
+ In a React component, `useMigrations(db, migrations)` returns `{ success, error }`.
56
+ Wait for `success` before rendering components that query the migrated schema.
57
+ Changing the database or migration bundle resets the hook's state. Migrations
58
+ already queued still finish after a component unmounts.
59
+
60
+ ```tsx
61
+ import { useMigrations } from 'nitro-sqlite-drizzle'
62
+
63
+ function DatabaseGate() {
64
+ const { success, error } = useMigrations(db, migrations)
65
+ if (error) throw error
66
+ if (!success) return null
67
+ return <AppContent />
68
+ }
69
+ ```
70
+
71
+ Calls to `migrate` and `useMigrations` sharing a connection run in sequence.
72
+ Closing the connection remains the caller's responsibility. Close it only after
73
+ all queries, transactions, and migrations finish.
74
+
75
+ ## Transactions and results
76
+
77
+ Use the callback's `tx` handle for every query inside a transaction, and await
78
+ nested transactions before using their parent again. Nested transactions use
79
+ SQLite savepoints. An escaped callback error rolls back its changes. Transaction
80
+ handles and their prepared queries reject after their callback ends.
81
+
82
+ Drizzle selected fields decode positional SQLite rows, so joins preserve columns
83
+ with repeated names. Queries without selected fields return objects keyed by
84
+ column name. `run()` returns the native raw result with `rowsAffected`, optional
85
+ `insertId`, `columnNames`, and positional `rows`. Binary views used as parameters
86
+ bind only their own bytes, rather than the entire backing buffer.
87
+
88
+ This driver supports Drizzle ORM 0.45.x. It uses asynchronous queries and does not
89
+ own or close the supplied SQLite connection. Its prepared-query wrappers do not
90
+ retain native statements and need no disposal.
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "nitro-sqlite-drizzle",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "11.0.0-alpha.1",
4
+ "description": "Drizzle ORM driver for nitro-sqlite.",
5
+ "source": "./src/index.ts",
6
+ "main": "./src/index.ts",
7
+ "types": "./src/index.ts",
8
+ "files": [
9
+ "src",
10
+ "!**/__tests__",
11
+ "README.md",
12
+ "scripts",
13
+ "LICENSE"
14
+ ],
15
+ "scripts": {
16
+ "typecheck": "node scripts/materialize.mjs && tsc --noEmit",
17
+ "prepublishOnly": "node scripts/materialize.mjs && tsc --noEmit",
18
+ "materialize": "node scripts/materialize.mjs",
19
+ "prepack": "node scripts/materialize.mjs && tsc --noEmit",
20
+ "pack": "bun pm pack"
21
+ },
22
+ "keywords": [
23
+ "sqlite",
24
+ "drizzle",
25
+ "drizzle-orm",
26
+ "orm",
27
+ "ios",
28
+ "android",
29
+ "nitro-ui"
30
+ ],
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/margelo/nitro-sqlite.git",
34
+ "directory": "packages/integrations/nitro-ui/drizzle"
35
+ },
36
+ "author": "Christoph Pader",
37
+ "license": "MIT",
38
+ "publishConfig": {
39
+ "registry": "https://registry.npmjs.org/",
40
+ "access": "public"
41
+ },
42
+ "peerDependencies": {
43
+ "drizzle-orm": ">=0.45.4 <1.0.0",
44
+ "react": ">=17.0.0",
45
+ "nitro-sqlite": ">=11.0.0-0"
46
+ },
47
+ "devDependencies": {
48
+ "drizzle-orm": "0.45.4",
49
+ "typescript": "^5.8.3"
50
+ },
51
+ "exports": {
52
+ ".": {
53
+ "types": "./src/index.ts",
54
+ "default": "./src/index.ts"
55
+ },
56
+ "./driver": "./src/driver.ts",
57
+ "./session": "./src/session.ts",
58
+ "./migrator": "./src/migrator.ts",
59
+ "./package.json": "./package.json",
60
+ "./src/*.ts": "./src/*.ts",
61
+ "./src/*": "./src/*.ts"
62
+ },
63
+ "type": "module",
64
+ "module": "./src/index.ts"
65
+ }
@@ -0,0 +1,35 @@
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync } from 'node:fs'
2
+ import { dirname, join, resolve } from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
4
+
5
+ const packageDirectory = resolve(dirname(fileURLToPath(import.meta.url)), '..')
6
+ const sharedDirectory = resolve(
7
+ packageDirectory,
8
+ '../../../nitro-sqlite-drizzle-core/src',
9
+ )
10
+ const sourceDirectory = join(packageDirectory, 'src')
11
+ const packageName = JSON.parse(
12
+ readFileSync(join(packageDirectory, 'package.json'), 'utf8'),
13
+ ).name
14
+ const sqlitePackage = packageName.replace(/-drizzle$/, '')
15
+
16
+ // Packed packages retain their materialized source and do not need the workspace.
17
+ if (existsSync(sharedDirectory)) {
18
+ const { writeGeneratedFile } = await import(
19
+ '../../../../nitro-sqlite-core/scripts/materialize-sources.mjs'
20
+ )
21
+ mkdirSync(sourceDirectory, { recursive: true })
22
+ for (const file of readdirSync(sharedDirectory)) {
23
+ if (!file.endsWith('.ts')) continue
24
+ const content = readFileSync(
25
+ join(sharedDirectory, file),
26
+ 'utf8',
27
+ ).replaceAll('react-native-nitro-sqlite', sqlitePackage)
28
+ const destination = join(sourceDirectory, file)
29
+ writeGeneratedFile(destination, Buffer.from(content))
30
+ }
31
+ } else if (!existsSync(join(sourceDirectory, 'index.ts'))) {
32
+ throw new Error(
33
+ 'Drizzle source is missing. Build the package from the workspace before packing it.',
34
+ )
35
+ }
package/src/driver.ts ADDED
@@ -0,0 +1,87 @@
1
+ import {
2
+ createTableRelationsHelpers,
3
+ DefaultLogger,
4
+ entityKind,
5
+ extractTablesRelationalConfig,
6
+ } from 'drizzle-orm'
7
+ import type {
8
+ DrizzleConfig,
9
+ RelationalSchemaConfig,
10
+ TablesRelationalConfig,
11
+ } from 'drizzle-orm'
12
+ import { BaseSQLiteDatabase, SQLiteAsyncDialect } from 'drizzle-orm/sqlite-core'
13
+ import type {
14
+ NitroSQLiteConnection,
15
+ NitroSQLiteRawQueryResult,
16
+ } from 'nitro-sqlite'
17
+ import { NitroSQLiteSession } from './session'
18
+
19
+ /**
20
+ * Asynchronous Drizzle database backed by an open Nitro SQLite connection.
21
+ * Create it with {@link drizzle}; queries and prepared queries remain usable
22
+ * until you close the connection. The database does not own or close it.
23
+ * Use the callback's transaction handle for every query inside a transaction.
24
+ * @typeParam TSchema Tables and relations supplied in the Drizzle configuration.
25
+ */
26
+ export class NitroSQLiteDatabase<
27
+ TSchema extends Record<string, unknown> = Record<string, never>,
28
+ > extends BaseSQLiteDatabase<'async', NitroSQLiteRawQueryResult, TSchema> {
29
+ /** @internal Drizzle entity discriminator. */
30
+ static override readonly [entityKind]: string = 'NitroSQLiteDatabase'
31
+
32
+ /** Connection attached by {@link drizzle}. Close it after all queries finish. */
33
+ $client?: NitroSQLiteConnection
34
+ }
35
+
36
+ /**
37
+ * Create a Drizzle database whose queries run asynchronously on a Nitro SQLite connection.
38
+ * Creating the wrapper does not open, migrate, or close the connection.
39
+ * @typeParam TSchema Tables and relations supplied in `config.schema`.
40
+ * @param connection Connection returned by `open()`.
41
+ * @param config Drizzle options such as `schema`, `logger`, and `casing`.
42
+ * @returns A database whose `$client` is the supplied connection.
43
+ * @throws If Drizzle cannot read the supplied schema configuration.
44
+ * Query promises reject on binding, SQLite, or closed-connection errors.
45
+ */
46
+ export function drizzle<
47
+ TSchema extends Record<string, unknown> = Record<string, never>,
48
+ >(
49
+ connection: NitroSQLiteConnection,
50
+ config: DrizzleConfig<TSchema> = {},
51
+ ): NitroSQLiteDatabase<TSchema> & { $client: NitroSQLiteConnection } {
52
+ const dialect = new SQLiteAsyncDialect({ casing: config.casing })
53
+ let logger
54
+ if (config.logger === true) {
55
+ logger = new DefaultLogger()
56
+ } else if (config.logger !== false) {
57
+ logger = config.logger
58
+ }
59
+
60
+ let schema: RelationalSchemaConfig<TablesRelationalConfig> | undefined
61
+ if (config.schema) {
62
+ const tablesConfig = extractTablesRelationalConfig(
63
+ config.schema,
64
+ createTableRelationsHelpers,
65
+ )
66
+ schema = {
67
+ fullSchema: config.schema,
68
+ schema: tablesConfig.tables,
69
+ tableNamesMap: tablesConfig.tableNamesMap,
70
+ }
71
+ }
72
+
73
+ const session = new NitroSQLiteSession(
74
+ connection,
75
+ connection,
76
+ dialect,
77
+ schema,
78
+ { logger },
79
+ )
80
+ const db = new NitroSQLiteDatabase(
81
+ 'async',
82
+ dialect,
83
+ session,
84
+ schema,
85
+ ) as NitroSQLiteDatabase<TSchema>
86
+ return Object.assign(db, { $client: connection })
87
+ }
@@ -0,0 +1,60 @@
1
+ // drizzle-orm 0.45 ships these at runtime but marks them internal, so its type declarations omit them.
2
+ /* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-shadow -- merged declarations must repeat drizzle-orm's type parameters */
3
+ import type {
4
+ AnyColumn,
5
+ ExtractTablesWithRelations,
6
+ SelectedFieldsOrdered,
7
+ TablesRelationalConfig,
8
+ } from 'drizzle-orm'
9
+ import type {
10
+ SQLiteAsyncDialect,
11
+ SQLiteSession,
12
+ SQLiteSyncDialect,
13
+ } from 'drizzle-orm/sqlite-core'
14
+
15
+ declare module 'drizzle-orm/utils' {
16
+ export function mapResultRow<TResult>(
17
+ columns: SelectedFieldsOrdered<AnyColumn>,
18
+ row: unknown[],
19
+ joinsNotNullableMap: Record<string, boolean> | undefined,
20
+ ): TResult
21
+ }
22
+
23
+ declare module 'drizzle-orm/sqlite-core/session' {
24
+ interface SQLitePreparedQuery<T extends PreparedQueryConfig> {
25
+ joinsNotNullableMap?: Record<string, boolean>
26
+ }
27
+
28
+ interface SQLiteSession<
29
+ TResultKind extends 'sync' | 'async',
30
+ TRunResult,
31
+ TFullSchema extends Record<string, unknown>,
32
+ TSchema extends TablesRelationalConfig,
33
+ > {
34
+ readonly dialect: {
35
+ sync: SQLiteSyncDialect
36
+ async: SQLiteAsyncDialect
37
+ }[TResultKind]
38
+ }
39
+ }
40
+
41
+ declare module 'drizzle-orm/sqlite-core/db' {
42
+ interface BaseSQLiteDatabase<
43
+ TResultKind extends 'sync' | 'async',
44
+ TRunResult,
45
+ TFullSchema extends Record<string, unknown> = Record<string, never>,
46
+ TSchema extends
47
+ TablesRelationalConfig = ExtractTablesWithRelations<TFullSchema>,
48
+ > {
49
+ readonly dialect: {
50
+ sync: SQLiteSyncDialect
51
+ async: SQLiteAsyncDialect
52
+ }[TResultKind]
53
+ readonly session: SQLiteSession<
54
+ TResultKind,
55
+ TRunResult,
56
+ TFullSchema,
57
+ TSchema
58
+ >
59
+ }
60
+ }
package/src/index.ts ADDED
@@ -0,0 +1,9 @@
1
+ export { drizzle, NitroSQLiteDatabase } from './driver'
2
+ export { migrate, useMigrations } from './migrator'
3
+ export type { MigrationConfig, MigrationState } from './migrator'
4
+ export {
5
+ NitroSQLitePreparedQuery,
6
+ NitroSQLiteSession,
7
+ NitroSQLiteTransaction,
8
+ } from './session'
9
+ export type { NitroSQLiteSessionOptions } from './session'
@@ -0,0 +1,124 @@
1
+ import { useEffect, useState } from 'react'
2
+ import type { MigrationMeta } from 'drizzle-orm/migrator'
3
+ import type { NitroSQLiteDatabase } from './driver'
4
+ import './drizzle-orm'
5
+
6
+ const pendingMigrations = new WeakMap<object, Promise<void>>()
7
+
8
+ /** Bundled SQL and journal metadata exported by drizzle-kit's `migrations.js`. */
9
+ export interface MigrationConfig {
10
+ /** Generated journal listing migrations in application order. */
11
+ journal: {
12
+ /** Migration indexes, creation timestamps, file tags, and statement-breakpoint settings. */
13
+ entries: { idx: number; when: number; tag: string; breakpoints: boolean }[]
14
+ }
15
+ /** SQL strings keyed by the journal index, such as `m0000`. */
16
+ migrations: Record<string, string>
17
+ }
18
+
19
+ /**
20
+ * Apply the migrations that drizzle-kit generated and that have not run on this database yet.
21
+ * Pending migrations run in one transaction and roll back together on failure.
22
+ * Calls sharing a connection wait for earlier calls before reading migration history.
23
+ * A failed call does not prevent later calls from retrying.
24
+ * @typeParam TSchema Tables and relations supplied to Drizzle.
25
+ * @param db Database returned by `drizzle()`.
26
+ * @param config The `migrations.js` module that drizzle-kit generates.
27
+ * @returns Resolves when all pending migrations finish.
28
+ * @throws Rejects if a journal entry has no SQL, or a query or transaction fails.
29
+ */
30
+ export async function migrate<TSchema extends Record<string, unknown>>(
31
+ db: NitroSQLiteDatabase<TSchema>,
32
+ config: MigrationConfig,
33
+ ): Promise<void> {
34
+ const connection = db.$client ?? db.session
35
+ const previous = pendingMigrations.get(connection) ?? Promise.resolve()
36
+ const pending = previous
37
+ .catch(() => undefined)
38
+ .then(() => db.dialect.migrate(readMigrationFiles(config), db.session))
39
+ pendingMigrations.set(connection, pending)
40
+
41
+ try {
42
+ await pending
43
+ } finally {
44
+ if (pendingMigrations.get(connection) === pending) {
45
+ pendingMigrations.delete(connection)
46
+ }
47
+ }
48
+ }
49
+
50
+ /** Result of the migration attempt for the hook's current inputs. */
51
+ export interface MigrationState {
52
+ /** True after all pending migrations finish successfully. */
53
+ success: boolean
54
+ /** Failure from the migration attempt; absent while pending or after success. */
55
+ error?: Error
56
+ }
57
+
58
+ /**
59
+ * Run {@linkcode migrate} on mount and when the database or migration bundle changes.
60
+ * Concurrent calls on the same connection are serialized, including Strict Mode
61
+ * effect replays. Results from earlier inputs or after unmount do not update state.
62
+ * Changing either input returns pending state immediately, before the effect runs.
63
+ * Queued and running migrations still finish after an input change or unmount.
64
+ * @typeParam TSchema Tables and relations supplied to Drizzle.
65
+ * @param db Database returned by `drizzle()`.
66
+ * @param migrations The `migrations.js` module that drizzle-kit generates.
67
+ * @returns `success` once the migrations finished, or the `error` they failed with.
68
+ */
69
+ export function useMigrations<TSchema extends Record<string, unknown>>(
70
+ db: NitroSQLiteDatabase<TSchema>,
71
+ migrations: MigrationConfig,
72
+ ): MigrationState {
73
+ const [state, setState] = useState<{
74
+ db: NitroSQLiteDatabase<TSchema>
75
+ migrations: MigrationConfig
76
+ result: MigrationState
77
+ }>({ db, migrations, result: { success: false } })
78
+
79
+ useEffect(() => {
80
+ let active = true
81
+ setState({ db, migrations, result: { success: false } })
82
+ migrate(db, migrations)
83
+ .then(() => {
84
+ if (active) setState({ db, migrations, result: { success: true } })
85
+ })
86
+ .catch((error: unknown) => {
87
+ if (active) {
88
+ setState({
89
+ db,
90
+ migrations,
91
+ result: {
92
+ success: false,
93
+ error: error instanceof Error ? error : new Error(String(error)),
94
+ },
95
+ })
96
+ }
97
+ })
98
+ return () => {
99
+ active = false
100
+ }
101
+ }, [db, migrations])
102
+
103
+ return state.db === db && state.migrations === migrations
104
+ ? state.result
105
+ : { success: false }
106
+ }
107
+
108
+ function readMigrationFiles({
109
+ journal,
110
+ migrations,
111
+ }: MigrationConfig): MigrationMeta[] {
112
+ return journal.entries.map((entry) => {
113
+ const query = migrations[`m${entry.idx.toString().padStart(4, '0')}`]
114
+ if (!query) {
115
+ throw new Error(`Missing migration: ${entry.tag}`)
116
+ }
117
+ return {
118
+ sql: query.split('--> statement-breakpoint'),
119
+ bps: entry.breakpoints,
120
+ folderMillis: entry.when,
121
+ hash: '',
122
+ }
123
+ })
124
+ }
package/src/session.ts ADDED
@@ -0,0 +1,501 @@
1
+ import { entityKind, fillPlaceholders, NoopLogger, sql } from 'drizzle-orm'
2
+ import type {
3
+ Logger,
4
+ Query,
5
+ RelationalSchemaConfig,
6
+ TablesRelationalConfig,
7
+ } from 'drizzle-orm'
8
+ import {
9
+ SQLitePreparedQuery,
10
+ SQLiteSession,
11
+ SQLiteTransaction,
12
+ } from 'drizzle-orm/sqlite-core'
13
+ import type {
14
+ PreparedQueryConfig,
15
+ SelectedFieldsOrdered,
16
+ SQLiteAsyncDialect,
17
+ SQLiteExecuteMethod,
18
+ SQLiteTransactionConfig,
19
+ } from 'drizzle-orm/sqlite-core'
20
+ import { mapResultRow } from 'drizzle-orm/utils'
21
+ import type {
22
+ NitroSQLiteConnection,
23
+ NitroSQLiteRawQueryResult,
24
+ SQLiteQueryParams,
25
+ Transaction,
26
+ } from 'nitro-sqlite'
27
+ import './drizzle-orm'
28
+
29
+ /** Logging configuration shared by a session and its transactions. */
30
+ export interface NitroSQLiteSessionOptions {
31
+ /** Receives SQL and bound parameters before execution. Omit to disable logging. */
32
+ logger?: Logger
33
+ }
34
+
35
+ /**
36
+ * Executes Drizzle queries through a Nitro SQLite connection or transaction.
37
+ * {@link drizzle} creates sessions for normal use. A session does not close its
38
+ * connection; a transaction-bound session is usable only within its callback.
39
+ * @typeParam TFullSchema Full schema object supplied to Drizzle.
40
+ * @typeParam TSchema Relational table configuration extracted from that schema.
41
+ */
42
+ export class NitroSQLiteSession<
43
+ TFullSchema extends Record<string, unknown>,
44
+ TSchema extends TablesRelationalConfig,
45
+ > extends SQLiteSession<
46
+ 'async',
47
+ NitroSQLiteRawQueryResult,
48
+ TFullSchema,
49
+ TSchema
50
+ > {
51
+ /** @internal Drizzle entity discriminator. */
52
+ static override readonly [entityKind]: string = 'NitroSQLiteSession'
53
+
54
+ private logger: Logger
55
+
56
+ /**
57
+ * Bind a session to an existing connection or active transaction.
58
+ * @param connection Open connection used to start managed transactions.
59
+ * @param client The connection, or the active transaction used for queries.
60
+ * @param dialect Asynchronous SQLite dialect used to compile queries.
61
+ * @param schema Relational schema configuration, or `undefined` when none was supplied.
62
+ * @param options Query logging options, inherited by transactions.
63
+ * @param assertActive Internal callback-scope check, run before executing queries.
64
+ */
65
+ constructor(
66
+ private connection: NitroSQLiteConnection,
67
+ // The connection, or the transaction handle while a transaction runs.
68
+ private client: NitroSQLiteConnection | Transaction,
69
+ dialect: SQLiteAsyncDialect,
70
+ private schema: RelationalSchemaConfig<TSchema> | undefined,
71
+ private options: NitroSQLiteSessionOptions = {},
72
+ private assertActive?: () => void,
73
+ ) {
74
+ super(dialect)
75
+ this.logger = options.logger ?? new NoopLogger()
76
+ }
77
+
78
+ /**
79
+ * Create a reusable query wrapper without preparing a native SQLite statement.
80
+ * @typeParam T Result types for the query's execution methods.
81
+ * @param query Compiled SQL and positional parameters, including placeholders.
82
+ * @param fields Ordered selected fields used to decode result rows.
83
+ * @param executeMethod Method invoked by the wrapper's `execute()` call.
84
+ * @param isResponseInArrayMode Whether Drizzle expects positional rows.
85
+ * @param customResultMapper Optional decoder for relational query results.
86
+ * @returns A wrapper bound to this session's client. It needs no disposal.
87
+ */
88
+ prepareQuery<T extends PreparedQueryConfig & { type: 'async' }>(
89
+ query: Query,
90
+ fields: SelectedFieldsOrdered | undefined,
91
+ executeMethod: SQLiteExecuteMethod,
92
+ isResponseInArrayMode: boolean,
93
+ customResultMapper?: (rows: unknown[][]) => unknown,
94
+ ): NitroSQLitePreparedQuery<T> {
95
+ return new NitroSQLitePreparedQuery(
96
+ this.client,
97
+ query,
98
+ this.logger,
99
+ fields,
100
+ executeMethod,
101
+ isResponseInArrayMode,
102
+ customResultMapper,
103
+ this.assertActive,
104
+ )
105
+ }
106
+
107
+ /** @internal Bind queries, including prepared queries, to one transaction callback's lifetime. */
108
+ withScope(
109
+ assertActive: () => void,
110
+ ): NitroSQLiteSession<TFullSchema, TSchema> {
111
+ return new NitroSQLiteSession(
112
+ this.connection,
113
+ this.client,
114
+ this.dialect,
115
+ this.schema,
116
+ this.options,
117
+ assertActive,
118
+ )
119
+ }
120
+
121
+ /**
122
+ * Hold the connection until an asynchronous transaction callback finishes.
123
+ * Await every query through `tx`; awaiting queries through the outer database
124
+ * waits for this transaction and deadlocks the callback.
125
+ * Await each nested transaction before starting another on the same handle or
126
+ * returning from the callback. Overlapping nested calls reject before running SQL.
127
+ * @typeParam T Callback result type.
128
+ * @param transaction Callback that commits on success and rolls back on failure.
129
+ * @param _config Accepted for Drizzle compatibility. `behavior` is ignored;
130
+ * the connection starts the transaction with `BEGIN`.
131
+ * @returns The callback result after the transaction commits.
132
+ * @throws Rejects with `NitroSQLiteError` on query, callback, or finalization failure.
133
+ * An uncaught `tx.rollback()` rejects with the message `Rollback`.
134
+ */
135
+ override async transaction<T>(
136
+ transaction: (
137
+ tx: NitroSQLiteTransaction<TFullSchema, TSchema>,
138
+ ) => Promise<T>,
139
+ _config?: SQLiteTransactionConfig,
140
+ ): Promise<T> {
141
+ return this.connection.transaction(async (nitroTransaction) => {
142
+ const session = new NitroSQLiteSession<TFullSchema, TSchema>(
143
+ this.connection,
144
+ nitroTransaction,
145
+ this.dialect,
146
+ this.schema,
147
+ this.options,
148
+ )
149
+ const tx = new NitroSQLiteTransaction<TFullSchema, TSchema>(
150
+ 'async',
151
+ this.dialect,
152
+ session,
153
+ this.schema,
154
+ )
155
+ return tx.runCallback(transaction)
156
+ })
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Drizzle transaction handle supplied to a transaction callback.
162
+ * Use it for queries and nested transactions only while the callback is active.
163
+ * Await each nested call before using its parent handle again. Descendants must
164
+ * nest through the handle supplied to their own callback, not an ancestor handle.
165
+ * Queries and prepared queries through a child reject after its callback ends,
166
+ * even while the parent transaction remains active.
167
+ * Inherited `rollback()` throws Drizzle's `TransactionRollbackError`; an error
168
+ * escaping the outer callback becomes a `NitroSQLiteError` with message `Rollback`.
169
+ * @typeParam TFullSchema Full schema object supplied to Drizzle.
170
+ * @typeParam TSchema Relational table configuration extracted from that schema.
171
+ */
172
+ export class NitroSQLiteTransaction<
173
+ TFullSchema extends Record<string, unknown>,
174
+ TSchema extends TablesRelationalConfig,
175
+ > extends SQLiteTransaction<
176
+ 'async',
177
+ NitroSQLiteRawQueryResult,
178
+ TFullSchema,
179
+ TSchema
180
+ > {
181
+ /** @internal Drizzle entity discriminator. */
182
+ static override readonly [entityKind]: string = 'NitroSQLiteTransaction'
183
+
184
+ private nestedState:
185
+ | { kind: 'ready' | 'closed' }
186
+ | { kind: 'running'; completion: Promise<unknown> } = { kind: 'ready' }
187
+
188
+ // Savepoint failures leave the stack uncertain, so the outer transaction must fail.
189
+ private context: { failure?: { error: unknown } } = {}
190
+
191
+ /**
192
+ * Bind a Drizzle transaction to its own callback scope.
193
+ * @param resultType Drizzle's asynchronous execution mode.
194
+ * @param dialect SQLite SQL compiler.
195
+ * @param transactionSession Session using the outer managed transaction's connection.
196
+ * @param schema Relational schema configuration, if supplied.
197
+ * @param nestedIndex Savepoint depth, starting at zero for the outer transaction.
198
+ */
199
+ constructor(
200
+ resultType: 'async',
201
+ dialect: SQLiteAsyncDialect,
202
+ private readonly transactionSession: NitroSQLiteSession<
203
+ TFullSchema,
204
+ TSchema
205
+ >,
206
+ schema: RelationalSchemaConfig<TSchema> | undefined,
207
+ nestedIndex = 0,
208
+ ) {
209
+ super(
210
+ resultType,
211
+ dialect,
212
+ transactionSession.withScope(() => {
213
+ if (this.nestedState.kind === 'closed') {
214
+ throw new Error(
215
+ 'Cannot execute query on a finished transaction handle.',
216
+ )
217
+ }
218
+ }),
219
+ schema,
220
+ nestedIndex,
221
+ )
222
+ }
223
+
224
+ /**
225
+ * Run a nested transaction using a SQLite savepoint.
226
+ * Only one nested call can be active on this handle. Await it before starting
227
+ * a sibling or using the parent handle. To nest further, use the child handle.
228
+ * Overlap rejects immediately without invoking the callback or executing SQL;
229
+ * calls are not queued because an ancestor call could wait on its own descendant.
230
+ * @typeParam T Nested callback result type.
231
+ * @param transaction Callback whose changes roll back to the savepoint if it throws.
232
+ * @returns The callback result after releasing the savepoint.
233
+ * @throws Rejects on overlap, a finished handle, or a callback that returns with
234
+ * an active child. Callback errors roll back and release the savepoint, then
235
+ * reject with the original error. Catch these errors in the parent to continue.
236
+ * Savepoint failures also force the outer transaction to roll back, even if
237
+ * caught. A cleanup failure preserves both errors in an AggregateError cause.
238
+ */
239
+ override async transaction<T>(
240
+ transaction: (
241
+ tx: NitroSQLiteTransaction<TFullSchema, TSchema>,
242
+ ) => Promise<T>,
243
+ ): Promise<T> {
244
+ if (this.nestedState.kind !== 'ready') {
245
+ throw new Error(
246
+ this.nestedState.kind === 'closed'
247
+ ? 'Cannot start a nested transaction on a finished transaction handle.'
248
+ : 'Overlapping nested transactions are not supported. Await the previous transaction call on this handle; use the child handle for deeper nesting.',
249
+ )
250
+ }
251
+ if (this.context.failure) throw this.context.failure.error
252
+
253
+ // Reserve the handle before SQL logging or execution can reenter caller code.
254
+ const completion = Promise.resolve().then(() =>
255
+ this.runNestedTransaction(transaction),
256
+ )
257
+ this.nestedState = { kind: 'running', completion }
258
+ try {
259
+ return await completion
260
+ } finally {
261
+ if (this.nestedState.kind === 'running') {
262
+ this.nestedState = { kind: 'ready' }
263
+ }
264
+ }
265
+ }
266
+
267
+ /** @internal Close the callback scope before its savepoint or transaction ends. */
268
+ async runCallback<T>(
269
+ callback: (tx: NitroSQLiteTransaction<TFullSchema, TSchema>) => Promise<T>,
270
+ ): Promise<T> {
271
+ try {
272
+ const result = await callback(this)
273
+ await this.finishCallback()
274
+ if (this.context.failure) throw this.context.failure.error
275
+ return result
276
+ } catch (error) {
277
+ try {
278
+ await this.finishCallback()
279
+ } catch (cleanupError) {
280
+ throw new Error(
281
+ 'Transaction callback and nested transaction cleanup failed',
282
+ {
283
+ cause: new AggregateError([error, cleanupError]),
284
+ },
285
+ )
286
+ }
287
+ throw error
288
+ }
289
+ }
290
+
291
+ private async finishCallback(): Promise<void> {
292
+ const state = this.nestedState
293
+ this.nestedState = { kind: 'closed' }
294
+ if (state.kind === 'running') {
295
+ // Drain descendants before the parent rolls back or releases their savepoints.
296
+ const [outcome] = await Promise.allSettled([state.completion])
297
+ throw new Error(
298
+ 'Await every nested transaction call before its parent callback finishes.',
299
+ {
300
+ cause: outcome?.status === 'rejected' ? outcome.reason : undefined,
301
+ },
302
+ )
303
+ }
304
+ }
305
+
306
+ private async runNestedTransaction<T>(
307
+ transaction: (
308
+ tx: NitroSQLiteTransaction<TFullSchema, TSchema>,
309
+ ) => Promise<T>,
310
+ ): Promise<T> {
311
+ const savepointName = `sp${this.nestedIndex}`
312
+ const tx = new NitroSQLiteTransaction<TFullSchema, TSchema>(
313
+ 'async',
314
+ this.dialect,
315
+ this.transactionSession,
316
+ this.schema,
317
+ this.nestedIndex + 1,
318
+ )
319
+ tx.context = this.context
320
+ await this.runSavepoint(`savepoint ${savepointName}`)
321
+ try {
322
+ const result = await tx.runCallback(transaction)
323
+ await this.runSavepoint(`release savepoint ${savepointName}`)
324
+ return result
325
+ } catch (error) {
326
+ try {
327
+ await this.runSavepoint(`rollback to savepoint ${savepointName}`)
328
+ await this.runSavepoint(`release savepoint ${savepointName}`)
329
+ } catch (cleanupError) {
330
+ throw new Error('Nested transaction rollback or release failed', {
331
+ cause: new AggregateError([error, cleanupError]),
332
+ })
333
+ }
334
+ throw error
335
+ }
336
+ }
337
+
338
+ private async runSavepoint(query: string): Promise<void> {
339
+ try {
340
+ await this.transactionSession.run(sql.raw(query))
341
+ } catch (error) {
342
+ this.context.failure ??= { error }
343
+ throw error
344
+ }
345
+ }
346
+ }
347
+
348
+ /**
349
+ * Reusable compiled Drizzle query with asynchronous execution and row decoding.
350
+ * Each execution binds fresh placeholder values. No native prepared statement is
351
+ * retained, so no finalization is needed. A transaction-bound query must finish
352
+ * before its callback returns; other queries require an open connection.
353
+ * @typeParam T Result types supplied by Drizzle for each execution method.
354
+ */
355
+ export class NitroSQLitePreparedQuery<
356
+ T extends PreparedQueryConfig = PreparedQueryConfig,
357
+ > extends SQLitePreparedQuery<{
358
+ type: 'async'
359
+ run: NitroSQLiteRawQueryResult
360
+ all: T['all']
361
+ get: T['get']
362
+ values: T['values']
363
+ execute: T['execute']
364
+ }> {
365
+ /** @internal Drizzle entity discriminator. */
366
+ static override readonly [entityKind]: string = 'NitroSQLitePreparedQuery'
367
+
368
+ /**
369
+ * Create a query wrapper without executing SQL.
370
+ * @param client Open connection or active transaction used for execution.
371
+ * @param query Compiled SQL and positional parameters, including placeholders.
372
+ * @param logger Receives each query before execution.
373
+ * @param fields Ordered selected fields used to decode result rows.
374
+ * @param executeMethod Method invoked by `execute()`.
375
+ * @param _isResponseInArrayMode Whether Drizzle expects positional rows.
376
+ * @param customResultMapper Optional decoder for relational query results.
377
+ * @param assertActive Internal transaction callback-scope check, run at execution.
378
+ */
379
+ constructor(
380
+ private client: NitroSQLiteConnection | Transaction,
381
+ query: Query,
382
+ private logger: Logger,
383
+ private fields: SelectedFieldsOrdered | undefined,
384
+ executeMethod: SQLiteExecuteMethod,
385
+ private _isResponseInArrayMode: boolean,
386
+ private customResultMapper?: (rows: unknown[][]) => unknown,
387
+ private assertActive?: () => void,
388
+ ) {
389
+ super('async', executeMethod, query)
390
+ }
391
+
392
+ /**
393
+ * Execute SQL and return Nitro SQLite's raw result, including affected rows.
394
+ * @param placeholderValues Values for every named placeholder in the query.
395
+ * @returns Raw positional rows, column names, and execution metadata.
396
+ * @throws Rejects on missing placeholders, invalid bindings, SQLite errors,
397
+ * or a closed connection or finalized transaction.
398
+ */
399
+ async run(
400
+ placeholderValues?: Record<string, unknown>,
401
+ ): Promise<NitroSQLiteRawQueryResult> {
402
+ return this.client.executeRawAsync(
403
+ this.query.sql,
404
+ this.bindParams(placeholderValues),
405
+ )
406
+ }
407
+
408
+ /**
409
+ * Execute SQL and decode every row with the selected fields or custom mapper.
410
+ * Without either, rows are objects keyed by SQLite column names.
411
+ * @param placeholderValues Values for every named placeholder in the query.
412
+ * @returns All decoded rows, or the custom mapper's result.
413
+ * @throws Rejects on binding, query, or decoding errors, including an inactive client.
414
+ */
415
+ async all(placeholderValues?: Record<string, unknown>): Promise<T['all']> {
416
+ const { fields, customResultMapper } = this
417
+ if (!fields && !customResultMapper) {
418
+ const result = await this.client.executeAsync(
419
+ this.query.sql,
420
+ this.bindParams(placeholderValues),
421
+ )
422
+ return result.results
423
+ }
424
+
425
+ const rows = (await this.values(placeholderValues)) as unknown[][]
426
+ if (customResultMapper) {
427
+ return customResultMapper(rows) as T['all']
428
+ }
429
+ return rows.map((row) =>
430
+ mapResultRow(fields!, row, this.joinsNotNullableMap),
431
+ )
432
+ }
433
+
434
+ /**
435
+ * Execute SQL and decode its first row.
436
+ * @param placeholderValues Values for every named placeholder in the query.
437
+ * @returns The first decoded row, `undefined` if empty, or the custom mapper's result.
438
+ * @throws Rejects on binding, query, or decoding errors, including an inactive client.
439
+ */
440
+ async get(placeholderValues?: Record<string, unknown>): Promise<T['get']> {
441
+ const { fields, customResultMapper } = this
442
+ if (!fields && !customResultMapper) {
443
+ const result = await this.client.executeAsync(
444
+ this.query.sql,
445
+ this.bindParams(placeholderValues),
446
+ )
447
+ return result.results[0]
448
+ }
449
+
450
+ const rows = (await this.values(placeholderValues)) as unknown[][]
451
+ const row = rows[0]
452
+ if (!row) {
453
+ return undefined
454
+ }
455
+ if (customResultMapper) {
456
+ return customResultMapper(rows) as T['get']
457
+ }
458
+ return mapResultRow(fields!, row, this.joinsNotNullableMap)
459
+ }
460
+
461
+ /**
462
+ * Execute SQL and return positional rows without Drizzle field decoding.
463
+ * @param placeholderValues Values for every named placeholder in the query.
464
+ * @returns Row arrays in SQLite's selected-column order.
465
+ * @throws Rejects on binding or query errors, including an inactive client.
466
+ */
467
+ async values(
468
+ placeholderValues?: Record<string, unknown>,
469
+ ): Promise<T['values']> {
470
+ const result = await this.client.executeRawAsync(
471
+ this.query.sql,
472
+ this.bindParams(placeholderValues),
473
+ )
474
+ return result.rows
475
+ }
476
+
477
+ /** @internal */
478
+ isResponseInArrayMode(): boolean {
479
+ return this._isResponseInArrayMode
480
+ }
481
+
482
+ private bindParams(
483
+ placeholderValues: Record<string, unknown> | undefined,
484
+ ): SQLiteQueryParams {
485
+ const params = fillPlaceholders(
486
+ this.query.params,
487
+ placeholderValues ?? {},
488
+ ).map((value) =>
489
+ ArrayBuffer.isView(value)
490
+ ? new Uint8Array(
491
+ value.buffer,
492
+ value.byteOffset,
493
+ value.byteLength,
494
+ ).slice().buffer
495
+ : value,
496
+ )
497
+ this.logger.logQuery(this.query.sql, params)
498
+ this.assertActive?.()
499
+ return params as SQLiteQueryParams
500
+ }
501
+ }