@rawsql-ts/testkit-sqlite 1.0.1 → 1.0.2

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 MSugiura
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,67 +1,67 @@
1
- # @rawsql-ts/testkit-sqlite
2
-
3
- ![npm version](https://img.shields.io/npm/v/@rawsql-ts/testkit-sqlite)
4
- ![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)
5
-
6
- SQLite driver adapter for running repository tests entirely in-memory by shadowing tables with fixture-backed CTEs. Built on `@rawsql-ts/testkit-core` for schema validation and SQL rewrites.
7
-
8
- ## Features
9
-
10
- - In-memory testing with `better-sqlite3`
11
- - Transparent query interception via `wrapSqliteDriver`
12
- - Scenario-specific fixture overrides with `withFixtures`
13
- - Schema registry support for consistent large test suites
14
-
15
- ## Installation
16
-
17
- ```bash
18
- npm install @rawsql-ts/testkit-sqlite
19
- ```
20
-
21
- ## Quick Start
22
-
23
- ```ts
24
- import Database from 'better-sqlite3';
25
- import { createSqliteSelectTestDriver } from '@rawsql-ts/testkit-sqlite';
26
-
27
- const driver = createSqliteSelectTestDriver({
28
- connectionFactory: () => new Database(':memory:'),
29
- fixtures: [
30
- {
31
- tableName: 'users',
32
- rows: [{ id: 1, name: 'Alice', role: 'admin' }],
33
- schema: { columns: { id: 'INTEGER', name: 'TEXT', role: 'TEXT' } },
34
- },
35
- ],
36
- missingFixtureStrategy: 'error',
37
- });
38
-
39
- const rows = await driver.query('SELECT * FROM users');
40
- ```
41
-
42
- Use `driver.withFixtures([...])` to derive a scoped driver with scenario-specific overrides, and `driver.close()` to dispose the connection when done.
43
-
44
- ## Wrapping an Existing Connection
45
-
46
- `wrapSqliteDriver` turns any `better-sqlite3` connection into a transparent proxy that intercepts `prepare`, `exec`, `all`, `get`, and `run` — rewriting SELECT statements into fixture-backed CTEs while passing through everything else.
47
-
48
- ```ts
49
- import Database from 'better-sqlite3';
50
- import { wrapSqliteDriver } from '@rawsql-ts/testkit-sqlite';
51
-
52
- const raw = new Database(':memory:');
53
- const intercepted = wrapSqliteDriver(raw, {
54
- fixtures: [
55
- { tableName: 'orders', rows: [{ id: 1 }], schema: { columns: { id: 'INTEGER' } } },
56
- ],
57
- missingFixtureStrategy: 'warn',
58
- recordQueries: true,
59
- });
60
-
61
- intercepted.prepare('SELECT * FROM orders').all();
62
- console.log(intercepted.queries); // inspect emitted SQL
63
- ```
64
-
65
- ## License
66
-
67
- MIT
1
+ # @rawsql-ts/testkit-sqlite
2
+
3
+ ![npm version](https://img.shields.io/npm/v/@rawsql-ts/testkit-sqlite)
4
+ ![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)
5
+
6
+ SQLite driver adapter for running repository tests entirely in-memory by shadowing tables with fixture-backed CTEs. Built on `@rawsql-ts/testkit-core` for schema validation and SQL rewrites.
7
+
8
+ ## Features
9
+
10
+ - In-memory testing with `better-sqlite3`
11
+ - Transparent query interception via `wrapSqliteDriver`
12
+ - Scenario-specific fixture overrides with `withFixtures`
13
+ - Schema registry support for consistent large test suites
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm install @rawsql-ts/testkit-sqlite
19
+ ```
20
+
21
+ ## Quick Start
22
+
23
+ ```ts
24
+ import Database from 'better-sqlite3';
25
+ import { createSqliteSelectTestDriver } from '@rawsql-ts/testkit-sqlite';
26
+
27
+ const driver = createSqliteSelectTestDriver({
28
+ connectionFactory: () => new Database(':memory:'),
29
+ fixtures: [
30
+ {
31
+ tableName: 'users',
32
+ rows: [{ id: 1, name: 'Alice', role: 'admin' }],
33
+ schema: { columns: { id: 'INTEGER', name: 'TEXT', role: 'TEXT' } },
34
+ },
35
+ ],
36
+ missingFixtureStrategy: 'error',
37
+ });
38
+
39
+ const rows = await driver.query('SELECT * FROM users');
40
+ ```
41
+
42
+ Use `driver.withFixtures([...])` to derive a scoped driver with scenario-specific overrides, and `driver.close()` to dispose the connection when done.
43
+
44
+ ## Wrapping an Existing Connection
45
+
46
+ `wrapSqliteDriver` turns any `better-sqlite3` connection into a transparent proxy that intercepts `prepare`, `exec`, `all`, `get`, and `run` — rewriting SELECT statements into fixture-backed CTEs while passing through everything else.
47
+
48
+ ```ts
49
+ import Database from 'better-sqlite3';
50
+ import { wrapSqliteDriver } from '@rawsql-ts/testkit-sqlite';
51
+
52
+ const raw = new Database(':memory:');
53
+ const intercepted = wrapSqliteDriver(raw, {
54
+ fixtures: [
55
+ { tableName: 'orders', rows: [{ id: 1 }], schema: { columns: { id: 'INTEGER' } } },
56
+ ],
57
+ missingFixtureStrategy: 'warn',
58
+ recordQueries: true,
59
+ });
60
+
61
+ intercepted.prepare('SELECT * FROM orders').all();
62
+ console.log(intercepted.queries); // inspect emitted SQL
63
+ ```
64
+
65
+ ## License
66
+
67
+ MIT
@@ -225,16 +225,16 @@ function getDeclaredType(dataType) {
225
225
  * Prints the human-friendly CLI usage instructions and exits the process.
226
226
  */
227
227
  function printUsage() {
228
- console.log(`
229
- Usage:
230
- pnpm --filter @rawsql-ts/testkit-sqlite run schema:generate -- --database <path> [--output <path>] [--tables <names>]
231
-
232
- Options:
233
- --per-table Emit per-table JSON files instead of a single schema.json (output path becomes a directory).
234
- --database, -d <path> SQLite database file that hosts the CREATE TABLE statements.
235
- --output, -o <path> Path to write schema.json (defaults to schema.json in the current directory).
236
- --tables, -t <names> Comma-separated list of table names to include (case-insensitive).
237
- --help, -h Show this message.
228
+ console.log(`
229
+ Usage:
230
+ pnpm --filter @rawsql-ts/testkit-sqlite run schema:generate -- --database <path> [--output <path>] [--tables <names>]
231
+
232
+ Options:
233
+ --per-table Emit per-table JSON files instead of a single schema.json (output path becomes a directory).
234
+ --database, -d <path> SQLite database file that hosts the CREATE TABLE statements.
235
+ --output, -o <path> Path to write schema.json (defaults to schema.json in the current directory).
236
+ --tables, -t <names> Comma-separated list of table names to include (case-insensitive).
237
+ --help, -h Show this message.
238
238
  `);
239
239
  }
240
240
  void main().catch((error) => {
package/package.json CHANGED
@@ -1,51 +1,51 @@
1
- {
2
- "name": "@rawsql-ts/testkit-sqlite",
3
- "version": "1.0.1",
4
- "description": "SQLite driver adapters for the rawsql-ts select query test harness.",
5
- "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
7
- "scripts": {
8
- "prepack": "node -e \"const fs=require('fs');const cp=require('child_process');const npm=process.platform==='win32'?'npm.cmd':'npm';if(!fs.existsSync('dist/index.js')){process.exit(cp.spawnSync(npm,['run','build'],{stdio:'inherit'}).status??1)}\"",
9
- "build": "tsc -p tsconfig.build.json",
10
- "test": "vitest run",
11
- "test:watch": "vitest",
12
- "lint": "eslint src tests --ext .ts",
13
- "schema:generate": "ts-node --project tsconfig.json src/cli/generateSchema.ts",
14
- "postinstall": "node ./scripts/install-better-sqlite3.cjs",
15
- "release": "npm run lint && npm run test && npm run build && node -e \"require('fs').mkdirSync('../../tmp', { recursive: true })\" && pnpm pack --out ../../tmp/rawsql-ts-testkit-sqlite.tgz && pnpm publish --access public"
16
- },
17
- "keywords": [
18
- "sqlite",
19
- "testing",
20
- "fixtures",
21
- "rawsql"
22
- ],
23
- "license": "MIT",
24
- "author": "msugiura",
25
- "repository": {
26
- "type": "git",
27
- "url": "git+https://github.com/mk3008/rawsql-ts.git",
28
- "directory": "packages/testkit-sqlite"
29
- },
30
- "publishConfig": {
31
- "access": "public"
32
- },
33
- "engines": {
34
- "node": ">=20"
35
- },
36
- "dependencies": {
37
- "@rawsql-ts/testkit-core": "workspace:^",
38
- "rawsql-ts": "workspace:^"
39
- },
40
- "devDependencies": {
41
- "@types/better-sqlite3": "^7.6.13",
42
- "better-sqlite3": "^12.4.1",
43
- "dotenv": "^16.4.7",
44
- "typescript": "^5.8.2",
45
- "vitest": "^4.0.7",
46
- "ts-node": "^10.9.2"
47
- },
48
- "files": [
49
- "dist"
50
- ]
51
- }
1
+ {
2
+ "name": "@rawsql-ts/testkit-sqlite",
3
+ "version": "1.0.2",
4
+ "description": "SQLite driver adapters for the rawsql-ts select query test harness.",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "keywords": [
8
+ "sqlite",
9
+ "testing",
10
+ "fixtures",
11
+ "rawsql"
12
+ ],
13
+ "license": "MIT",
14
+ "author": "msugiura",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/mk3008/rawsql-ts.git",
18
+ "directory": "packages/testkit-sqlite"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "engines": {
24
+ "node": ">=20"
25
+ },
26
+ "dependencies": {
27
+ "@rawsql-ts/testkit-core": "^0.16.1",
28
+ "rawsql-ts": "^0.17.0"
29
+ },
30
+ "devDependencies": {
31
+ "@types/better-sqlite3": "^7.6.13",
32
+ "better-sqlite3": "^12.4.1",
33
+ "dotenv": "^16.4.7",
34
+ "typescript": "^5.8.2",
35
+ "vitest": "^4.0.7",
36
+ "ts-node": "^10.9.2"
37
+ },
38
+ "files": [
39
+ "dist",
40
+ "scripts"
41
+ ],
42
+ "scripts": {
43
+ "build": "tsc -p tsconfig.build.json",
44
+ "test": "vitest run",
45
+ "test:watch": "vitest",
46
+ "lint": "eslint src tests --ext .ts",
47
+ "schema:generate": "ts-node --project tsconfig.json src/cli/generateSchema.ts",
48
+ "postinstall": "node ./scripts/install-better-sqlite3.cjs",
49
+ "release": "npm run lint && npm run test && npm run build && node -e \"require('fs').mkdirSync('../../tmp', { recursive: true })\" && pnpm pack --out ../../tmp/rawsql-ts-testkit-sqlite.tgz && pnpm publish --access public"
50
+ }
51
+ }
@@ -0,0 +1,118 @@
1
+ #!/usr/bin/env node
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const os = require('node:os');
5
+ const https = require('node:https');
6
+ const { spawnSync } = require('node:child_process');
7
+
8
+ const packageRoot = path.resolve(__dirname, '..');
9
+ let pkgJsonPath;
10
+ try {
11
+ pkgJsonPath = require.resolve('better-sqlite3/package.json', { paths: [packageRoot] });
12
+ } catch (error) {
13
+ console.warn('[better-sqlite3-prebuild] better-sqlite3 is not installed yet.');
14
+ process.exit(0);
15
+ }
16
+
17
+ const betterRoot = path.dirname(pkgJsonPath);
18
+ const betterPkg = require(pkgJsonPath);
19
+ const version = betterPkg.version;
20
+ const abi = process.versions.modules;
21
+ const platform = process.platform;
22
+ const arch = process.arch;
23
+ const bindingDir = path.join(betterRoot, 'lib', 'binding', `node-v${abi}-${platform}-${arch}`);
24
+ const releaseDir = path.join(betterRoot, 'build', 'Release');
25
+ const bindingFile = path.join(bindingDir, 'better_sqlite3.node');
26
+
27
+ if (fs.existsSync(bindingFile)) {
28
+ process.exit(0);
29
+ }
30
+
31
+ const assetName = `better-sqlite3-v${version}-node-v${abi}-${platform}-${arch}.tar.gz`;
32
+ const downloadUrl = `https://github.com/WiseLibs/better-sqlite3/releases/download/v${version}/${assetName}`;
33
+
34
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'better-sqlite3-'));
35
+ const archivePath = path.join(tmpDir, assetName);
36
+
37
+ const download = (url = downloadUrl, redirectCount = 0) =>
38
+ new Promise((resolve, reject) => {
39
+ https
40
+ .get(url, (response) => {
41
+ if (
42
+ response.statusCode &&
43
+ response.statusCode >= 300 &&
44
+ response.statusCode < 400 &&
45
+ response.headers.location
46
+ ) {
47
+ // Follow GitHub's redirector (a HEAD object would yield a 302 first).
48
+ if (redirectCount >= 5) {
49
+ reject(new Error('Too many redirects while downloading prebuilt binary'));
50
+ return;
51
+ }
52
+ response.resume();
53
+ download(response.headers.location, redirectCount + 1).then(resolve).catch(reject);
54
+ return;
55
+ }
56
+
57
+ if (response.statusCode && response.statusCode >= 400) {
58
+ reject(new Error(`Failed to download prebuilt binary (${response.statusCode})`));
59
+ response.resume();
60
+ return;
61
+ }
62
+
63
+ // Stream the payload into the archive path once we have a 200 response.
64
+ const file = fs.createWriteStream(archivePath);
65
+ response.pipe(file);
66
+ file.on('finish', () => {
67
+ file.close(resolve);
68
+ });
69
+ file.on('error', reject);
70
+ })
71
+ .on('error', reject);
72
+ });
73
+
74
+ (async () => {
75
+ try {
76
+ await download();
77
+ } catch (error) {
78
+ console.warn(`[better-sqlite3-prebuild] ${error.message}`);
79
+ process.exit(0);
80
+ }
81
+
82
+ const extractResult = spawnSync('tar', ['-xzf', archivePath, '-C', tmpDir], {
83
+ stdio: 'inherit',
84
+ });
85
+
86
+ if (extractResult.status !== 0) {
87
+ console.warn('[better-sqlite3-prebuild] Failed to extract archive, skipping.');
88
+ process.exit(0);
89
+ }
90
+
91
+ const locatePrebuilt = (searchDir) => {
92
+ // Depth-first search so we can handle archives that wrap binaries with additional folders.
93
+ for (const entry of fs.readdirSync(searchDir, { withFileTypes: true })) {
94
+ const fullPath = path.join(searchDir, entry.name);
95
+ if (entry.isDirectory()) {
96
+ const nested = locatePrebuilt(fullPath);
97
+ if (nested) {
98
+ return nested;
99
+ }
100
+ } else if (entry.isFile() && entry.name === 'better_sqlite3.node') {
101
+ return fullPath;
102
+ }
103
+ }
104
+ return undefined;
105
+ };
106
+
107
+ const prebuildRelease = locatePrebuilt(tmpDir);
108
+ if (!prebuildRelease) {
109
+ console.warn('[better-sqlite3-prebuild] Extracted archive did not contain better_sqlite3.node');
110
+ process.exit(0);
111
+ }
112
+
113
+ fs.mkdirSync(bindingDir, { recursive: true });
114
+ fs.mkdirSync(releaseDir, { recursive: true });
115
+ fs.copyFileSync(prebuildRelease, bindingFile);
116
+ fs.copyFileSync(prebuildRelease, path.join(releaseDir, 'better_sqlite3.node'));
117
+ console.log(`[better-sqlite3-prebuild] Installed ${assetName}`);
118
+ })();