@pikku/kysely-node-sqlite 0.12.5 → 0.12.8

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/CHANGELOG.md CHANGED
@@ -1,5 +1,97 @@
1
1
  # @pikku/kysely-node-sqlite
2
2
 
3
+ ## 0.12.8
4
+
5
+ ### Patch Changes
6
+
7
+ - 4c7a1b5: Run the monorepo's own scripts through bun instead of yarn. What moves is the
8
+ package manager each package's `prepublishOnly` and build scripts invoke, plus
9
+ the two manifest fixes bun needs to resolve the tree: `uWebSockets.js` is
10
+ declared with an explicit `github:` specifier, and `@pikku/uws-handler` marks
11
+ its `uWebSockets.js` peer optional so a bun install of a consumer that brings
12
+ its own uWS app does not try to fetch it from the registry.
13
+
14
+ Three published behaviours change, all of them cases where an isolated
15
+ `node_modules` or bun as the runtime had been papered over by yarn's hoisting:
16
+
17
+ - `@pikku/migrator-sql` turns foreign keys on when it opens a sqlite database
18
+ through bun. `node:sqlite` enforces them by default and `bun:sqlite` does not,
19
+ which silently turned every `ON DELETE CASCADE` into a no-op under
20
+ `bunx --bun pikku`.
21
+ - `@pikku/cli` resolves a deploy provider against the project being deployed
22
+ rather than against wherever the CLI itself is installed, which is what its
23
+ own "is not installed" error asks the user to arrange.
24
+ - `@pikku/cli` treats a specifier a runtime hands straight back — bun does this
25
+ for the modules it implements itself — as not resolved from the project, so
26
+ it falls back rather than loading the runtime's own copy.
27
+
28
+ - Updated dependencies [4c7a1b5]
29
+ - @pikku/core@0.12.108
30
+ - @pikku/kysely@0.13.25
31
+ - @pikku/kysely-sqlite@0.12.14
32
+
33
+ ## 0.12.7
34
+
35
+ ### Patch Changes
36
+
37
+ - 746ed6a: fix: one coercion plugin, not three
38
+
39
+ The Kysely coercion plugin existed in three copies — the CLI's local database,
40
+ `@pikku/kysely-node-sqlite` and `@pikku/kysely-bun-sqlite` — and all three had
41
+ drifted apart. Only the CLI's resolved a column against the tables the query
42
+ actually named, so two tables that disagree on the kind of a same-named column
43
+ coerced correctly in local development and silently did not at runtime; only
44
+ bun's dropped a genuinely ambiguous column instead of letting the last table
45
+ processed win.
46
+
47
+ The single implementation now lives in `@pikku/kysely`, which all three already
48
+ depended on, and keeps both behaviours: table-qualified resolution first, an
49
+ ambiguity-safe bare-name fallback second.
50
+
51
+ `ColumnKind` — the value type of the generated `coercion.gen.ts` — is
52
+ `'date' | 'bool' | 'json'`. The CLI's fourth member, `uuid`, was never a
53
+ coercion kind: the codegen excludes it from the map by construction, because a
54
+ UUID is a string in both Postgres and SQLite. It is now `AnnotationKind` in the
55
+ CLI, the union a column may declare in `db/annotations.ts`, of which
56
+ `ColumnKind` is the coercible subset.
57
+
58
+ `@pikku/cli` also drops its unused dependency on the Node-only
59
+ `@pikku/kysely-node-sqlite`.
60
+
61
+ - Updated dependencies [5a1a962]
62
+ - Updated dependencies [746ed6a]
63
+ - @pikku/core@0.12.86
64
+ - @pikku/kysely@0.13.18
65
+
66
+ ## 0.12.6
67
+
68
+ ### Patch Changes
69
+
70
+ - 6eef0a0: Bump every dependency to its latest compatible minor/patch across the monorepo.
71
+ - Updated dependencies [7722ceb]
72
+ - Updated dependencies [375c1ff]
73
+ - Updated dependencies [02a70cd]
74
+ - Updated dependencies [aeef159]
75
+ - Updated dependencies [a281de6]
76
+ - Updated dependencies [266e3bc]
77
+ - Updated dependencies [02a70cd]
78
+ - Updated dependencies [786dae5]
79
+ - Updated dependencies [6eef0a0]
80
+ - Updated dependencies [3561d67]
81
+ - Updated dependencies [a91c433]
82
+ - Updated dependencies [02a70cd]
83
+ - Updated dependencies [9537f74]
84
+ - Updated dependencies [2b57ca8]
85
+ - Updated dependencies [266e3bc]
86
+ - Updated dependencies [9fce0f1]
87
+ - Updated dependencies [83683a0]
88
+ - Updated dependencies [456c88b]
89
+ - Updated dependencies [456c88b]
90
+ - Updated dependencies [c127273]
91
+ - @pikku/core@0.12.85
92
+ - @pikku/kysely@0.13.17
93
+ - @pikku/kysely-sqlite@0.12.13
94
+
3
95
  ## 0.12.5
4
96
 
5
97
  ### Patch Changes
@@ -2,4 +2,4 @@ export { NodeSqliteDatabase } from './node-sqlite-adapter.js';
2
2
  export { createNodeSqliteKysely, type CreateNodeSqliteKyselyOptions, } from './create-node-sqlite-kysely.js';
3
3
  export { registerSqliteFunctions } from './register-functions.js';
4
4
  export { SqliteFunctionsUnsupportedError, type SqliteFunctionMap, } from '@pikku/kysely-sqlite';
5
- export { createCoercionPlugin, type ColumnKind, type CreateCoercionPluginOptions, } from './coercion-plugin.js';
5
+ export { createCoercionPlugin, type ColumnKind, type CoercionMap, type CreateCoercionPluginOptions, } from '@pikku/kysely';
package/dist/src/index.js CHANGED
@@ -2,4 +2,4 @@ export { NodeSqliteDatabase } from './node-sqlite-adapter.js';
2
2
  export { createNodeSqliteKysely, } from './create-node-sqlite-kysely.js';
3
3
  export { registerSqliteFunctions } from './register-functions.js';
4
4
  export { SqliteFunctionsUnsupportedError, } from '@pikku/kysely-sqlite';
5
- export { createCoercionPlugin, } from './coercion-plugin.js';
5
+ export { createCoercionPlugin, } from '@pikku/kysely';
@@ -16,6 +16,22 @@ function coerce(v) {
16
16
  return JSON.stringify(v);
17
17
  return v;
18
18
  }
19
+ /**
20
+ * Whether a statement returns rows. node:sqlite's StatementSync has no `reader`
21
+ * flag (better-sqlite3, which Kysely's SqliteDialect was written against, does),
22
+ * so the value has to come from the SQL: a writer is run through `.run()` for
23
+ * its `changes`/`lastInsertRowid`, a reader through `.all()` for its rows, and
24
+ * getting it wrong silently drops whichever half the caller wanted.
25
+ *
26
+ * The list is wider than SELECT because Kysely's own SQLite introspector asks
27
+ * for columns through a CTE over `pragma_table_info`, so a statement that opens
28
+ * with WITH is a reader too — treating it as a writer reports every table as
29
+ * having no columns.
30
+ */
31
+ function isReaderSql(sql) {
32
+ return (/^\s*(select|with|pragma|values|explain)\b/i.test(sql) ||
33
+ /\breturning\b/i.test(sql));
34
+ }
19
35
  /**
20
36
  * Wraps node:sqlite's DatabaseSync as Kysely's SqliteDatabase. The shapes
21
37
  * are close but not identical: node:sqlite's Statement methods take
@@ -24,9 +40,10 @@ function coerce(v) {
24
40
  */
25
41
  class NodeSqliteStatement {
26
42
  stmt;
27
- reader = true;
28
- constructor(stmt) {
43
+ reader;
44
+ constructor(stmt, reader) {
29
45
  this.stmt = stmt;
46
+ this.reader = reader;
30
47
  }
31
48
  all(parameters) {
32
49
  return this.stmt.all(...parameters.map(coerce));
@@ -50,7 +67,7 @@ export class NodeSqliteDatabase {
50
67
  this.db = db;
51
68
  }
52
69
  prepare(sql) {
53
- return new NodeSqliteStatement(this.db.prepare(sql));
70
+ return new NodeSqliteStatement(this.db.prepare(sql), isReaderSql(sql));
54
71
  }
55
72
  close() {
56
73
  this.db.close();
package/package.json CHANGED
@@ -1,6 +1,11 @@
1
1
  {
2
2
  "name": "@pikku/kysely-node-sqlite",
3
- "version": "0.12.5",
3
+ "version": "0.12.8",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "git+https://github.com/pikkujs/pikku.git",
7
+ "directory": "packages/services/kysely-node-sqlite"
8
+ },
4
9
  "description": "Kysely driver for Pikku backed by the built-in node:sqlite module",
5
10
  "author": "yasser.fadl@gmail.com",
6
11
  "license": "MIT",
@@ -14,24 +19,23 @@
14
19
  "test": "bash run-tests.sh",
15
20
  "test:watch": "bash run-tests.sh --watch",
16
21
  "test:coverage": "bash run-tests.sh --coverage",
17
- "prepublishOnly": "yarn build"
22
+ "prepublishOnly": "bun run build"
18
23
  },
19
24
  "engines": {
20
25
  "node": ">=22.10"
21
26
  },
22
27
  "dependencies": {
23
- "@pikku/kysely": "^0.13.15",
24
- "@pikku/kysely-sqlite": "^0.12.11",
25
- "kysely": "^0.29.0"
28
+ "@pikku/kysely": "^0.13.25",
29
+ "@pikku/kysely-sqlite": "^0.12.14",
30
+ "kysely": "^0.29.5"
26
31
  },
27
32
  "peerDependencies": {
28
- "@pikku/core": "^0.12.82"
33
+ "@pikku/core": "^0.12.108"
29
34
  },
30
35
  "devDependencies": {
31
- "@pikku/core": "^0.12.82",
36
+ "@pikku/core": "^0.12.108",
32
37
  "@types/node": "^22",
33
- "tsx": "^4.19.2",
34
- "typescript": "^6.0.3"
38
+ "tsx": "^4.23.12"
35
39
  },
36
40
  "exports": {
37
41
  ".": "./dist/src/index.js"
package/run-tests.sh CHANGED
@@ -1,33 +1,68 @@
1
1
  #!/bin/bash
2
2
 
3
- # Parse command line arguments
4
- WATCH_MODE=false
5
- COVERAGE_MODE=false
6
-
7
- for arg in "$@"
8
- do
9
- case $arg in
10
- --watch)
11
- WATCH_MODE=true
12
- shift
13
- ;;
14
- --coverage)
15
- COVERAGE_MODE=true
16
- shift
17
- ;;
18
- esac
3
+ # Enable nullglob to handle cases where no files match the pattern
4
+ shopt -s nullglob
5
+
6
+ # Initialize variables for options
7
+ watch_mode=false
8
+ coverage_mode=false
9
+
10
+ # Parse command-line options
11
+ while [[ $# -gt 0 ]]; do
12
+ case $1 in
13
+ --watch)
14
+ watch_mode=true
15
+ shift
16
+ ;;
17
+ --coverage)
18
+ coverage_mode=true
19
+ shift
20
+ ;;
21
+ *)
22
+ echo "Unknown option: $1"
23
+ exit 1
24
+ ;;
25
+ esac
19
26
  done
20
27
 
21
- # Build the command
22
- CMD="node --import tsx --test --test-force-exit src/**/*.test.ts"
28
+ # Define the pattern to match your test files
29
+ pattern="src/*.test.ts"
30
+
31
+ # Expand the pattern into an array of files
32
+ files=($(find src -type f -name "*.test.ts"))
33
+
34
+ # Check if any files matched the pattern
35
+ if [ ${#files[@]} -eq 0 ]; then
36
+ echo "No test files found matching pattern: $pattern"
37
+ if [ "${STRICT_TEST_DISCOVERY}" = "1" ]; then
38
+ exit 1
39
+ fi
40
+ exit 0
41
+ fi
42
+
43
+ # Construct the bun command
44
+ #
45
+ # --parallel gives every test file its own worker process, which is what node's
46
+ # `--test` did. Several suites keep module-level caches (a TypeScript program, a
47
+ # temp fixture directory) that a shared process would leak between files.
48
+ #
49
+ # --timeout because bun caps a test at 5s by default where node had no cap, and
50
+ # the suites that build real TypeScript programs run well past that.
51
+ bun_cmd=(bun test --parallel --timeout 120000)
23
52
 
24
- if [ "$WATCH_MODE" = true ]; then
25
- CMD="$CMD --watch"
53
+ # Append options based on flags
54
+ if [ "$watch_mode" = true ]; then
55
+ # --watch reruns in one process; parallel workers have nothing to watch.
56
+ bun_cmd=(bun test --watch --timeout 120000)
26
57
  fi
27
58
 
28
- if [ "$COVERAGE_MODE" = true ]; then
29
- CMD="$CMD --experimental-test-coverage"
59
+ if [ "$coverage_mode" = true ]; then
60
+ # --coverage-dir=. keeps lcov.info at the package root: CI merges every
61
+ # package's report by prefixing its SF paths with the file's own directory,
62
+ # so a nested coverage/ directory would re-root them one level too deep.
63
+ bun_cmd+=(--coverage --coverage-reporter=lcov --coverage-reporter=text --coverage-dir=.)
64
+ export PIKKU_TEST_COVERAGE=1
30
65
  fi
31
66
 
32
- # Execute the command
33
- eval $CMD
67
+ # Execute the bun command with the expanded list of files
68
+ "${bun_cmd[@]}" "${files[@]}"
@@ -1,24 +0,0 @@
1
- import type { KyselyPlugin } from 'kysely';
2
- export type ColumnKind = 'date' | 'bool' | 'json';
3
- /**
4
- * Per-table column kind map. Keys are snake_case table names matching the
5
- * physical SQLite tables; inner keys are snake_case column names.
6
- * Generated by `pikku db migrate` from `-- @date|@bool|@json` annotations
7
- * and naming conventions (col ends in _at/_on → date; starts with is_/has_/can_ → bool).
8
- */
9
- export type CoercionMap = Record<string, Record<string, ColumnKind>>;
10
- export interface CreateCoercionPluginOptions {
11
- map: CoercionMap;
12
- }
13
- /**
14
- * Convert SQLite-stored values (TEXT/INTEGER) back into the logical types
15
- * app code expects (Date / boolean / parsed JSON).
16
- *
17
- * Write-side coercion (Date → ISO string, boolean → 0/1, object → JSON) is
18
- * handled in the NodeSqliteDatabase adapter (always-on), so this plugin is
19
- * read-only.
20
- *
21
- * Place AFTER CamelCasePlugin in the plugin array (or it handles both
22
- * orderings via the dual-keyed global map).
23
- */
24
- export declare function createCoercionPlugin(options: CreateCoercionPluginOptions): KyselyPlugin;
@@ -1,77 +0,0 @@
1
- function fromDb(value, kind) {
2
- if (value == null)
3
- return value;
4
- switch (kind) {
5
- case 'date':
6
- if (typeof value === 'string') {
7
- const d = new Date(value);
8
- return Number.isNaN(d.getTime()) ? value : d;
9
- }
10
- return value;
11
- case 'bool':
12
- if (typeof value === 'number')
13
- return value !== 0;
14
- if (typeof value === 'bigint')
15
- return value !== 0n;
16
- return value;
17
- case 'json':
18
- if (typeof value !== 'string')
19
- return value;
20
- try {
21
- return JSON.parse(value);
22
- }
23
- catch {
24
- return value;
25
- }
26
- }
27
- }
28
- function snakeToCamel(name) {
29
- return name.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
30
- }
31
- /**
32
- * Flatten the per-table map into a single column-name → kind lookup.
33
- * Indexed by BOTH snake_case and camelCase so it works regardless of
34
- * CamelCasePlugin ordering in the plugin array.
35
- */
36
- function buildGlobalMap(map) {
37
- const out = {};
38
- for (const tbl of Object.values(map)) {
39
- for (const [col, kind] of Object.entries(tbl)) {
40
- out[col] = kind;
41
- out[snakeToCamel(col)] = kind;
42
- }
43
- }
44
- return out;
45
- }
46
- /**
47
- * Convert SQLite-stored values (TEXT/INTEGER) back into the logical types
48
- * app code expects (Date / boolean / parsed JSON).
49
- *
50
- * Write-side coercion (Date → ISO string, boolean → 0/1, object → JSON) is
51
- * handled in the NodeSqliteDatabase adapter (always-on), so this plugin is
52
- * read-only.
53
- *
54
- * Place AFTER CamelCasePlugin in the plugin array (or it handles both
55
- * orderings via the dual-keyed global map).
56
- */
57
- export function createCoercionPlugin(options) {
58
- const globalMap = buildGlobalMap(options.map);
59
- return {
60
- transformQuery(args) {
61
- return args.node;
62
- },
63
- async transformResult(args) {
64
- const out = [];
65
- for (const row of args.result.rows) {
66
- const next = { ...row };
67
- for (const [col, val] of Object.entries(row)) {
68
- const kind = globalMap[col];
69
- if (kind)
70
- next[col] = fromDb(val, kind);
71
- }
72
- out.push(next);
73
- }
74
- return { ...args.result, rows: out };
75
- },
76
- };
77
- }
@@ -1 +0,0 @@
1
- {"root":["../src/coercion-plugin.ts","../src/create-node-sqlite-kysely.ts","../src/index.ts","../src/node-sqlite-adapter.ts","../src/register-functions.ts"],"version":"6.0.3"}
@@ -1,92 +0,0 @@
1
- import type { KyselyPlugin, UnknownRow } from 'kysely'
2
-
3
- export type ColumnKind = 'date' | 'bool' | 'json'
4
-
5
- /**
6
- * Per-table column kind map. Keys are snake_case table names matching the
7
- * physical SQLite tables; inner keys are snake_case column names.
8
- * Generated by `pikku db migrate` from `-- @date|@bool|@json` annotations
9
- * and naming conventions (col ends in _at/_on → date; starts with is_/has_/can_ → bool).
10
- */
11
- export type CoercionMap = Record<string, Record<string, ColumnKind>>
12
-
13
- export interface CreateCoercionPluginOptions {
14
- map: CoercionMap
15
- }
16
-
17
- function fromDb(value: unknown, kind: ColumnKind): unknown {
18
- if (value == null) return value
19
- switch (kind) {
20
- case 'date':
21
- if (typeof value === 'string') {
22
- const d = new Date(value)
23
- return Number.isNaN(d.getTime()) ? value : d
24
- }
25
- return value
26
- case 'bool':
27
- if (typeof value === 'number') return value !== 0
28
- if (typeof value === 'bigint') return value !== 0n
29
- return value
30
- case 'json':
31
- if (typeof value !== 'string') return value
32
- try {
33
- return JSON.parse(value)
34
- } catch {
35
- return value
36
- }
37
- }
38
- }
39
-
40
- function snakeToCamel(name: string): string {
41
- return name.replace(/_([a-z])/g, (_, c) => c.toUpperCase())
42
- }
43
-
44
- /**
45
- * Flatten the per-table map into a single column-name → kind lookup.
46
- * Indexed by BOTH snake_case and camelCase so it works regardless of
47
- * CamelCasePlugin ordering in the plugin array.
48
- */
49
- function buildGlobalMap(map: CoercionMap): Record<string, ColumnKind> {
50
- const out: Record<string, ColumnKind> = {}
51
- for (const tbl of Object.values(map)) {
52
- for (const [col, kind] of Object.entries(tbl)) {
53
- out[col] = kind
54
- out[snakeToCamel(col)] = kind
55
- }
56
- }
57
- return out
58
- }
59
-
60
- /**
61
- * Convert SQLite-stored values (TEXT/INTEGER) back into the logical types
62
- * app code expects (Date / boolean / parsed JSON).
63
- *
64
- * Write-side coercion (Date → ISO string, boolean → 0/1, object → JSON) is
65
- * handled in the NodeSqliteDatabase adapter (always-on), so this plugin is
66
- * read-only.
67
- *
68
- * Place AFTER CamelCasePlugin in the plugin array (or it handles both
69
- * orderings via the dual-keyed global map).
70
- */
71
- export function createCoercionPlugin(
72
- options: CreateCoercionPluginOptions
73
- ): KyselyPlugin {
74
- const globalMap = buildGlobalMap(options.map)
75
- return {
76
- transformQuery(args) {
77
- return args.node
78
- },
79
- async transformResult(args) {
80
- const out: UnknownRow[] = []
81
- for (const row of args.result.rows as UnknownRow[]) {
82
- const next: UnknownRow = { ...row }
83
- for (const [col, val] of Object.entries(row)) {
84
- const kind = globalMap[col]
85
- if (kind) next[col] = fromDb(val, kind)
86
- }
87
- out.push(next)
88
- }
89
- return { ...args.result, rows: out }
90
- },
91
- }
92
- }
@@ -1,43 +0,0 @@
1
- import { DatabaseSync } from 'node:sqlite'
2
- import {
3
- Kysely,
4
- SqliteDialect,
5
- CamelCasePlugin,
6
- type KyselyPlugin,
7
- } from 'kysely'
8
- import type { SqliteFunctionMap } from '@pikku/kysely-sqlite'
9
- import { NodeSqliteDatabase } from './node-sqlite-adapter.js'
10
- import { registerSqliteFunctions } from './register-functions.js'
11
-
12
- export interface CreateNodeSqliteKyselyOptions {
13
- /** Path to the SQLite file. Use ':memory:' for an in-memory DB. */
14
- filename: string
15
- /** Apply CamelCasePlugin so DB columns map to camelCase TS fields. Default true. */
16
- camelCase?: boolean
17
- /** Extra plugins to layer on top. */
18
- plugins?: KyselyPlugin[]
19
- /**
20
- * Scalar user-defined SQL functions to register, keyed by the name SQL calls
21
- * them by. Registered as deterministic.
22
- *
23
- * Note that this is the one option with no bun equivalent:
24
- * `createBunSqliteKysely` throws if it is set, because bun:sqlite cannot
25
- * register functions. Using it is a decision to stay on Node.
26
- */
27
- functions?: SqliteFunctionMap
28
- }
29
-
30
- export function createNodeSqliteKysely<DB>(
31
- options: CreateNodeSqliteKyselyOptions
32
- ): Kysely<DB> {
33
- const db = new DatabaseSync(options.filename)
34
- if (options.functions) registerSqliteFunctions(db, options.functions)
35
- const plugins: KyselyPlugin[] = []
36
- if (options.camelCase ?? true) plugins.push(new CamelCasePlugin())
37
- if (options.plugins) plugins.push(...options.plugins)
38
-
39
- return new Kysely<DB>({
40
- dialect: new SqliteDialect({ database: new NodeSqliteDatabase(db) }),
41
- plugins,
42
- })
43
- }
package/src/index.ts DELETED
@@ -1,15 +0,0 @@
1
- export { NodeSqliteDatabase } from './node-sqlite-adapter.js'
2
- export {
3
- createNodeSqliteKysely,
4
- type CreateNodeSqliteKyselyOptions,
5
- } from './create-node-sqlite-kysely.js'
6
- export { registerSqliteFunctions } from './register-functions.js'
7
- export {
8
- SqliteFunctionsUnsupportedError,
9
- type SqliteFunctionMap,
10
- } from '@pikku/kysely-sqlite'
11
- export {
12
- createCoercionPlugin,
13
- type ColumnKind,
14
- type CreateCoercionPluginOptions,
15
- } from './coercion-plugin.js'
@@ -1,62 +0,0 @@
1
- import type { DatabaseSync, StatementSync, SQLInputValue } from 'node:sqlite'
2
- import type { SqliteDatabase, SqliteStatement } from 'kysely'
3
-
4
- /**
5
- * Always-on write-side coercion: converts JS values that SQLite's node:sqlite
6
- * binding cannot accept into their storable equivalents.
7
- * boolean → 0 | 1
8
- * Date → ISO 8601 string
9
- * object → JSON string (covers arrays and plain objects)
10
- */
11
- function coerce(v: unknown): SQLInputValue {
12
- if (v === null || v === undefined) return null as unknown as SQLInputValue
13
- if (typeof v === 'boolean') return v ? 1 : 0
14
- if (v instanceof Date) return v.toISOString()
15
- if (typeof v === 'object') return JSON.stringify(v)
16
- return v as SQLInputValue
17
- }
18
-
19
- /**
20
- * Wraps node:sqlite's DatabaseSync as Kysely's SqliteDatabase. The shapes
21
- * are close but not identical: node:sqlite's Statement methods take
22
- * variadic positional params and always return bigint counters; Kysely's
23
- * dialect passes parameters as a ReadonlyArray and expects number|bigint.
24
- */
25
- class NodeSqliteStatement implements SqliteStatement {
26
- readonly reader = true
27
-
28
- constructor(private readonly stmt: StatementSync) {}
29
-
30
- all(parameters: ReadonlyArray<unknown>): unknown[] {
31
- return this.stmt.all(...parameters.map(coerce)) as unknown[]
32
- }
33
-
34
- *iterate(parameters: ReadonlyArray<unknown>): IterableIterator<unknown> {
35
- for (const row of this.stmt.iterate(...parameters.map(coerce))) {
36
- yield row
37
- }
38
- }
39
-
40
- run(parameters: ReadonlyArray<unknown>): {
41
- changes: number | bigint
42
- lastInsertRowid: number | bigint
43
- } {
44
- const result = this.stmt.run(...parameters.map(coerce))
45
- return {
46
- changes: result.changes,
47
- lastInsertRowid: result.lastInsertRowid,
48
- }
49
- }
50
- }
51
-
52
- export class NodeSqliteDatabase implements SqliteDatabase {
53
- constructor(private readonly db: DatabaseSync) {}
54
-
55
- prepare(sql: string): SqliteStatement {
56
- return new NodeSqliteStatement(this.db.prepare(sql))
57
- }
58
-
59
- close(): void {
60
- this.db.close()
61
- }
62
- }
@@ -1,52 +0,0 @@
1
- import { describe, test } from 'node:test'
2
- import assert from 'node:assert/strict'
3
- import { DatabaseSync } from 'node:sqlite'
4
- import { sql } from 'kysely'
5
- import { registerSqliteFunctions } from './register-functions.js'
6
- import { createNodeSqliteKysely } from './create-node-sqlite-kysely.js'
7
-
8
- describe('registerSqliteFunctions', () => {
9
- test('makes the function callable from SQL', () => {
10
- const db = new DatabaseSync(':memory:')
11
- registerSqliteFunctions(db, {
12
- shout: (value) => `${String(value).toUpperCase()}!`,
13
- })
14
-
15
- const row = db.prepare(`SELECT shout('hello') AS v`).get() as { v: string }
16
- assert.equal(row.v, 'HELLO!')
17
- db.close()
18
- })
19
-
20
- test('registers as deterministic, so it is usable in an index', () => {
21
- const db = new DatabaseSync(':memory:')
22
- registerSqliteFunctions(db, { half: (n) => Number(n) / 2 })
23
-
24
- db.exec('CREATE TABLE t (n INTEGER)')
25
- // SQLite rejects non-deterministic functions in an index outright, so this
26
- // statement succeeding IS the assertion about how they were registered.
27
- db.exec('CREATE INDEX t_half ON t (half(n))')
28
- db.close()
29
- })
30
-
31
- test('registers every entry in the map', () => {
32
- const db = new DatabaseSync(':memory:')
33
- registerSqliteFunctions(db, { a: () => 1, b: () => 2 })
34
-
35
- const row = db.prepare('SELECT a() + b() AS v').get() as { v: number }
36
- assert.equal(row.v, 3)
37
- db.close()
38
- })
39
-
40
- test('createNodeSqliteKysely registers them on the connection it builds', async () => {
41
- const db = createNodeSqliteKysely<{ t: { id: number } }>({
42
- filename: ':memory:',
43
- functions: { double: (n) => Number(n) * 2 },
44
- })
45
-
46
- const result = await sql<{
47
- v: number
48
- }>`SELECT double(21) AS v`.execute(db)
49
- assert.equal(result.rows[0]!.v, 42)
50
- await db.destroy()
51
- })
52
- })
@@ -1,27 +0,0 @@
1
- import type { DatabaseSync } from 'node:sqlite'
2
- import type { SqliteFunctionMap } from '@pikku/kysely-sqlite'
3
-
4
- /**
5
- * Registers scalar user-defined SQL functions on a node:sqlite connection.
6
- *
7
- * Exported separately from `createNodeSqliteKysely` because an app that needs
8
- * pragmas — WAL, `foreign_keys`, `busy_timeout` — has to build the connection
9
- * itself, and would otherwise have no supported way to add UDFs to it.
10
- *
11
- * Registered as `deterministic`, which is what makes them usable in indexes and
12
- * lets SQLite cache repeated calls with the same arguments. That is a promise
13
- * about the function, not a hint: one whose output depends on the clock, a
14
- * random source or anything mutable must not go through here.
15
- *
16
- * There is no bun counterpart. `@pikku/kysely-bun-sqlite` exports the same name
17
- * so the import resolves either way, but it throws — see
18
- * SqliteFunctionsUnsupportedError.
19
- */
20
- export function registerSqliteFunctions(
21
- db: DatabaseSync,
22
- functions: SqliteFunctionMap
23
- ): void {
24
- for (const [name, fn] of Object.entries(functions)) {
25
- db.function(name, { deterministic: true }, fn as never)
26
- }
27
- }
package/tsconfig.json DELETED
@@ -1,12 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.json",
3
- "compilerOptions": {
4
- "rootDir": ".",
5
- "module": "Node18",
6
- "outDir": "dist",
7
- "target": "esnext",
8
- "declaration": true
9
- },
10
- "include": ["src/**/*.ts"],
11
- "exclude": ["**/*.test.ts", "node_modules"]
12
- }