schema-seed-adapter-sqlite 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 schema-seed contributors
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 ADDED
@@ -0,0 +1,5 @@
1
+ # @schema-seed/adapter-sqlite
2
+
3
+ Part of the [schema-seed](https://github.com/AliNazar-111/schema-seed) project.
4
+
5
+ For full documentation and usage, please visit the [main repository](https://github.com/AliNazar-111/schema-seed).
package/dist/index.cjs ADDED
@@ -0,0 +1,177 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ SqliteAdapter: () => SqliteAdapter,
34
+ createSqliteAdapter: () => createSqliteAdapter
35
+ });
36
+ module.exports = __toCommonJS(index_exports);
37
+ var import_better_sqlite3 = __toESM(require("better-sqlite3"), 1);
38
+ var import_schema_seed_core = require("schema-seed-core");
39
+ var SqliteAdapter = class {
40
+ db = null;
41
+ filename;
42
+ constructor(filename) {
43
+ this.filename = filename;
44
+ }
45
+ async connect() {
46
+ this.db = new import_better_sqlite3.default(this.filename);
47
+ this.db.pragma("foreign_keys = ON");
48
+ }
49
+ async disconnect() {
50
+ if (this.db) {
51
+ this.db.close();
52
+ this.db = null;
53
+ }
54
+ }
55
+ async begin() {
56
+ this.db?.prepare("BEGIN").run();
57
+ }
58
+ async commit() {
59
+ this.db?.prepare("COMMIT").run();
60
+ }
61
+ async rollback() {
62
+ this.db?.prepare("ROLLBACK").run();
63
+ }
64
+ async introspectSchema() {
65
+ if (!this.db) throw new Error("Not connected");
66
+ const schema = { tables: {} };
67
+ const tables = this.db.prepare(`
68
+ SELECT name FROM sqlite_master
69
+ WHERE type='table' AND name NOT LIKE 'sqlite_%'
70
+ `).all();
71
+ for (const table of tables) {
72
+ const tableName = table.name;
73
+ schema.tables[tableName] = {
74
+ name: tableName,
75
+ columns: {},
76
+ foreignKeys: [],
77
+ uniqueConstraints: []
78
+ };
79
+ const columns = this.db.prepare(`PRAGMA table_info("${tableName}")`).all();
80
+ for (const col of columns) {
81
+ const colName = col.name;
82
+ const column = {
83
+ name: colName,
84
+ type: this.mapSqliteType(col.type),
85
+ rawType: col.type,
86
+ nullable: col.notnull === 0,
87
+ defaultValue: col.dflt_value,
88
+ isAutoIncrement: false
89
+ // SQLite handles this via rowid or AUTOINCREMENT keyword
90
+ };
91
+ if (col.pk > 0) {
92
+ if (!schema.tables[tableName].primaryKey) {
93
+ schema.tables[tableName].primaryKey = { columns: [] };
94
+ }
95
+ schema.tables[tableName].primaryKey.columns.push(colName);
96
+ if (column.type === import_schema_seed_core.NormalizedSqlType.INT || column.type === import_schema_seed_core.NormalizedSqlType.BIGINT) {
97
+ column.isAutoIncrement = true;
98
+ }
99
+ }
100
+ schema.tables[tableName].columns[colName] = column;
101
+ }
102
+ const fks = this.db.prepare(`PRAGMA foreign_key_list("${tableName}")`).all();
103
+ for (const fk of fks) {
104
+ schema.tables[tableName].foreignKeys.push({
105
+ columns: [fk.from],
106
+ referencedTable: fk.table,
107
+ referencedColumns: [fk.to]
108
+ });
109
+ }
110
+ const indexes = this.db.prepare(`PRAGMA index_list("${tableName}")`).all();
111
+ for (const idx of indexes) {
112
+ if (idx.unique === 1 && idx.origin !== "pk") {
113
+ const idxInfo = this.db.prepare(`PRAGMA index_info("${idx.name}")`).all();
114
+ schema.tables[tableName].uniqueConstraints.push({
115
+ name: idx.name,
116
+ columns: idxInfo.map((info) => info.name)
117
+ });
118
+ }
119
+ }
120
+ }
121
+ return schema;
122
+ }
123
+ async insertBatch(batch) {
124
+ if (!this.db) throw new Error("Not connected");
125
+ const { tableName, rows } = batch;
126
+ if (rows.length === 0) return;
127
+ const columns = Object.keys(rows[0]);
128
+ const placeholders = columns.map(() => "?").join(", ");
129
+ const query = `INSERT INTO "${tableName}" (${columns.map((c) => `"${c}"`).join(", ")}) VALUES (${placeholders})`;
130
+ const stmt = this.db.prepare(query);
131
+ const insertMany = this.db.transaction((data) => {
132
+ for (const row of data) {
133
+ const values = columns.map((col) => row[col]);
134
+ stmt.run(values);
135
+ }
136
+ });
137
+ insertMany(rows);
138
+ }
139
+ async truncateTables(tableNames) {
140
+ if (!this.db) throw new Error("Not connected");
141
+ this.db.pragma("foreign_keys = OFF");
142
+ try {
143
+ for (const table of tableNames) {
144
+ this.db.prepare(`DELETE FROM "${table}"`).run();
145
+ this.db.prepare(`DELETE FROM sqlite_sequence WHERE name = ?`).run(table);
146
+ }
147
+ } finally {
148
+ this.db.pragma("foreign_keys = ON");
149
+ }
150
+ }
151
+ capabilities = {
152
+ enums: false,
153
+ deferrableConstraints: false,
154
+ returning: true,
155
+ identityInsert: true
156
+ // SQLite allows inserting into PKs
157
+ };
158
+ mapSqliteType(sqliteType) {
159
+ const type = sqliteType.toUpperCase();
160
+ if (type.includes("INT")) return import_schema_seed_core.NormalizedSqlType.INT;
161
+ if (type.includes("CHAR") || type.includes("TEXT") || type === "") return import_schema_seed_core.NormalizedSqlType.STRING;
162
+ if (type.includes("BLOB")) return import_schema_seed_core.NormalizedSqlType.BINARY;
163
+ if (type.includes("REAL") || type.includes("FLOA") || type.includes("DOUB")) return import_schema_seed_core.NormalizedSqlType.FLOAT;
164
+ if (type.includes("BOOL")) return import_schema_seed_core.NormalizedSqlType.BOOLEAN;
165
+ if (type.includes("DATE") || type.includes("TIME")) return import_schema_seed_core.NormalizedSqlType.DATETIME;
166
+ return import_schema_seed_core.NormalizedSqlType.STRING;
167
+ }
168
+ };
169
+ function createSqliteAdapter(filename) {
170
+ return new SqliteAdapter(filename);
171
+ }
172
+ // Annotate the CommonJS export names for ESM import in node:
173
+ 0 && (module.exports = {
174
+ SqliteAdapter,
175
+ createSqliteAdapter
176
+ });
177
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import Database from 'better-sqlite3'\nimport {\n SqlAdapter,\n SchemaGraph,\n SeedBatch,\n NormalizedSqlType,\n TableSchema,\n ColumnSchema\n} from 'schema-seed-core'\n\nexport class SqliteAdapter implements SqlAdapter {\n private db: Database.Database | null = null\n private filename: string\n\n constructor(filename: string) {\n this.filename = filename\n }\n\n async connect(): Promise<void> {\n this.db = new Database(this.filename)\n this.db.pragma('foreign_keys = ON')\n }\n\n async disconnect(): Promise<void> {\n if (this.db) {\n this.db.close()\n this.db = null\n }\n }\n\n async begin(): Promise<void> {\n this.db?.prepare('BEGIN').run()\n }\n\n async commit(): Promise<void> {\n this.db?.prepare('COMMIT').run()\n }\n\n async rollback(): Promise<void> {\n this.db?.prepare('ROLLBACK').run()\n }\n\n async introspectSchema(): Promise<SchemaGraph> {\n if (!this.db) throw new Error('Not connected')\n\n const schema: SchemaGraph = { tables: {} }\n\n // Get tables\n const tables = this.db.prepare(`\n SELECT name FROM sqlite_master \n WHERE type='table' AND name NOT LIKE 'sqlite_%'\n `).all() as { name: string }[]\n\n for (const table of tables) {\n const tableName = table.name\n schema.tables[tableName] = {\n name: tableName,\n columns: {},\n foreignKeys: [],\n uniqueConstraints: []\n }\n\n // Get columns\n const columns = this.db.prepare(`PRAGMA table_info(\"${tableName}\")`).all() as any[]\n for (const col of columns) {\n const colName = col.name\n const column: ColumnSchema = {\n name: colName,\n type: this.mapSqliteType(col.type),\n rawType: col.type,\n nullable: col.notnull === 0,\n defaultValue: col.dflt_value,\n isAutoIncrement: false // SQLite handles this via rowid or AUTOINCREMENT keyword\n }\n\n if (col.pk > 0) {\n if (!schema.tables[tableName].primaryKey) {\n schema.tables[tableName].primaryKey = { columns: [] }\n }\n schema.tables[tableName].primaryKey!.columns.push(colName)\n // In SQLite, an INTEGER PRIMARY KEY is automatically auto-incrementing\n if (column.type === NormalizedSqlType.INT || column.type === NormalizedSqlType.BIGINT) {\n column.isAutoIncrement = true\n }\n }\n\n schema.tables[tableName].columns[colName] = column\n }\n\n // Get Foreign Keys\n const fks = this.db.prepare(`PRAGMA foreign_key_list(\"${tableName}\")`).all() as any[]\n for (const fk of fks) {\n schema.tables[tableName].foreignKeys.push({\n columns: [fk.from],\n referencedTable: fk.table,\n referencedColumns: [fk.to]\n })\n }\n\n // Get Unique Constraints\n const indexes = this.db.prepare(`PRAGMA index_list(\"${tableName}\")`).all() as any[]\n for (const idx of indexes) {\n if (idx.unique === 1 && idx.origin !== 'pk') {\n const idxInfo = this.db.prepare(`PRAGMA index_info(\"${idx.name}\")`).all() as any[]\n schema.tables[tableName].uniqueConstraints.push({\n name: idx.name,\n columns: idxInfo.map(info => info.name)\n })\n }\n }\n }\n\n return schema\n }\n\n async insertBatch(batch: SeedBatch): Promise<void> {\n if (!this.db) throw new Error('Not connected')\n const { tableName, rows } = batch\n if (rows.length === 0) return\n\n const columns = Object.keys(rows[0])\n const placeholders = columns.map(() => '?').join(', ')\n const query = `INSERT INTO \"${tableName}\" (${columns.map(c => `\"${c}\"`).join(', ')}) VALUES (${placeholders})`\n\n const stmt = this.db.prepare(query)\n\n // better-sqlite3 is sync, but we are in an async method\n // We can use a transaction for performance\n const insertMany = this.db.transaction((data: any[]) => {\n for (const row of data) {\n const values = columns.map(col => row[col])\n stmt.run(values)\n }\n })\n\n insertMany(rows)\n }\n\n async truncateTables(tableNames: string[]): Promise<void> {\n if (!this.db) throw new Error('Not connected')\n\n this.db.pragma('foreign_keys = OFF')\n try {\n for (const table of tableNames) {\n this.db.prepare(`DELETE FROM \"${table}\"`).run()\n // Reset auto-increment\n this.db.prepare(`DELETE FROM sqlite_sequence WHERE name = ?`).run(table)\n }\n } finally {\n this.db.pragma('foreign_keys = ON')\n }\n }\n\n readonly capabilities = {\n enums: false,\n deferrableConstraints: false,\n returning: true,\n identityInsert: true // SQLite allows inserting into PKs\n }\n\n private mapSqliteType(sqliteType: string): NormalizedSqlType {\n const type = sqliteType.toUpperCase()\n if (type.includes('INT')) return NormalizedSqlType.INT\n if (type.includes('CHAR') || type.includes('TEXT') || type === '') return NormalizedSqlType.STRING\n if (type.includes('BLOB')) return NormalizedSqlType.BINARY\n if (type.includes('REAL') || type.includes('FLOA') || type.includes('DOUB')) return NormalizedSqlType.FLOAT\n if (type.includes('BOOL')) return NormalizedSqlType.BOOLEAN\n if (type.includes('DATE') || type.includes('TIME')) return NormalizedSqlType.DATETIME\n\n return NormalizedSqlType.STRING\n }\n}\n\nexport function createSqliteAdapter(filename: string): SqliteAdapter {\n return new SqliteAdapter(filename)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4BAAqB;AACrB,8BAOO;AAEA,IAAM,gBAAN,MAA0C;AAAA,EACvC,KAA+B;AAAA,EAC/B;AAAA,EAER,YAAY,UAAkB;AAC5B,SAAK,WAAW;AAAA,EAClB;AAAA,EAEA,MAAM,UAAyB;AAC7B,SAAK,KAAK,IAAI,sBAAAA,QAAS,KAAK,QAAQ;AACpC,SAAK,GAAG,OAAO,mBAAmB;AAAA,EACpC;AAAA,EAEA,MAAM,aAA4B;AAChC,QAAI,KAAK,IAAI;AACX,WAAK,GAAG,MAAM;AACd,WAAK,KAAK;AAAA,IACZ;AAAA,EACF;AAAA,EAEA,MAAM,QAAuB;AAC3B,SAAK,IAAI,QAAQ,OAAO,EAAE,IAAI;AAAA,EAChC;AAAA,EAEA,MAAM,SAAwB;AAC5B,SAAK,IAAI,QAAQ,QAAQ,EAAE,IAAI;AAAA,EACjC;AAAA,EAEA,MAAM,WAA0B;AAC9B,SAAK,IAAI,QAAQ,UAAU,EAAE,IAAI;AAAA,EACnC;AA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AM,IAAI,MAAM,eAAe;AAE7C,SAAK,GAAG,OAAO,oBAAoB;AACnC,QAAI;AACF,iBAAW,SAAS,YAAY;AAC9B,aAAK,GAAG,QAAQ,gBAAgB,KAAK,GAAG,EAAE,IAAI;AAE9C,aAAK,GAAG,QAAQ,4CAA4C,EAAE,IAAI,KAAK;AAAA,MACzE;AAAA,IACF,UAAE;AACA,WAAK,GAAG,OAAO,mBAAmB;AAAA,IACpC;AAAA,EACF;AAAA,EAES,eAAe;AAAA,IACtB,OAAO;AAAA,IACP,uBAAuB;AAAA,IACvB,WAAW;AAAA,IACX,gBAAgB;AAAA;AAAA,EAClB;AAAA,EAEQ,cAAc,YAAuC;AAC3D,UAAM,OAAO,WAAW,YAAY;AACpC,QAAI,KAAK,SAAS,KAAK,EAAG,QAAO,0CAAkB;AACnD,QAAI,KAAK,SAAS,MAAM,KAAK,KAAK,SAAS,MAAM,KAAK,SAAS,GAAI,QAAO,0CAAkB;AAC5F,QAAI,KAAK,SAAS,MAAM,EAAG,QAAO,0CAAkB;AACpD,QAAI,KAAK,SAAS,MAAM,KAAK,KAAK,SAAS,MAAM,KAAK,KAAK,SAAS,MAAM,EAAG,QAAO,0CAAkB;AACtG,QAAI,KAAK,SAAS,MAAM,EAAG,QAAO,0CAAkB;AACpD,QAAI,KAAK,SAAS,MAAM,KAAK,KAAK,SAAS,MAAM,EAAG,QAAO,0CAAkB;AAE7E,WAAO,0CAAkB;AAAA,EAC3B;AACF;AAEO,SAAS,oBAAoB,UAAiC;AACnE,SAAO,IAAI,cAAc,QAAQ;AACnC;","names":["Database"]}
@@ -0,0 +1,25 @@
1
+ import { SqlAdapter, SchemaGraph, SeedBatch } from 'schema-seed-core';
2
+
3
+ declare class SqliteAdapter implements SqlAdapter {
4
+ private db;
5
+ private filename;
6
+ constructor(filename: string);
7
+ connect(): Promise<void>;
8
+ disconnect(): Promise<void>;
9
+ begin(): Promise<void>;
10
+ commit(): Promise<void>;
11
+ rollback(): Promise<void>;
12
+ introspectSchema(): Promise<SchemaGraph>;
13
+ insertBatch(batch: SeedBatch): Promise<void>;
14
+ truncateTables(tableNames: string[]): Promise<void>;
15
+ readonly capabilities: {
16
+ enums: boolean;
17
+ deferrableConstraints: boolean;
18
+ returning: boolean;
19
+ identityInsert: boolean;
20
+ };
21
+ private mapSqliteType;
22
+ }
23
+ declare function createSqliteAdapter(filename: string): SqliteAdapter;
24
+
25
+ export { SqliteAdapter, createSqliteAdapter };
@@ -0,0 +1,25 @@
1
+ import { SqlAdapter, SchemaGraph, SeedBatch } from 'schema-seed-core';
2
+
3
+ declare class SqliteAdapter implements SqlAdapter {
4
+ private db;
5
+ private filename;
6
+ constructor(filename: string);
7
+ connect(): Promise<void>;
8
+ disconnect(): Promise<void>;
9
+ begin(): Promise<void>;
10
+ commit(): Promise<void>;
11
+ rollback(): Promise<void>;
12
+ introspectSchema(): Promise<SchemaGraph>;
13
+ insertBatch(batch: SeedBatch): Promise<void>;
14
+ truncateTables(tableNames: string[]): Promise<void>;
15
+ readonly capabilities: {
16
+ enums: boolean;
17
+ deferrableConstraints: boolean;
18
+ returning: boolean;
19
+ identityInsert: boolean;
20
+ };
21
+ private mapSqliteType;
22
+ }
23
+ declare function createSqliteAdapter(filename: string): SqliteAdapter;
24
+
25
+ export { SqliteAdapter, createSqliteAdapter };
package/dist/index.js ADDED
@@ -0,0 +1,143 @@
1
+ // src/index.ts
2
+ import Database from "better-sqlite3";
3
+ import {
4
+ NormalizedSqlType
5
+ } from "schema-seed-core";
6
+ var SqliteAdapter = class {
7
+ db = null;
8
+ filename;
9
+ constructor(filename) {
10
+ this.filename = filename;
11
+ }
12
+ async connect() {
13
+ this.db = new Database(this.filename);
14
+ this.db.pragma("foreign_keys = ON");
15
+ }
16
+ async disconnect() {
17
+ if (this.db) {
18
+ this.db.close();
19
+ this.db = null;
20
+ }
21
+ }
22
+ async begin() {
23
+ this.db?.prepare("BEGIN").run();
24
+ }
25
+ async commit() {
26
+ this.db?.prepare("COMMIT").run();
27
+ }
28
+ async rollback() {
29
+ this.db?.prepare("ROLLBACK").run();
30
+ }
31
+ async introspectSchema() {
32
+ if (!this.db) throw new Error("Not connected");
33
+ const schema = { tables: {} };
34
+ const tables = this.db.prepare(`
35
+ SELECT name FROM sqlite_master
36
+ WHERE type='table' AND name NOT LIKE 'sqlite_%'
37
+ `).all();
38
+ for (const table of tables) {
39
+ const tableName = table.name;
40
+ schema.tables[tableName] = {
41
+ name: tableName,
42
+ columns: {},
43
+ foreignKeys: [],
44
+ uniqueConstraints: []
45
+ };
46
+ const columns = this.db.prepare(`PRAGMA table_info("${tableName}")`).all();
47
+ for (const col of columns) {
48
+ const colName = col.name;
49
+ const column = {
50
+ name: colName,
51
+ type: this.mapSqliteType(col.type),
52
+ rawType: col.type,
53
+ nullable: col.notnull === 0,
54
+ defaultValue: col.dflt_value,
55
+ isAutoIncrement: false
56
+ // SQLite handles this via rowid or AUTOINCREMENT keyword
57
+ };
58
+ if (col.pk > 0) {
59
+ if (!schema.tables[tableName].primaryKey) {
60
+ schema.tables[tableName].primaryKey = { columns: [] };
61
+ }
62
+ schema.tables[tableName].primaryKey.columns.push(colName);
63
+ if (column.type === NormalizedSqlType.INT || column.type === NormalizedSqlType.BIGINT) {
64
+ column.isAutoIncrement = true;
65
+ }
66
+ }
67
+ schema.tables[tableName].columns[colName] = column;
68
+ }
69
+ const fks = this.db.prepare(`PRAGMA foreign_key_list("${tableName}")`).all();
70
+ for (const fk of fks) {
71
+ schema.tables[tableName].foreignKeys.push({
72
+ columns: [fk.from],
73
+ referencedTable: fk.table,
74
+ referencedColumns: [fk.to]
75
+ });
76
+ }
77
+ const indexes = this.db.prepare(`PRAGMA index_list("${tableName}")`).all();
78
+ for (const idx of indexes) {
79
+ if (idx.unique === 1 && idx.origin !== "pk") {
80
+ const idxInfo = this.db.prepare(`PRAGMA index_info("${idx.name}")`).all();
81
+ schema.tables[tableName].uniqueConstraints.push({
82
+ name: idx.name,
83
+ columns: idxInfo.map((info) => info.name)
84
+ });
85
+ }
86
+ }
87
+ }
88
+ return schema;
89
+ }
90
+ async insertBatch(batch) {
91
+ if (!this.db) throw new Error("Not connected");
92
+ const { tableName, rows } = batch;
93
+ if (rows.length === 0) return;
94
+ const columns = Object.keys(rows[0]);
95
+ const placeholders = columns.map(() => "?").join(", ");
96
+ const query = `INSERT INTO "${tableName}" (${columns.map((c) => `"${c}"`).join(", ")}) VALUES (${placeholders})`;
97
+ const stmt = this.db.prepare(query);
98
+ const insertMany = this.db.transaction((data) => {
99
+ for (const row of data) {
100
+ const values = columns.map((col) => row[col]);
101
+ stmt.run(values);
102
+ }
103
+ });
104
+ insertMany(rows);
105
+ }
106
+ async truncateTables(tableNames) {
107
+ if (!this.db) throw new Error("Not connected");
108
+ this.db.pragma("foreign_keys = OFF");
109
+ try {
110
+ for (const table of tableNames) {
111
+ this.db.prepare(`DELETE FROM "${table}"`).run();
112
+ this.db.prepare(`DELETE FROM sqlite_sequence WHERE name = ?`).run(table);
113
+ }
114
+ } finally {
115
+ this.db.pragma("foreign_keys = ON");
116
+ }
117
+ }
118
+ capabilities = {
119
+ enums: false,
120
+ deferrableConstraints: false,
121
+ returning: true,
122
+ identityInsert: true
123
+ // SQLite allows inserting into PKs
124
+ };
125
+ mapSqliteType(sqliteType) {
126
+ const type = sqliteType.toUpperCase();
127
+ if (type.includes("INT")) return NormalizedSqlType.INT;
128
+ if (type.includes("CHAR") || type.includes("TEXT") || type === "") return NormalizedSqlType.STRING;
129
+ if (type.includes("BLOB")) return NormalizedSqlType.BINARY;
130
+ if (type.includes("REAL") || type.includes("FLOA") || type.includes("DOUB")) return NormalizedSqlType.FLOAT;
131
+ if (type.includes("BOOL")) return NormalizedSqlType.BOOLEAN;
132
+ if (type.includes("DATE") || type.includes("TIME")) return NormalizedSqlType.DATETIME;
133
+ return NormalizedSqlType.STRING;
134
+ }
135
+ };
136
+ function createSqliteAdapter(filename) {
137
+ return new SqliteAdapter(filename);
138
+ }
139
+ export {
140
+ SqliteAdapter,
141
+ createSqliteAdapter
142
+ };
143
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import Database from 'better-sqlite3'\nimport {\n SqlAdapter,\n SchemaGraph,\n SeedBatch,\n NormalizedSqlType,\n TableSchema,\n ColumnSchema\n} from 'schema-seed-core'\n\nexport class SqliteAdapter implements SqlAdapter {\n private db: Database.Database | null = null\n private filename: string\n\n constructor(filename: string) {\n this.filename = filename\n }\n\n async connect(): Promise<void> {\n this.db = new Database(this.filename)\n this.db.pragma('foreign_keys = ON')\n }\n\n async disconnect(): Promise<void> {\n if (this.db) {\n this.db.close()\n this.db = null\n }\n }\n\n async begin(): Promise<void> {\n this.db?.prepare('BEGIN').run()\n }\n\n async commit(): Promise<void> {\n this.db?.prepare('COMMIT').run()\n }\n\n async rollback(): Promise<void> {\n this.db?.prepare('ROLLBACK').run()\n }\n\n async introspectSchema(): Promise<SchemaGraph> {\n if (!this.db) throw new Error('Not connected')\n\n const schema: SchemaGraph = { tables: {} }\n\n // Get tables\n const tables = this.db.prepare(`\n SELECT name FROM sqlite_master \n WHERE type='table' AND name NOT LIKE 'sqlite_%'\n `).all() as { name: string }[]\n\n for (const table of tables) {\n const tableName = table.name\n schema.tables[tableName] = {\n name: tableName,\n columns: {},\n foreignKeys: [],\n uniqueConstraints: []\n }\n\n // Get columns\n const columns = this.db.prepare(`PRAGMA table_info(\"${tableName}\")`).all() as any[]\n for (const col of columns) {\n const colName = col.name\n const column: ColumnSchema = {\n name: colName,\n type: this.mapSqliteType(col.type),\n rawType: col.type,\n nullable: col.notnull === 0,\n defaultValue: col.dflt_value,\n isAutoIncrement: false // SQLite handles this via rowid or AUTOINCREMENT keyword\n }\n\n if (col.pk > 0) {\n if (!schema.tables[tableName].primaryKey) {\n schema.tables[tableName].primaryKey = { columns: [] }\n }\n schema.tables[tableName].primaryKey!.columns.push(colName)\n // In SQLite, an INTEGER PRIMARY KEY is automatically auto-incrementing\n if (column.type === NormalizedSqlType.INT || column.type === NormalizedSqlType.BIGINT) {\n column.isAutoIncrement = true\n }\n }\n\n schema.tables[tableName].columns[colName] = column\n }\n\n // Get Foreign Keys\n const fks = this.db.prepare(`PRAGMA foreign_key_list(\"${tableName}\")`).all() as any[]\n for (const fk of fks) {\n schema.tables[tableName].foreignKeys.push({\n columns: [fk.from],\n referencedTable: fk.table,\n referencedColumns: [fk.to]\n })\n }\n\n // Get Unique Constraints\n const indexes = this.db.prepare(`PRAGMA index_list(\"${tableName}\")`).all() as any[]\n for (const idx of indexes) {\n if (idx.unique === 1 && idx.origin !== 'pk') {\n const idxInfo = this.db.prepare(`PRAGMA index_info(\"${idx.name}\")`).all() as any[]\n schema.tables[tableName].uniqueConstraints.push({\n name: idx.name,\n columns: idxInfo.map(info => info.name)\n })\n }\n }\n }\n\n return schema\n }\n\n async insertBatch(batch: SeedBatch): Promise<void> {\n if (!this.db) throw new Error('Not connected')\n const { tableName, rows } = batch\n if (rows.length === 0) return\n\n const columns = Object.keys(rows[0])\n const placeholders = columns.map(() => '?').join(', ')\n const query = `INSERT INTO \"${tableName}\" (${columns.map(c => `\"${c}\"`).join(', ')}) VALUES (${placeholders})`\n\n const stmt = this.db.prepare(query)\n\n // better-sqlite3 is sync, but we are in an async method\n // We can use a transaction for performance\n const insertMany = this.db.transaction((data: any[]) => {\n for (const row of data) {\n const values = columns.map(col => row[col])\n stmt.run(values)\n }\n })\n\n insertMany(rows)\n }\n\n async truncateTables(tableNames: string[]): Promise<void> {\n if (!this.db) throw new Error('Not connected')\n\n this.db.pragma('foreign_keys = OFF')\n try {\n for (const table of tableNames) {\n this.db.prepare(`DELETE FROM \"${table}\"`).run()\n // Reset auto-increment\n this.db.prepare(`DELETE FROM sqlite_sequence WHERE name = ?`).run(table)\n }\n } finally {\n this.db.pragma('foreign_keys = ON')\n }\n }\n\n readonly capabilities = {\n enums: false,\n deferrableConstraints: false,\n returning: true,\n identityInsert: true // SQLite allows inserting into PKs\n }\n\n private mapSqliteType(sqliteType: string): NormalizedSqlType {\n const type = sqliteType.toUpperCase()\n if (type.includes('INT')) return NormalizedSqlType.INT\n if (type.includes('CHAR') || type.includes('TEXT') || type === '') return NormalizedSqlType.STRING\n if (type.includes('BLOB')) return NormalizedSqlType.BINARY\n if (type.includes('REAL') || type.includes('FLOA') || type.includes('DOUB')) return NormalizedSqlType.FLOAT\n if (type.includes('BOOL')) return NormalizedSqlType.BOOLEAN\n if (type.includes('DATE') || type.includes('TIME')) return NormalizedSqlType.DATETIME\n\n return NormalizedSqlType.STRING\n }\n}\n\nexport function createSqliteAdapter(filename: string): SqliteAdapter {\n return new SqliteAdapter(filename)\n}\n"],"mappings":";AAAA,OAAO,cAAc;AACrB;AAAA,EAIE;AAAA,OAGK;AAEA,IAAM,gBAAN,MAA0C;AAAA,EACvC,KAA+B;AAAA,EAC/B;AAAA,EAER,YAAY,UAAkB;AAC5B,SAAK,WAAW;AAAA,EAClB;AAAA,EAEA,MAAM,UAAyB;AAC7B,SAAK,KAAK,IAAI,SAAS,KAAK,QAAQ;AACpC,SAAK,GAAG,OAAO,mBAAmB;AAAA,EACpC;AAAA,EAEA,MAAM,aAA4B;AAChC,QAAI,KAAK,IAAI;AACX,WAAK,GAAG,MAAM;AACd,WAAK,KAAK;AAAA,IACZ;AAAA,EACF;AAAA,EAEA,MAAM,QAAuB;AAC3B,SAAK,IAAI,QAAQ,OAAO,EAAE,IAAI;AAAA,EAChC;AAAA,EAEA,MAAM,SAAwB;AAC5B,SAAK,IAAI,QAAQ,QAAQ,EAAE,IAAI;AAAA,EACjC;AAAA,EAEA,MAAM,WAA0B;AAC9B,SAAK,IAAI,QAAQ,UAAU,EAAE,IAAI;AAAA,EACnC;AAAA,EAEA,MAAM,mBAAyC;AAC7C,QAAI,CAAC,KAAK,GAAI,OAAM,IAAI,MAAM,eAAe;AAE7C,UAAM,SAAsB,EAAE,QAAQ,CAAC,EAAE;AAGzC,UAAM,SAAS,KAAK,GAAG,QAAQ;AAAA;AAA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Q,4CAA4C,EAAE,IAAI,KAAK;AAAA,MACzE;AAAA,IACF,UAAE;AACA,WAAK,GAAG,OAAO,mBAAmB;AAAA,IACpC;AAAA,EACF;AAAA,EAES,eAAe;AAAA,IACtB,OAAO;AAAA,IACP,uBAAuB;AAAA,IACvB,WAAW;AAAA,IACX,gBAAgB;AAAA;AAAA,EAClB;AAAA,EAEQ,cAAc,YAAuC;AAC3D,UAAM,OAAO,WAAW,YAAY;AACpC,QAAI,KAAK,SAAS,KAAK,EAAG,QAAO,kBAAkB;AACnD,QAAI,KAAK,SAAS,MAAM,KAAK,KAAK,SAAS,MAAM,KAAK,SAAS,GAAI,QAAO,kBAAkB;AAC5F,QAAI,KAAK,SAAS,MAAM,EAAG,QAAO,kBAAkB;AACpD,QAAI,KAAK,SAAS,MAAM,KAAK,KAAK,SAAS,MAAM,KAAK,KAAK,SAAS,MAAM,EAAG,QAAO,kBAAkB;AACtG,QAAI,KAAK,SAAS,MAAM,EAAG,QAAO,kBAAkB;AACpD,QAAI,KAAK,SAAS,MAAM,KAAK,KAAK,SAAS,MAAM,EAAG,QAAO,kBAAkB;AAE7E,WAAO,kBAAkB;AAAA,EAC3B;AACF;AAEO,SAAS,oBAAoB,UAAiC;AACnE,SAAO,IAAI,cAAc,QAAQ;AACnC;","names":[]}
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "schema-seed-adapter-sqlite",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "SQLite adapter for schema-seed",
6
+ "author": "Ali Nazar",
7
+ "license": "MIT",
8
+ "private": false,
9
+ "sideEffects": false,
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/alinazar-111/schema-seed.git"
13
+ },
14
+ "homepage": "https://github.com/alinazar-111/schema-seed#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/alinazar-111/schema-seed/issues"
17
+ },
18
+ "keywords": [
19
+ "database",
20
+ "seeding",
21
+ "test-data",
22
+ "adapter",
23
+ "schema-seed"
24
+ ],
25
+ "main": "./dist/index.cjs",
26
+ "module": "./dist/index.js",
27
+ "types": "./dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.js",
32
+ "require": "./dist/index.cjs"
33
+ }
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "README.md",
38
+ "LICENSE"
39
+ ],
40
+ "dependencies": {
41
+ "better-sqlite3": "^11.3.0",
42
+ "schema-seed-core": "0.1.0"
43
+ },
44
+ "devDependencies": {
45
+ "@types/better-sqlite3": "^7.6.11",
46
+ "tsup": "^8.3.5",
47
+ "typescript": "^5.7.2",
48
+ "vitest": "^2.1.8"
49
+ },
50
+ "scripts": {
51
+ "build": "tsup",
52
+ "clean": "rm -rf dist",
53
+ "dev": "tsup --watch",
54
+ "lint": "eslint .",
55
+ "test": "vitest run --passWithNoTests",
56
+ "typecheck": "tsc --noEmit"
57
+ }
58
+ }