Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ To open another connection to the same file, use `open({ name: 'myDb.sqlite', co
| Method | Sync | Async | Description |
|--------|------|-------|-------------|
| **Execute** | `db.execute(query, params?)` | `db.executeAsync(query, params?)` | Run a single SQL statement. |
| **Prepared statement** | `db.prepare(query)` | Statement `executeAsync(params?)` | Prepare once and execute repeatedly with different parameters. |
| **Batch** | `db.executeBatch(commands)` | `db.executeBatchAsync(commands)` | Run multiple statements in one transaction. |
| **Load file** | `db.loadFile(path)` | `db.loadFileAsync(path)` | Execute SQL from a file. |
| **Transaction** | — | `db.transaction(async (tx) => { ... })` | Run multiple statements in a transaction (async only). |
Expand Down Expand Up @@ -160,6 +161,21 @@ const { rowsAffected } = db.executeBatch(commands)
// Or: await db.executeBatchAsync(commands)
```

## Prepared statements

Use `db.prepare()` when the same SQL statement is executed repeatedly with different parameters. Call `finalize()` once the statement is no longer needed, and always finalize it before closing its database connection.

```typescript
const insertUser = db.prepare(
'INSERT INTO users (id, name) VALUES (?, ?)',
)

insertUser.execute([1, 'Ada'])
await insertUser.executeAsync([2, 'Grace'])

insertUser.finalize()
```

# Column metadata

When you need column types or names for the result set, use the `metadata` field on the query result. Keys are column names; values include `name`, `type` (e.g. from `ColumnType`), and `index`.
Expand Down
5 changes: 5 additions & 0 deletions example/tests/unit/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { setupTestDb } from './common'
import registerExecuteUnitTests from './specs/operations/execute.spec'
import registerTransactionUnitTests from './specs/operations/transaction.spec'
import registerExecuteBatchUnitTests from './specs/operations/executeBatch.spec'
import registerPreparedStatementUnitTests from './specs/operations/preparedStatement.spec'
import registerTypeORMUnitTestsSpecs from './specs/typeorm.spec'
import registerDatabaseQueueUnitTests from './specs/DatabaseQueue.spec'
import registerSqliteVecUnitTestsSpecs from './specs/sqlite-vec.spec'
Expand All @@ -15,6 +16,10 @@ export function registerUnitTests() {
describe('operations/execute.spec.ts', registerExecuteUnitTests)
describe('operations/transaction.spec.ts', registerTransactionUnitTests)
describe('operations/executeBatch.spec.ts', registerExecuteBatchUnitTests)
describe(
'operations/preparedStatement.spec.ts',
registerPreparedStatementUnitTests,
)
describe('DatabaseQueue.spec.ts', registerDatabaseQueueUnitTests)
describe('Connections.spec.ts', registerConnectionUnitTests)
describe('benchmarkDatabase.spec.ts', registerBenchmarkDatabaseUnitTests)
Expand Down
125 changes: 125 additions & 0 deletions example/tests/unit/specs/operations/preparedStatement.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import {
chance,
expect,
isNitroSQLiteError,
TEST_ERROR_CODES,
} from '@tests/unit/common'
import { describe, it } from '@tests/TestApi'
import { testDb } from '@tests/db'

export default function registerPreparedStatementUnitTests() {
describe('prepared statements', () => {
it('reuses one statement with different parameter values', () => {
const insert = testDb.prepare(
'INSERT INTO User (id, name, age, networth) VALUES (?, ?, ?, ?)',
)
const firstUser = {
id: chance.integer(),
name: chance.name(),
age: chance.integer(),
networth: chance.floating(),
}
const secondUser = {
id: chance.integer(),
name: chance.name(),
age: chance.integer(),
networth: chance.floating(),
}

expect(insert.isFinalized).toBe(false)
expect(
insert.execute([
firstUser.id,
firstUser.name,
firstUser.age,
firstUser.networth,
]).rowsAffected,
).toBe(1)
expect(
insert.execute([
secondUser.id,
secondUser.name,
secondUser.age,
secondUser.networth,
]).rowsAffected,
).toBe(1)

const select = testDb.prepare('SELECT * FROM User WHERE id = ?')
expect(select.execute([firstUser.id]).rows._array).toEqual([firstUser])
expect(select.execute([secondUser.id]).rows._array).toEqual([secondUser])

insert.finalize()
select.finalize()
expect(insert.isFinalized).toBe(true)
expect(select.isFinalized).toBe(true)
})

it('executes asynchronously', async () => {
const id = chance.integer()
const statement = testDb.prepare(
'INSERT INTO User (id, name, age, networth) VALUES (?, ?, ?, ?)',
)

const result = await statement.executeAsync([
id,
chance.name(),
chance.integer(),
chance.floating(),
])

expect(result.rowsAffected).toBe(1)
expect(
testDb.execute('SELECT * FROM User WHERE id = ?', [id]).rows.length,
).toBe(1)
statement.finalize()
})

it('can run again after an execution error', () => {
const statement = testDb.prepare(
'INSERT INTO User (id, name, age, networth) VALUES (?, ?, ?, ?)',
)
statement.execute([42, 'Ada', 37, 1])

try {
statement.execute([42, 'Duplicate', 37, 1])
throw new Error('Expected duplicate key to fail')
} catch (error) {
expect(isNitroSQLiteError(error)).toBe(true)
}

expect(statement.execute([43, 'Grace', 38, 2]).rowsAffected).toBe(1)
statement.finalize()
})

it('rejects execution after finalization', () => {
const statement = testDb.prepare('SELECT * FROM User')
statement.finalize()

try {
statement.execute()
throw new Error('Expected execution to throw after finalization')
} catch (error) {
expect(isNitroSQLiteError(error)).toBe(true)
if (isNitroSQLiteError(error)) {
expect(error.message).toContain(
'Prepared statement has been finalized',
)
}
}
})

it('rejects a query that contains no SQL', () => {
for (const query of ['', '-- just a comment']) {
try {
testDb.prepare(query)
throw new Error(TEST_ERROR_CODES.EXPECT_NITRO_SQLITE_ERROR)
} catch (error) {
if (!isNitroSQLiteError(error)) throw error
expect(error.message).toContain(
'Query does not contain any SQL statement',
)
}
}
})
})
}
Loading
Loading