@mark1russell7/docker-sqlite 0.1.0 → 0.1.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/CHANGELOG.md +34 -23
- package/LICENSE +21 -21
- package/README.md +1064 -1057
- package/dist/.tsbuildinfo +1 -1
- package/dist/connect.d.ts +50 -50
- package/dist/connect.d.ts.map +1 -1
- package/dist/connect.js +60 -8
- package/dist/connect.js.map +1 -1
- package/dist/migrate.d.ts.map +1 -1
- package/dist/migrate.js +151 -12
- package/dist/migrate.js.map +1 -1
- package/dist/query.d.ts +51 -51
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +3 -4
- package/dist/query.js.map +1 -1
- package/package.json +80 -86
- package/schema/logs.sql +21 -21
- package/src/connect.ts +245 -194
- package/src/index.ts +61 -61
- package/src/migrate.ts +293 -159
- package/src/query.ts +146 -147
- package/src/types.ts +62 -62
package/src/connect.ts
CHANGED
|
@@ -1,194 +1,245 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Connection utilities for SQLite using sql.js
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
import initSqlJs, { type Database } from "sql.js";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
// keeps the
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
await
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
()
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
*
|
|
146
|
-
*
|
|
147
|
-
*
|
|
148
|
-
* )
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Connection utilities for SQLite using sql.js
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import initSqlJs, { type Database } from "sql.js";
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import { readFile, mkdir, open, rename, unlink } from "node:fs/promises";
|
|
8
|
+
import { dirname, resolve } from "node:path";
|
|
9
|
+
import type { ConnectionConfig, ConnectionCallback } from "./types.js";
|
|
10
|
+
|
|
11
|
+
let sqlPromise: Promise<Awaited<ReturnType<typeof initSqlJs>>> | null = null;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Initialize sql.js (cached)
|
|
15
|
+
*/
|
|
16
|
+
async function getSql(): Promise<Awaited<ReturnType<typeof initSqlJs>>> {
|
|
17
|
+
if (!sqlPromise) {
|
|
18
|
+
sqlPromise = initSqlJs();
|
|
19
|
+
}
|
|
20
|
+
return sqlPromise;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** A database and the bytes of its file when it was loaded (null: there was no file). */
|
|
24
|
+
interface LoadedDatabase {
|
|
25
|
+
db: Database;
|
|
26
|
+
original: Uint8Array | null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Load a database from a file path or create a new one
|
|
31
|
+
*/
|
|
32
|
+
async function loadDatabase(dbPath: string): Promise<LoadedDatabase> {
|
|
33
|
+
const SQL = await getSql();
|
|
34
|
+
|
|
35
|
+
if (dbPath === ":memory:") {
|
|
36
|
+
return { db: new SQL.Database(), original: null };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
try {
|
|
40
|
+
const buffer = await readFile(dbPath);
|
|
41
|
+
// sql.js keeps the array that it gets and writes into it: give it a copy, so `original`
|
|
42
|
+
// keeps the bytes of the file
|
|
43
|
+
return { db: new SQL.Database(new Uint8Array(buffer)), original: buffer };
|
|
44
|
+
} catch (error) {
|
|
45
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
46
|
+
// File doesn't exist, create new database
|
|
47
|
+
return { db: new SQL.Database(), original: null };
|
|
48
|
+
}
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Save a database to a file path, when its content changed.
|
|
55
|
+
*
|
|
56
|
+
* A database that did not change is not written. Before, each call wrote the file, also a
|
|
57
|
+
* read: a read failed on a read-only file (EPERM), a read wrote an old copy over the rows of
|
|
58
|
+
* another process, and a query of a missing file made an empty file. The export of a
|
|
59
|
+
* database that did not change has the bytes of its file, and an empty new database exports
|
|
60
|
+
* no bytes.
|
|
61
|
+
*
|
|
62
|
+
* Writes a temporary file, flushes it to the disk and renames it over the database, so a crash
|
|
63
|
+
* or a power loss during the write cannot leave a truncated database (the rename replaces the
|
|
64
|
+
* file in one step).
|
|
65
|
+
*/
|
|
66
|
+
async function saveDatabase(db: Database, dbPath: string, original: Uint8Array | null): Promise<Uint8Array | null> {
|
|
67
|
+
if (dbPath === ":memory:") {
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const data = db.export();
|
|
72
|
+
const unchanged = original
|
|
73
|
+
? Buffer.compare(Buffer.from(data), Buffer.from(original)) === 0
|
|
74
|
+
: data.length === 0;
|
|
75
|
+
if (unchanged) {
|
|
76
|
+
return original;
|
|
77
|
+
}
|
|
78
|
+
const buffer = Buffer.from(data);
|
|
79
|
+
|
|
80
|
+
// Ensure directory exists
|
|
81
|
+
await mkdir(dirname(dbPath), { recursive: true });
|
|
82
|
+
|
|
83
|
+
// A random part, so two saves at once never share a temporary file. Before, the name had only
|
|
84
|
+
// the process id and the time in milliseconds.
|
|
85
|
+
const tempPath = `${dbPath}.${process.pid}.${randomUUID()}.tmp`;
|
|
86
|
+
try {
|
|
87
|
+
await writeDurably(tempPath, buffer);
|
|
88
|
+
} catch (error) {
|
|
89
|
+
await unlink(tempPath).catch(() => {});
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
await rename(tempPath, dbPath);
|
|
94
|
+
} catch (error) {
|
|
95
|
+
await unlink(tempPath).catch(() => {});
|
|
96
|
+
// The file is held open on Windows: fall back to a direct write. Before, each error of the
|
|
97
|
+
// rename started the direct write, which is not atomic.
|
|
98
|
+
if (!FILE_IN_USE.has((error as NodeJS.ErrnoException).code ?? "")) {
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
await writeDurably(dbPath, buffer);
|
|
102
|
+
}
|
|
103
|
+
await syncDirectory(dirname(dbPath));
|
|
104
|
+
return data;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The error codes of a rename over a file that another process holds open (Windows). */
|
|
108
|
+
const FILE_IN_USE = new Set(["EPERM", "EACCES", "EBUSY"]);
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Write a file and flush it to the disk before the rename. Without the flush, a power loss soon
|
|
112
|
+
* after the rename can leave an empty or partial database on some file systems.
|
|
113
|
+
*/
|
|
114
|
+
async function writeDurably(path: string, data: Uint8Array): Promise<void> {
|
|
115
|
+
const file = await open(path, "w");
|
|
116
|
+
try {
|
|
117
|
+
await file.writeFile(data);
|
|
118
|
+
await file.sync();
|
|
119
|
+
} finally {
|
|
120
|
+
await file.close();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Flush a directory, so that a rename in it stays after a power loss. Windows cannot open a
|
|
126
|
+
* directory for this, and some file systems refuse it: the flush is only an extra safety.
|
|
127
|
+
*/
|
|
128
|
+
async function syncDirectory(path: string): Promise<void> {
|
|
129
|
+
if (process.platform === "win32") {
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
try {
|
|
133
|
+
const directory = await open(path, "r");
|
|
134
|
+
try {
|
|
135
|
+
await directory.sync();
|
|
136
|
+
} finally {
|
|
137
|
+
await directory.close();
|
|
138
|
+
}
|
|
139
|
+
} catch {
|
|
140
|
+
// The rename is done
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* The calls that wait for each database file. Each call reads the whole file, changes it in
|
|
146
|
+
* memory and writes it back, so two calls at once lost the changes of one of them
|
|
147
|
+
* (50 concurrent inserts kept 1 row). Calls for the same file now run one at a time in this
|
|
148
|
+
* process. (Other processes that write the same file are not coordinated.)
|
|
149
|
+
*/
|
|
150
|
+
const fileQueues = new Map<string, Promise<unknown>>();
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The queue key of a file. Windows file names do not depend on case, so the key is in lower
|
|
154
|
+
* case there. Before, two spellings of one file had two queues, and their calls ran at once.
|
|
155
|
+
*/
|
|
156
|
+
export function fileQueueKey(dbPath: string, platform: NodeJS.Platform = process.platform): string {
|
|
157
|
+
const path = resolve(dbPath);
|
|
158
|
+
return platform === "win32" ? path.toLowerCase() : path;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function inFileQueue<T>(dbPath: string, task: () => Promise<T>): Promise<T> {
|
|
162
|
+
if (dbPath === ":memory:") {
|
|
163
|
+
return task();
|
|
164
|
+
}
|
|
165
|
+
const key = fileQueueKey(dbPath);
|
|
166
|
+
const previous = fileQueues.get(key) ?? Promise.resolve();
|
|
167
|
+
const run = previous.then(task, task);
|
|
168
|
+
const tail = run.then(
|
|
169
|
+
() => undefined,
|
|
170
|
+
() => undefined
|
|
171
|
+
);
|
|
172
|
+
fileQueues.set(key, tail);
|
|
173
|
+
try {
|
|
174
|
+
return await run;
|
|
175
|
+
} finally {
|
|
176
|
+
if (fileQueues.get(key) === tail) {
|
|
177
|
+
fileQueues.delete(key);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Execute a callback with a SQLite connection, ensuring proper cleanup and persistence.
|
|
184
|
+
*
|
|
185
|
+
* @example
|
|
186
|
+
* ```typescript
|
|
187
|
+
* const result = await withConnection(
|
|
188
|
+
* { dbPath: './data/app.db' },
|
|
189
|
+
* async (db) => {
|
|
190
|
+
* const stmt = db.prepare('SELECT * FROM users WHERE id = ?');
|
|
191
|
+
* stmt.bind([1]);
|
|
192
|
+
* const rows = [];
|
|
193
|
+
* while (stmt.step()) {
|
|
194
|
+
* rows.push(stmt.getAsObject());
|
|
195
|
+
* }
|
|
196
|
+
* stmt.free();
|
|
197
|
+
* return rows;
|
|
198
|
+
* }
|
|
199
|
+
* );
|
|
200
|
+
* ```
|
|
201
|
+
*/
|
|
202
|
+
export async function withConnection<T>(
|
|
203
|
+
config: ConnectionConfig,
|
|
204
|
+
fn: ConnectionCallback<T>
|
|
205
|
+
): Promise<T> {
|
|
206
|
+
return inFileQueue(config.dbPath, async () => {
|
|
207
|
+
const { db, original } = await loadDatabase(config.dbPath);
|
|
208
|
+
|
|
209
|
+
try {
|
|
210
|
+
const result = await fn(db);
|
|
211
|
+
// Save changes back to file (only when there are changes)
|
|
212
|
+
await saveDatabase(db, config.dbPath, original);
|
|
213
|
+
return result;
|
|
214
|
+
} finally {
|
|
215
|
+
db.close();
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Create a SQLite database that can be manually managed.
|
|
222
|
+
* Caller is responsible for calling db.close() and saving if needed.
|
|
223
|
+
*
|
|
224
|
+
* @example
|
|
225
|
+
* ```typescript
|
|
226
|
+
* const { db, save } = await createConnection({ dbPath: './data/app.db' });
|
|
227
|
+
* try {
|
|
228
|
+
* db.run('INSERT INTO users (name) VALUES (?)', ['Alice']);
|
|
229
|
+
* await save();
|
|
230
|
+
* } finally {
|
|
231
|
+
* db.close();
|
|
232
|
+
* }
|
|
233
|
+
* ```
|
|
234
|
+
*/
|
|
235
|
+
export async function createConnection(
|
|
236
|
+
config: ConnectionConfig
|
|
237
|
+
): Promise<{ db: Database; save: () => Promise<void> }> {
|
|
238
|
+
const { db, original } = await loadDatabase(config.dbPath);
|
|
239
|
+
// The bytes of the file after the last save, to compare the next save with
|
|
240
|
+
let saved = original;
|
|
241
|
+
const save = async (): Promise<void> => {
|
|
242
|
+
saved = await saveDatabase(db, config.dbPath, saved);
|
|
243
|
+
};
|
|
244
|
+
return { db, save };
|
|
245
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,61 +1,61 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* docker-sqlite - Reusable SQLite Docker setup with TypeScript utilities
|
|
3
|
-
*
|
|
4
|
-
* @example
|
|
5
|
-
* ```typescript
|
|
6
|
-
* import { withConnection, query, execute, runMigrations } from 'docker-sqlite';
|
|
7
|
-
*
|
|
8
|
-
* // Define migrations
|
|
9
|
-
* const migrations = [
|
|
10
|
-
* {
|
|
11
|
-
* version: 1,
|
|
12
|
-
* description: 'Create users table',
|
|
13
|
-
* up: 'CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)',
|
|
14
|
-
* down: 'DROP TABLE users'
|
|
15
|
-
* }
|
|
16
|
-
* ];
|
|
17
|
-
*
|
|
18
|
-
* // Run with auto-save
|
|
19
|
-
* await withConnection({ dbPath: './data/app.db' }, (db) => {
|
|
20
|
-
* runMigrations(db, migrations);
|
|
21
|
-
*
|
|
22
|
-
* execute(db, 'INSERT INTO users (name, email) VALUES (?, ?)', ['Alice', 'alice@example.com']);
|
|
23
|
-
*
|
|
24
|
-
* const result = query(db, 'SELECT * FROM users');
|
|
25
|
-
* console.log(result.rows);
|
|
26
|
-
* });
|
|
27
|
-
* ```
|
|
28
|
-
*/
|
|
29
|
-
|
|
30
|
-
// Types
|
|
31
|
-
export type {
|
|
32
|
-
ConnectionConfig,
|
|
33
|
-
ConnectionCallback,
|
|
34
|
-
QueryResult,
|
|
35
|
-
ExecuteResult,
|
|
36
|
-
Migration,
|
|
37
|
-
MigrationStatus,
|
|
38
|
-
} from "./types.js";
|
|
39
|
-
|
|
40
|
-
// Connection utilities
|
|
41
|
-
export { withConnection, createConnection } from "./connect.js";
|
|
42
|
-
|
|
43
|
-
// Query utilities
|
|
44
|
-
export {
|
|
45
|
-
query,
|
|
46
|
-
execute,
|
|
47
|
-
execMultiple,
|
|
48
|
-
lastInsertRowId,
|
|
49
|
-
tableExists,
|
|
50
|
-
} from "./query.js";
|
|
51
|
-
|
|
52
|
-
// Migration utilities
|
|
53
|
-
export {
|
|
54
|
-
getMigrationStatus,
|
|
55
|
-
runMigrations,
|
|
56
|
-
rollbackMigration,
|
|
57
|
-
createMigration,
|
|
58
|
-
} from "./migrate.js";
|
|
59
|
-
|
|
60
|
-
// Re-export sql.js Database type for convenience
|
|
61
|
-
export type { Database } from "sql.js";
|
|
1
|
+
/**
|
|
2
|
+
* docker-sqlite - Reusable SQLite Docker setup with TypeScript utilities
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* ```typescript
|
|
6
|
+
* import { withConnection, query, execute, runMigrations } from 'docker-sqlite';
|
|
7
|
+
*
|
|
8
|
+
* // Define migrations
|
|
9
|
+
* const migrations = [
|
|
10
|
+
* {
|
|
11
|
+
* version: 1,
|
|
12
|
+
* description: 'Create users table',
|
|
13
|
+
* up: 'CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)',
|
|
14
|
+
* down: 'DROP TABLE users'
|
|
15
|
+
* }
|
|
16
|
+
* ];
|
|
17
|
+
*
|
|
18
|
+
* // Run with auto-save
|
|
19
|
+
* await withConnection({ dbPath: './data/app.db' }, (db) => {
|
|
20
|
+
* runMigrations(db, migrations);
|
|
21
|
+
*
|
|
22
|
+
* execute(db, 'INSERT INTO users (name, email) VALUES (?, ?)', ['Alice', 'alice@example.com']);
|
|
23
|
+
*
|
|
24
|
+
* const result = query(db, 'SELECT * FROM users');
|
|
25
|
+
* console.log(result.rows);
|
|
26
|
+
* });
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
// Types
|
|
31
|
+
export type {
|
|
32
|
+
ConnectionConfig,
|
|
33
|
+
ConnectionCallback,
|
|
34
|
+
QueryResult,
|
|
35
|
+
ExecuteResult,
|
|
36
|
+
Migration,
|
|
37
|
+
MigrationStatus,
|
|
38
|
+
} from "./types.js";
|
|
39
|
+
|
|
40
|
+
// Connection utilities
|
|
41
|
+
export { withConnection, createConnection } from "./connect.js";
|
|
42
|
+
|
|
43
|
+
// Query utilities
|
|
44
|
+
export {
|
|
45
|
+
query,
|
|
46
|
+
execute,
|
|
47
|
+
execMultiple,
|
|
48
|
+
lastInsertRowId,
|
|
49
|
+
tableExists,
|
|
50
|
+
} from "./query.js";
|
|
51
|
+
|
|
52
|
+
// Migration utilities
|
|
53
|
+
export {
|
|
54
|
+
getMigrationStatus,
|
|
55
|
+
runMigrations,
|
|
56
|
+
rollbackMigration,
|
|
57
|
+
createMigration,
|
|
58
|
+
} from "./migrate.js";
|
|
59
|
+
|
|
60
|
+
// Re-export sql.js Database type for convenience
|
|
61
|
+
export type { Database } from "sql.js";
|