@mark1russell7/docker-sqlite 0.0.0-stage → 0.1.0

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/src/migrate.ts ADDED
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Migration utilities for SQLite
3
+ */
4
+
5
+ import type { Database } from "sql.js";
6
+ import type { Migration, MigrationStatus } from "./types.js";
7
+ import { query, execute, execMultiple } from "./query.js";
8
+
9
+ /**
10
+ * Schema for tracking migrations
11
+ */
12
+ const MIGRATIONS_TABLE_SQL = `
13
+ CREATE TABLE IF NOT EXISTS _migrations (
14
+ version INTEGER PRIMARY KEY,
15
+ description TEXT NOT NULL,
16
+ applied_at TEXT NOT NULL DEFAULT (datetime('now'))
17
+ )
18
+ `;
19
+
20
+ /**
21
+ * Ensure the migrations table exists
22
+ */
23
+ function ensureMigrationsTable(db: Database): void {
24
+ execMultiple(db, MIGRATIONS_TABLE_SQL);
25
+ }
26
+
27
+ /**
28
+ * Get the current migration status
29
+ */
30
+ export function getMigrationStatus(
31
+ db: Database,
32
+ migrations: Migration[]
33
+ ): MigrationStatus {
34
+ ensureMigrationsTable(db);
35
+
36
+ const applied = query<{ version: number }>(
37
+ db,
38
+ "SELECT version FROM _migrations ORDER BY version"
39
+ );
40
+
41
+ const appliedVersions = new Set(applied.rows.map((r) => r.version));
42
+ const appliedMigrations = [...appliedVersions].sort((a, b) => a - b);
43
+ const currentVersion =
44
+ appliedMigrations.length > 0
45
+ ? appliedMigrations[appliedMigrations.length - 1]!
46
+ : 0;
47
+
48
+ const pendingMigrations = migrations
49
+ .filter((m) => !appliedVersions.has(m.version))
50
+ .sort((a, b) => a.version - b.version);
51
+
52
+ return {
53
+ currentVersion,
54
+ appliedMigrations,
55
+ pendingMigrations,
56
+ };
57
+ }
58
+
59
+ /**
60
+ * Run all pending migrations
61
+ *
62
+ * @example
63
+ * ```typescript
64
+ * const migrations: Migration[] = [
65
+ * {
66
+ * version: 1,
67
+ * description: 'Create users table',
68
+ * up: 'CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)',
69
+ * down: 'DROP TABLE users'
70
+ * },
71
+ * {
72
+ * version: 2,
73
+ * description: 'Add email column',
74
+ * up: 'ALTER TABLE users ADD COLUMN email TEXT',
75
+ * }
76
+ * ];
77
+ *
78
+ * const applied = runMigrations(db, migrations);
79
+ * console.log(`Applied ${applied.length} migrations`);
80
+ * ```
81
+ */
82
+ export function runMigrations(db: Database, migrations: Migration[]): Migration[] {
83
+ const status = getMigrationStatus(db, migrations);
84
+ const applied: Migration[] = [];
85
+
86
+ for (const migration of status.pendingMigrations) {
87
+ try {
88
+ // Run the migration
89
+ execMultiple(db, migration.up);
90
+
91
+ // Record it as applied
92
+ execute(
93
+ db,
94
+ "INSERT INTO _migrations (version, description) VALUES (?, ?)",
95
+ [migration.version, migration.description]
96
+ );
97
+
98
+ applied.push(migration);
99
+ } catch (error) {
100
+ throw new Error(
101
+ `Failed to apply migration ${migration.version} (${migration.description}): ${error instanceof Error ? error.message : String(error)}`
102
+ );
103
+ }
104
+ }
105
+
106
+ return applied;
107
+ }
108
+
109
+ /**
110
+ * Rollback the last applied migration
111
+ */
112
+ export function rollbackMigration(
113
+ db: Database,
114
+ migrations: Migration[]
115
+ ): Migration | null {
116
+ const status = getMigrationStatus(db, migrations);
117
+
118
+ if (status.currentVersion === 0) {
119
+ return null;
120
+ }
121
+
122
+ const migration = migrations.find((m) => m.version === status.currentVersion);
123
+
124
+ if (!migration) {
125
+ throw new Error(`Migration ${status.currentVersion} not found in migrations list`);
126
+ }
127
+
128
+ if (!migration.down) {
129
+ throw new Error(
130
+ `Migration ${migration.version} (${migration.description}) has no down migration`
131
+ );
132
+ }
133
+
134
+ try {
135
+ execMultiple(db, migration.down);
136
+ execute(db, "DELETE FROM _migrations WHERE version = ?", [migration.version]);
137
+ return migration;
138
+ } catch (error) {
139
+ throw new Error(
140
+ `Failed to rollback migration ${migration.version}: ${error instanceof Error ? error.message : String(error)}`
141
+ );
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Create a migration from SQL strings
147
+ */
148
+ export function createMigration(
149
+ version: number,
150
+ description: string,
151
+ up: string,
152
+ down?: string
153
+ ): Migration {
154
+ const migration: Migration = { version, description, up };
155
+ if (down !== undefined) {
156
+ migration.down = down;
157
+ }
158
+ return migration;
159
+ }
package/src/query.ts ADDED
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Query helper utilities for SQLite
3
+ */
4
+
5
+ import type { Database } from "sql.js";
6
+ import type { QueryResult, ExecuteResult } from "./types.js";
7
+
8
+ /**
9
+ * Execute a SELECT query and return results
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * const result = query(db, 'SELECT * FROM users WHERE age > ?', [21]);
14
+ * console.log(result.columns); // ['id', 'name', 'age']
15
+ * console.log(result.rows); // [{ id: 1, name: 'Alice', age: 25 }, ...]
16
+ * ```
17
+ */
18
+ export function query<T = Record<string, unknown>>(
19
+ db: Database,
20
+ sql: string,
21
+ params: unknown[] = []
22
+ ): QueryResult<T> {
23
+ const stmt = db.prepare(sql);
24
+
25
+ try {
26
+ stmt.bind(params as (string | number | Uint8Array | null)[]);
27
+
28
+ const rows: T[] = [];
29
+ let columns: string[] = [];
30
+
31
+ while (stmt.step()) {
32
+ if (columns.length === 0) {
33
+ columns = stmt.getColumnNames();
34
+ }
35
+ rows.push(stmt.getAsObject() as T);
36
+ }
37
+
38
+ return { columns, rows };
39
+ } finally {
40
+ stmt.free();
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Execute an INSERT, UPDATE, DELETE, or other statement
46
+ *
47
+ * @example
48
+ * ```typescript
49
+ * const result = execute(db, 'INSERT INTO users (name, age) VALUES (?, ?)', ['Bob', 30]);
50
+ * console.log(result.changes); // 1
51
+ * ```
52
+ */
53
+ export function execute(
54
+ db: Database,
55
+ sql: string,
56
+ params: unknown[] = []
57
+ ): ExecuteResult {
58
+ // With parameters, sql.js runs only the first statement. Before, the other statements were
59
+ // ignored and the call reported success. Now several statements run with no parameters, and
60
+ // are an error with parameters.
61
+ if (hasSeveralStatements(db, sql)) {
62
+ if (params.length > 0) {
63
+ throw new Error(
64
+ "execute() binds parameters to one statement, and the SQL has several. Send one statement per call."
65
+ );
66
+ }
67
+ const before = totalChanges(db);
68
+ db.exec(sql);
69
+ return { changes: totalChanges(db) - before };
70
+ }
71
+ db.run(sql, params as (string | number | Uint8Array | null)[]);
72
+ const changes = db.getRowsModified();
73
+ return { changes };
74
+ }
75
+
76
+ /** The number of rows that the statements of this connection changed. */
77
+ function totalChanges(db: Database): number {
78
+ const result = db.exec("SELECT total_changes()");
79
+ return Number(result[0]?.values[0]?.[0] ?? 0);
80
+ }
81
+
82
+ /** True when the text holds SQL other than spaces, ";" and comments. */
83
+ function holdsStatement(sql: string): boolean {
84
+ return sql
85
+ .replace(/--[^\n]*/g, "")
86
+ .replace(/\/\*[\s\S]*?\*\//g, "")
87
+ .replace(/[\s;]/g, "")
88
+ .length > 0;
89
+ }
90
+
91
+ /**
92
+ * True when `sql` holds more than one statement. Nothing runs: the function only prepares the
93
+ * first statement and examines the SQL after it.
94
+ */
95
+ export function hasSeveralStatements(db: Database, sql: string): boolean {
96
+ const iterator = db.iterateStatements(sql);
97
+ const first = iterator.next();
98
+ if (first.done) {
99
+ return false;
100
+ }
101
+ const rest = iterator.getRemainingSQL();
102
+ // Read the iterator to its end: this frees the statement and the copy of the SQL. A later
103
+ // statement can fail to prepare (its table does not exist yet), and that also ends it.
104
+ try {
105
+ while (!iterator.next().done) {
106
+ // Prepare only
107
+ }
108
+ } catch {
109
+ // The iterator ended
110
+ }
111
+ return holdsStatement(rest);
112
+ }
113
+
114
+ /**
115
+ * Execute multiple statements (for schema setup, etc.)
116
+ *
117
+ * @example
118
+ * ```typescript
119
+ * execMultiple(db, `
120
+ * CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT);
121
+ * CREATE TABLE IF NOT EXISTS posts (id INTEGER PRIMARY KEY, user_id INTEGER);
122
+ * `);
123
+ * ```
124
+ */
125
+ export function execMultiple(db: Database, sql: string): void {
126
+ db.exec(sql);
127
+ }
128
+
129
+ /**
130
+ * Get the last inserted row ID
131
+ */
132
+ export function lastInsertRowId(db: Database): number {
133
+ const result = query<{ id: number }>(db, "SELECT last_insert_rowid() as id");
134
+ return result.rows[0]?.id ?? 0;
135
+ }
136
+
137
+ /**
138
+ * Check if a table exists
139
+ */
140
+ export function tableExists(db: Database, tableName: string): boolean {
141
+ const result = query<{ name: string }>(
142
+ db,
143
+ "SELECT name FROM sqlite_master WHERE type='table' AND name=?",
144
+ [tableName]
145
+ );
146
+ return result.rows.length > 0;
147
+ }
package/src/types.ts ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Type definitions for docker-sqlite
3
+ */
4
+
5
+ import type { Database } from "sql.js";
6
+
7
+ /**
8
+ * Configuration for SQLite connection
9
+ */
10
+ export interface ConnectionConfig {
11
+ /** Path to the SQLite database file. Use ":memory:" for in-memory database */
12
+ dbPath: string;
13
+ }
14
+
15
+ /**
16
+ * Callback function for withConnection
17
+ */
18
+ export type ConnectionCallback<T> = (db: Database) => T | Promise<T>;
19
+
20
+ /**
21
+ * Result of a query operation
22
+ */
23
+ export interface QueryResult<T = Record<string, unknown>> {
24
+ /** Column names */
25
+ columns: string[];
26
+ /** Row values */
27
+ rows: T[];
28
+ }
29
+
30
+ /**
31
+ * Result of an execute operation (INSERT, UPDATE, DELETE)
32
+ */
33
+ export interface ExecuteResult {
34
+ /** Number of rows affected */
35
+ changes: number;
36
+ }
37
+
38
+ /**
39
+ * Migration definition
40
+ */
41
+ export interface Migration {
42
+ /** Migration version (must be unique and sequential) */
43
+ version: number;
44
+ /** Description of the migration */
45
+ description: string;
46
+ /** SQL to apply the migration */
47
+ up: string;
48
+ /** SQL to revert the migration (optional) */
49
+ down?: string;
50
+ }
51
+
52
+ /**
53
+ * Migration status
54
+ */
55
+ export interface MigrationStatus {
56
+ /** Current version (0 if no migrations applied) */
57
+ currentVersion: number;
58
+ /** List of applied migrations */
59
+ appliedMigrations: number[];
60
+ /** List of pending migrations */
61
+ pendingMigrations: Migration[];
62
+ }