schema-seed-adapter-mssql 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 +21 -0
- package/README.md +5 -0
- package/dist/index.cjs +235 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +28 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.js +201 -0
- package/dist/index.js.map +1 -0
- package/package.json +58 -0
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
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
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
|
+
MssqlAdapter: () => MssqlAdapter,
|
|
34
|
+
createMssqlAdapter: () => createMssqlAdapter
|
|
35
|
+
});
|
|
36
|
+
module.exports = __toCommonJS(index_exports);
|
|
37
|
+
var import_mssql = __toESM(require("mssql"), 1);
|
|
38
|
+
var import_schema_seed_core = require("schema-seed-core");
|
|
39
|
+
var MssqlAdapter = class {
|
|
40
|
+
pool = null;
|
|
41
|
+
transaction = null;
|
|
42
|
+
config;
|
|
43
|
+
constructor(config) {
|
|
44
|
+
this.config = config;
|
|
45
|
+
}
|
|
46
|
+
async connect() {
|
|
47
|
+
this.pool = await new import_mssql.default.ConnectionPool(this.config).connect();
|
|
48
|
+
}
|
|
49
|
+
async disconnect() {
|
|
50
|
+
if (this.pool) {
|
|
51
|
+
await this.pool.close();
|
|
52
|
+
this.pool = null;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
async begin() {
|
|
56
|
+
this.transaction = new import_mssql.default.Transaction(this.pool);
|
|
57
|
+
await this.transaction.begin();
|
|
58
|
+
}
|
|
59
|
+
async commit() {
|
|
60
|
+
if (this.transaction) {
|
|
61
|
+
await this.transaction.commit();
|
|
62
|
+
this.transaction = null;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
async rollback() {
|
|
66
|
+
if (this.transaction) {
|
|
67
|
+
await this.transaction.rollback();
|
|
68
|
+
this.transaction = null;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
getRequest() {
|
|
72
|
+
if (this.transaction) return new import_mssql.default.Request(this.transaction);
|
|
73
|
+
if (this.pool) return new import_mssql.default.Request(this.pool);
|
|
74
|
+
throw new Error("Not connected");
|
|
75
|
+
}
|
|
76
|
+
async introspectSchema() {
|
|
77
|
+
const schema = { tables: {} };
|
|
78
|
+
const tablesRes = await this.getRequest().query(`
|
|
79
|
+
SELECT t.name AS table_name, s.name AS schema_name
|
|
80
|
+
FROM sys.tables t
|
|
81
|
+
JOIN sys.schemas s ON t.schema_id = s.schema_id
|
|
82
|
+
WHERE t.is_ms_shipped = 0
|
|
83
|
+
`);
|
|
84
|
+
for (const row of tablesRes.recordset) {
|
|
85
|
+
const tableName = row.table_name;
|
|
86
|
+
schema.tables[tableName] = {
|
|
87
|
+
name: tableName,
|
|
88
|
+
schema: row.schema_name,
|
|
89
|
+
columns: {},
|
|
90
|
+
foreignKeys: [],
|
|
91
|
+
uniqueConstraints: []
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
const columnsRes = await this.getRequest().query(`
|
|
95
|
+
SELECT
|
|
96
|
+
t.name AS table_name,
|
|
97
|
+
c.name AS column_name,
|
|
98
|
+
ty.name AS data_type,
|
|
99
|
+
c.is_nullable,
|
|
100
|
+
dc.definition AS column_default,
|
|
101
|
+
c.is_identity
|
|
102
|
+
FROM sys.columns c
|
|
103
|
+
JOIN sys.tables t ON c.object_id = t.object_id
|
|
104
|
+
JOIN sys.types ty ON c.user_type_id = ty.user_type_id
|
|
105
|
+
LEFT JOIN sys.default_constraints dc ON c.default_object_id = dc.object_id
|
|
106
|
+
WHERE t.is_ms_shipped = 0
|
|
107
|
+
`);
|
|
108
|
+
for (const row of columnsRes.recordset) {
|
|
109
|
+
if (!schema.tables[row.table_name]) continue;
|
|
110
|
+
const col = {
|
|
111
|
+
name: row.column_name,
|
|
112
|
+
type: this.mapMssqlType(row.data_type),
|
|
113
|
+
rawType: row.data_type,
|
|
114
|
+
nullable: row.is_nullable,
|
|
115
|
+
defaultValue: row.column_default,
|
|
116
|
+
isAutoIncrement: row.is_identity
|
|
117
|
+
};
|
|
118
|
+
schema.tables[row.table_name].columns[row.column_name] = col;
|
|
119
|
+
}
|
|
120
|
+
const fkRes = await this.getRequest().query(`
|
|
121
|
+
SELECT
|
|
122
|
+
obj.name AS constraint_name,
|
|
123
|
+
sch.name AS schema_name,
|
|
124
|
+
t.name AS table_name,
|
|
125
|
+
col.name AS column_name,
|
|
126
|
+
rt.name AS referenced_table_name,
|
|
127
|
+
rcol.name AS referenced_column_name
|
|
128
|
+
FROM sys.foreign_key_columns fkc
|
|
129
|
+
INNER JOIN sys.objects obj ON obj.object_id = fkc.constraint_object_id
|
|
130
|
+
INNER JOIN sys.tables t ON t.object_id = fkc.parent_object_id
|
|
131
|
+
INNER JOIN sys.schemas sch ON sch.schema_id = t.schema_id
|
|
132
|
+
INNER JOIN sys.columns col ON col.column_id = fkc.parent_column_id AND col.object_id = t.object_id
|
|
133
|
+
INNER JOIN sys.tables rt ON rt.object_id = fkc.referenced_object_id
|
|
134
|
+
INNER JOIN sys.columns rcol ON rcol.column_id = fkc.referenced_column_id AND rcol.object_id = rt.object_id
|
|
135
|
+
`);
|
|
136
|
+
for (const row of fkRes.recordset) {
|
|
137
|
+
if (!schema.tables[row.table_name]) continue;
|
|
138
|
+
schema.tables[row.table_name].foreignKeys.push({
|
|
139
|
+
name: row.constraint_name,
|
|
140
|
+
columns: [row.column_name],
|
|
141
|
+
referencedTable: row.referenced_table_name,
|
|
142
|
+
referencedColumns: [row.referenced_column_name]
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
const pkRes = await this.getRequest().query(`
|
|
146
|
+
SELECT
|
|
147
|
+
t.name AS table_name,
|
|
148
|
+
c.name AS column_name
|
|
149
|
+
FROM sys.indexes i
|
|
150
|
+
INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
|
|
151
|
+
INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
|
|
152
|
+
INNER JOIN sys.tables t ON i.object_id = t.object_id
|
|
153
|
+
WHERE i.is_primary_key = 1
|
|
154
|
+
`);
|
|
155
|
+
for (const row of pkRes.recordset) {
|
|
156
|
+
if (!schema.tables[row.table_name]) continue;
|
|
157
|
+
if (!schema.tables[row.table_name].primaryKey) {
|
|
158
|
+
schema.tables[row.table_name].primaryKey = { columns: [] };
|
|
159
|
+
}
|
|
160
|
+
schema.tables[row.table_name].primaryKey.columns.push(row.column_name);
|
|
161
|
+
}
|
|
162
|
+
return schema;
|
|
163
|
+
}
|
|
164
|
+
async insertBatch(batch) {
|
|
165
|
+
if (!this.pool) throw new Error("Not connected");
|
|
166
|
+
const { tableName, rows } = batch;
|
|
167
|
+
if (rows.length === 0) return;
|
|
168
|
+
const columns = Object.keys(rows[0]);
|
|
169
|
+
const tableSchema = (await this.introspectSchema()).tables[tableName];
|
|
170
|
+
const hasIdentity = Object.values(tableSchema.columns).some((c) => c.isAutoIncrement);
|
|
171
|
+
const request = this.getRequest();
|
|
172
|
+
if (hasIdentity) {
|
|
173
|
+
await this.getRequest().query(`SET IDENTITY_INSERT [${tableName}] ON`);
|
|
174
|
+
}
|
|
175
|
+
try {
|
|
176
|
+
const valuesStrings = [];
|
|
177
|
+
for (let i = 0; i < rows.length; i++) {
|
|
178
|
+
const row = rows[i];
|
|
179
|
+
const rowParams = [];
|
|
180
|
+
for (let j = 0; j < columns.length; j++) {
|
|
181
|
+
const colName = columns[j];
|
|
182
|
+
const paramName = `p${i}_${j}`;
|
|
183
|
+
request.input(paramName, row[colName]);
|
|
184
|
+
rowParams.push(`@${paramName}`);
|
|
185
|
+
}
|
|
186
|
+
valuesStrings.push(`(${rowParams.join(", ")})`);
|
|
187
|
+
}
|
|
188
|
+
const query = `INSERT INTO [${tableName}] (${columns.map((c) => `[${c}]`).join(", ")}) VALUES ${valuesStrings.join(", ")}`;
|
|
189
|
+
await request.query(query);
|
|
190
|
+
} finally {
|
|
191
|
+
if (hasIdentity) {
|
|
192
|
+
await this.getRequest().query(`SET IDENTITY_INSERT [${tableName}] OFF`);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
async truncateTables(tableNames) {
|
|
197
|
+
if (!this.pool) throw new Error("Not connected");
|
|
198
|
+
for (const table of tableNames) {
|
|
199
|
+
try {
|
|
200
|
+
await this.getRequest().query(`TRUNCATE TABLE [${table}]`);
|
|
201
|
+
} catch (err) {
|
|
202
|
+
await this.getRequest().query(`DELETE FROM [${table}]`);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
capabilities = {
|
|
207
|
+
enums: false,
|
|
208
|
+
deferrableConstraints: false,
|
|
209
|
+
returning: true,
|
|
210
|
+
identityInsert: true
|
|
211
|
+
};
|
|
212
|
+
mapMssqlType(mssqlType) {
|
|
213
|
+
const type = mssqlType.toLowerCase();
|
|
214
|
+
if (type.includes("int")) return import_schema_seed_core.NormalizedSqlType.INT;
|
|
215
|
+
if (type.includes("bigint")) return import_schema_seed_core.NormalizedSqlType.BIGINT;
|
|
216
|
+
if (type.includes("char") || type.includes("text") || type === "varchar" || type === "nvarchar") return import_schema_seed_core.NormalizedSqlType.STRING;
|
|
217
|
+
if (type === "bit") return import_schema_seed_core.NormalizedSqlType.BOOLEAN;
|
|
218
|
+
if (type === "date") return import_schema_seed_core.NormalizedSqlType.DATE;
|
|
219
|
+
if (type === "datetime" || type === "datetime2" || type === "smalldatetime") return import_schema_seed_core.NormalizedSqlType.DATETIME;
|
|
220
|
+
if (type === "decimal" || type === "numeric" || type === "money" || type === "smallmoney") return import_schema_seed_core.NormalizedSqlType.DECIMAL;
|
|
221
|
+
if (type === "float" || type === "real") return import_schema_seed_core.NormalizedSqlType.FLOAT;
|
|
222
|
+
if (type === "uniqueidentifier") return import_schema_seed_core.NormalizedSqlType.UUID;
|
|
223
|
+
if (type === "varbinary" || type === "binary" || type === "image") return import_schema_seed_core.NormalizedSqlType.BINARY;
|
|
224
|
+
return import_schema_seed_core.NormalizedSqlType.STRING;
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
function createMssqlAdapter(config) {
|
|
228
|
+
return new MssqlAdapter(config);
|
|
229
|
+
}
|
|
230
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
231
|
+
0 && (module.exports = {
|
|
232
|
+
MssqlAdapter,
|
|
233
|
+
createMssqlAdapter
|
|
234
|
+
});
|
|
235
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import mssql from 'mssql'\nimport {\n SqlAdapter,\n SchemaGraph,\n SeedBatch,\n NormalizedSqlType,\n TableSchema,\n ColumnSchema\n} from 'schema-seed-core'\n\nexport class MssqlAdapter implements SqlAdapter {\n private pool: mssql.ConnectionPool | null = null\n private transaction: mssql.Transaction | null = null\n private config: string | mssql.config\n\n constructor(config: string | mssql.config) {\n this.config = config\n }\n\n async connect(): Promise<void> {\n this.pool = await new mssql.ConnectionPool(this.config as any).connect()\n }\n\n async disconnect(): Promise<void> {\n if (this.pool) {\n await this.pool.close()\n this.pool = null\n }\n }\n\n async begin(): Promise<void> {\n this.transaction = new mssql.Transaction(this.pool!)\n await this.transaction.begin()\n }\n\n async commit(): Promise<void> {\n if (this.transaction) {\n await this.transaction.commit()\n this.transaction = null\n }\n }\n\n async rollback(): Promise<void> {\n if (this.transaction) {\n await this.transaction.rollback()\n this.transaction = null\n }\n }\n\n private getRequest(): mssql.Request {\n if (this.transaction) return new mssql.Request(this.transaction)\n if (this.pool) return new mssql.Request(this.pool)\n throw new Error('Not connected')\n }\n\n async introspectSchema(): Promise<SchemaGraph> {\n const schema: SchemaGraph = { tables: {} }\n\n // Get tables\n const tablesRes = await this.getRequest().query(`\n SELECT t.name AS table_name, s.name AS schema_name\n FROM sys.tables t\n JOIN sys.schemas s ON t.schema_id = s.schema_id\n WHERE t.is_ms_shipped = 0\n `)\n\n for (const row of tablesRes.recordset) {\n const tableName = row.table_name\n schema.tables[tableName] = {\n name: tableName,\n schema: row.schema_name,\n columns: {},\n foreignKeys: [],\n uniqueConstraints: []\n }\n }\n\n // Get columns\n const columnsRes = await this.getRequest().query(`\n SELECT \n t.name AS table_name,\n c.name AS column_name,\n ty.name AS data_type,\n c.is_nullable,\n dc.definition AS column_default,\n c.is_identity\n FROM sys.columns c\n JOIN sys.tables t ON c.object_id = t.object_id\n JOIN sys.types ty ON c.user_type_id = ty.user_type_id\n LEFT JOIN sys.default_constraints dc ON c.default_object_id = dc.object_id\n WHERE t.is_ms_shipped = 0\n `)\n\n for (const row of columnsRes.recordset) {\n if (!schema.tables[row.table_name]) continue\n\n const col: ColumnSchema = {\n name: row.column_name,\n type: this.mapMssqlType(row.data_type),\n rawType: row.data_type,\n nullable: row.is_nullable,\n defaultValue: row.column_default,\n isAutoIncrement: row.is_identity\n }\n schema.tables[row.table_name].columns[row.column_name] = col\n }\n\n // Get Foreign Keys\n const fkRes = await this.getRequest().query(`\n SELECT \n obj.name AS constraint_name,\n sch.name AS schema_name,\n t.name AS table_name,\n col.name AS column_name,\n rt.name AS referenced_table_name,\n rcol.name AS referenced_column_name\n FROM sys.foreign_key_columns fkc\n INNER JOIN sys.objects obj ON obj.object_id = fkc.constraint_object_id\n INNER JOIN sys.tables t ON t.object_id = fkc.parent_object_id\n INNER JOIN sys.schemas sch ON sch.schema_id = t.schema_id\n INNER JOIN sys.columns col ON col.column_id = fkc.parent_column_id AND col.object_id = t.object_id\n INNER JOIN sys.tables rt ON rt.object_id = fkc.referenced_object_id\n INNER JOIN sys.columns rcol ON rcol.column_id = fkc.referenced_column_id AND rcol.object_id = rt.object_id\n `)\n\n for (const row of fkRes.recordset) {\n if (!schema.tables[row.table_name]) continue\n schema.tables[row.table_name].foreignKeys.push({\n name: row.constraint_name,\n columns: [row.column_name],\n referencedTable: row.referenced_table_name,\n referencedColumns: [row.referenced_column_name]\n })\n }\n\n // Get Primary Keys\n const pkRes = await this.getRequest().query(`\n SELECT \n t.name AS table_name,\n c.name AS column_name\n FROM sys.indexes i\n INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id\n INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id\n INNER JOIN sys.tables t ON i.object_id = t.object_id\n WHERE i.is_primary_key = 1\n `)\n\n for (const row of pkRes.recordset) {\n if (!schema.tables[row.table_name]) continue\n if (!schema.tables[row.table_name].primaryKey) {\n schema.tables[row.table_name].primaryKey = { columns: [] }\n }\n schema.tables[row.table_name].primaryKey!.columns.push(row.column_name)\n }\n\n return schema\n }\n\n async insertBatch(batch: SeedBatch): Promise<void> {\n if (!this.pool) 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\n // Check if any column is an identity column\n const tableSchema = (await this.introspectSchema()).tables[tableName]\n const hasIdentity = Object.values(tableSchema.columns).some(c => c.isAutoIncrement)\n\n const request = this.getRequest()\n\n if (hasIdentity) {\n await this.getRequest().query(`SET IDENTITY_INSERT [${tableName}] ON`)\n }\n\n try {\n // MSSQL doesn't support multi-row INSERT with parameters in a simple way like MySQL/Postgres\n // We'll use a Table-Valued Parameter or just multiple inserts in a transaction if small\n // For simplicity here, we'll build a large query string with parameters\n\n const valuesStrings = []\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i]\n const rowParams = []\n for (let j = 0; j < columns.length; j++) {\n const colName = columns[j]\n const paramName = `p${i}_${j}`\n request.input(paramName, row[colName])\n rowParams.push(`@${paramName}`)\n }\n valuesStrings.push(`(${rowParams.join(', ')})`)\n }\n\n const query = `INSERT INTO [${tableName}] (${columns.map(c => `[${c}]`).join(', ')}) VALUES ${valuesStrings.join(', ')}`\n await request.query(query)\n } finally {\n if (hasIdentity) {\n await this.getRequest().query(`SET IDENTITY_INSERT [${tableName}] OFF`)\n }\n }\n }\n\n async truncateTables(tableNames: string[]): Promise<void> {\n if (!this.pool) throw new Error('Not connected')\n\n for (const table of tableNames) {\n try {\n await this.getRequest().query(`TRUNCATE TABLE [${table}]`)\n } catch (err) {\n // If TRUNCATE fails (e.g. due to FK), fallback to DELETE\n await this.getRequest().query(`DELETE FROM [${table}]`)\n }\n }\n }\n\n readonly capabilities = {\n enums: false,\n deferrableConstraints: false,\n returning: true,\n identityInsert: true\n }\n\n private mapMssqlType(mssqlType: string): NormalizedSqlType {\n const type = mssqlType.toLowerCase()\n if (type.includes('int')) return NormalizedSqlType.INT\n if (type.includes('bigint')) return NormalizedSqlType.BIGINT\n if (type.includes('char') || type.includes('text') || type === 'varchar' || type === 'nvarchar') return NormalizedSqlType.STRING\n if (type === 'bit') return NormalizedSqlType.BOOLEAN\n if (type === 'date') return NormalizedSqlType.DATE\n if (type === 'datetime' || type === 'datetime2' || type === 'smalldatetime') return NormalizedSqlType.DATETIME\n if (type === 'decimal' || type === 'numeric' || type === 'money' || type === 'smallmoney') return NormalizedSqlType.DECIMAL\n if (type === 'float' || type === 'real') return NormalizedSqlType.FLOAT\n if (type === 'uniqueidentifier') return NormalizedSqlType.UUID\n if (type === 'varbinary' || type === 'binary' || type === 'image') return NormalizedSqlType.BINARY\n\n return NormalizedSqlType.STRING\n }\n}\n\nexport function createMssqlAdapter(config: string | mssql.config): MssqlAdapter {\n return new MssqlAdapter(config)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAkB;AAClB,8BAOO;AAEA,IAAM,eAAN,MAAyC;AAAA,EACtC,OAAoC;AAAA,EACpC,cAAwC;AAAA,EACxC;AAAA,EAER,YAAY,QAA+B;AACzC,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,MAAM,UAAyB;AAC7B,SAAK,OAAO,MAAM,IAAI,aAAAA,QAAM,eAAe,KAAK,MAAa,EAAE,QAAQ;AAAA,EACzE;AAAA,EAEA,MAAM,aAA4B;AAChC,QAAI,KAAK,MAAM;AACb,YAAM,KAAK,KAAK,MAAM;AACtB,WAAK,OAAO;AAAA,IACd;AAAA,EACF;AAAA,EAEA,MAAM,QAAuB;AAC3B,SAAK,cAAc,IAAI,aAAAA,QAAM,YAAY,KAAK,IAAK;AACnD,UAAM,KAAK,YAAY,MAAM;AAAA,EAC/B;AAAA,EAEA,MAAM,SAAwB;AAC5B,QAAI,KAAK,aAAa;AACpB,YAAM,KAAK,YAAY,OAAO;AAC9B,WAAK,cAAc;AAAA,IACrB;AAAA,EACF;AAAA,EAEA,MAAM,WAA0B;AAC9B,QAAI,KAAK,aAAa;AACpB,YAAM,KAAK,YAAY,SAAS;AAChC,WAAK,cAAc;AAAA,IACrB;AAAA,EACF;AAAA,EAEQ,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AS,WAAY,QAAO,0CAAkB;AAC1H,QAAI,SAAS,MAAO,QAAO,0CAAkB;AAC7C,QAAI,SAAS,OAAQ,QAAO,0CAAkB;AAC9C,QAAI,SAAS,cAAc,SAAS,eAAe,SAAS,gBAAiB,QAAO,0CAAkB;AACtG,QAAI,SAAS,aAAa,SAAS,aAAa,SAAS,WAAW,SAAS,aAAc,QAAO,0CAAkB;AACpH,QAAI,SAAS,WAAW,SAAS,OAAQ,QAAO,0CAAkB;AAClE,QAAI,SAAS,mBAAoB,QAAO,0CAAkB;AAC1D,QAAI,SAAS,eAAe,SAAS,YAAY,SAAS,QAAS,QAAO,0CAAkB;AAE5F,WAAO,0CAAkB;AAAA,EAC3B;AACF;AAEO,SAAS,mBAAmB,QAA6C;AAC9E,SAAO,IAAI,aAAa,MAAM;AAChC;","names":["mssql"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import mssql from 'mssql';
|
|
2
|
+
import { SqlAdapter, SchemaGraph, SeedBatch } from 'schema-seed-core';
|
|
3
|
+
|
|
4
|
+
declare class MssqlAdapter implements SqlAdapter {
|
|
5
|
+
private pool;
|
|
6
|
+
private transaction;
|
|
7
|
+
private config;
|
|
8
|
+
constructor(config: string | mssql.config);
|
|
9
|
+
connect(): Promise<void>;
|
|
10
|
+
disconnect(): Promise<void>;
|
|
11
|
+
begin(): Promise<void>;
|
|
12
|
+
commit(): Promise<void>;
|
|
13
|
+
rollback(): Promise<void>;
|
|
14
|
+
private getRequest;
|
|
15
|
+
introspectSchema(): Promise<SchemaGraph>;
|
|
16
|
+
insertBatch(batch: SeedBatch): Promise<void>;
|
|
17
|
+
truncateTables(tableNames: string[]): Promise<void>;
|
|
18
|
+
readonly capabilities: {
|
|
19
|
+
enums: boolean;
|
|
20
|
+
deferrableConstraints: boolean;
|
|
21
|
+
returning: boolean;
|
|
22
|
+
identityInsert: boolean;
|
|
23
|
+
};
|
|
24
|
+
private mapMssqlType;
|
|
25
|
+
}
|
|
26
|
+
declare function createMssqlAdapter(config: string | mssql.config): MssqlAdapter;
|
|
27
|
+
|
|
28
|
+
export { MssqlAdapter, createMssqlAdapter };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import mssql from 'mssql';
|
|
2
|
+
import { SqlAdapter, SchemaGraph, SeedBatch } from 'schema-seed-core';
|
|
3
|
+
|
|
4
|
+
declare class MssqlAdapter implements SqlAdapter {
|
|
5
|
+
private pool;
|
|
6
|
+
private transaction;
|
|
7
|
+
private config;
|
|
8
|
+
constructor(config: string | mssql.config);
|
|
9
|
+
connect(): Promise<void>;
|
|
10
|
+
disconnect(): Promise<void>;
|
|
11
|
+
begin(): Promise<void>;
|
|
12
|
+
commit(): Promise<void>;
|
|
13
|
+
rollback(): Promise<void>;
|
|
14
|
+
private getRequest;
|
|
15
|
+
introspectSchema(): Promise<SchemaGraph>;
|
|
16
|
+
insertBatch(batch: SeedBatch): Promise<void>;
|
|
17
|
+
truncateTables(tableNames: string[]): Promise<void>;
|
|
18
|
+
readonly capabilities: {
|
|
19
|
+
enums: boolean;
|
|
20
|
+
deferrableConstraints: boolean;
|
|
21
|
+
returning: boolean;
|
|
22
|
+
identityInsert: boolean;
|
|
23
|
+
};
|
|
24
|
+
private mapMssqlType;
|
|
25
|
+
}
|
|
26
|
+
declare function createMssqlAdapter(config: string | mssql.config): MssqlAdapter;
|
|
27
|
+
|
|
28
|
+
export { MssqlAdapter, createMssqlAdapter };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import mssql from "mssql";
|
|
3
|
+
import {
|
|
4
|
+
NormalizedSqlType
|
|
5
|
+
} from "schema-seed-core";
|
|
6
|
+
var MssqlAdapter = class {
|
|
7
|
+
pool = null;
|
|
8
|
+
transaction = null;
|
|
9
|
+
config;
|
|
10
|
+
constructor(config) {
|
|
11
|
+
this.config = config;
|
|
12
|
+
}
|
|
13
|
+
async connect() {
|
|
14
|
+
this.pool = await new mssql.ConnectionPool(this.config).connect();
|
|
15
|
+
}
|
|
16
|
+
async disconnect() {
|
|
17
|
+
if (this.pool) {
|
|
18
|
+
await this.pool.close();
|
|
19
|
+
this.pool = null;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
async begin() {
|
|
23
|
+
this.transaction = new mssql.Transaction(this.pool);
|
|
24
|
+
await this.transaction.begin();
|
|
25
|
+
}
|
|
26
|
+
async commit() {
|
|
27
|
+
if (this.transaction) {
|
|
28
|
+
await this.transaction.commit();
|
|
29
|
+
this.transaction = null;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
async rollback() {
|
|
33
|
+
if (this.transaction) {
|
|
34
|
+
await this.transaction.rollback();
|
|
35
|
+
this.transaction = null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
getRequest() {
|
|
39
|
+
if (this.transaction) return new mssql.Request(this.transaction);
|
|
40
|
+
if (this.pool) return new mssql.Request(this.pool);
|
|
41
|
+
throw new Error("Not connected");
|
|
42
|
+
}
|
|
43
|
+
async introspectSchema() {
|
|
44
|
+
const schema = { tables: {} };
|
|
45
|
+
const tablesRes = await this.getRequest().query(`
|
|
46
|
+
SELECT t.name AS table_name, s.name AS schema_name
|
|
47
|
+
FROM sys.tables t
|
|
48
|
+
JOIN sys.schemas s ON t.schema_id = s.schema_id
|
|
49
|
+
WHERE t.is_ms_shipped = 0
|
|
50
|
+
`);
|
|
51
|
+
for (const row of tablesRes.recordset) {
|
|
52
|
+
const tableName = row.table_name;
|
|
53
|
+
schema.tables[tableName] = {
|
|
54
|
+
name: tableName,
|
|
55
|
+
schema: row.schema_name,
|
|
56
|
+
columns: {},
|
|
57
|
+
foreignKeys: [],
|
|
58
|
+
uniqueConstraints: []
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
const columnsRes = await this.getRequest().query(`
|
|
62
|
+
SELECT
|
|
63
|
+
t.name AS table_name,
|
|
64
|
+
c.name AS column_name,
|
|
65
|
+
ty.name AS data_type,
|
|
66
|
+
c.is_nullable,
|
|
67
|
+
dc.definition AS column_default,
|
|
68
|
+
c.is_identity
|
|
69
|
+
FROM sys.columns c
|
|
70
|
+
JOIN sys.tables t ON c.object_id = t.object_id
|
|
71
|
+
JOIN sys.types ty ON c.user_type_id = ty.user_type_id
|
|
72
|
+
LEFT JOIN sys.default_constraints dc ON c.default_object_id = dc.object_id
|
|
73
|
+
WHERE t.is_ms_shipped = 0
|
|
74
|
+
`);
|
|
75
|
+
for (const row of columnsRes.recordset) {
|
|
76
|
+
if (!schema.tables[row.table_name]) continue;
|
|
77
|
+
const col = {
|
|
78
|
+
name: row.column_name,
|
|
79
|
+
type: this.mapMssqlType(row.data_type),
|
|
80
|
+
rawType: row.data_type,
|
|
81
|
+
nullable: row.is_nullable,
|
|
82
|
+
defaultValue: row.column_default,
|
|
83
|
+
isAutoIncrement: row.is_identity
|
|
84
|
+
};
|
|
85
|
+
schema.tables[row.table_name].columns[row.column_name] = col;
|
|
86
|
+
}
|
|
87
|
+
const fkRes = await this.getRequest().query(`
|
|
88
|
+
SELECT
|
|
89
|
+
obj.name AS constraint_name,
|
|
90
|
+
sch.name AS schema_name,
|
|
91
|
+
t.name AS table_name,
|
|
92
|
+
col.name AS column_name,
|
|
93
|
+
rt.name AS referenced_table_name,
|
|
94
|
+
rcol.name AS referenced_column_name
|
|
95
|
+
FROM sys.foreign_key_columns fkc
|
|
96
|
+
INNER JOIN sys.objects obj ON obj.object_id = fkc.constraint_object_id
|
|
97
|
+
INNER JOIN sys.tables t ON t.object_id = fkc.parent_object_id
|
|
98
|
+
INNER JOIN sys.schemas sch ON sch.schema_id = t.schema_id
|
|
99
|
+
INNER JOIN sys.columns col ON col.column_id = fkc.parent_column_id AND col.object_id = t.object_id
|
|
100
|
+
INNER JOIN sys.tables rt ON rt.object_id = fkc.referenced_object_id
|
|
101
|
+
INNER JOIN sys.columns rcol ON rcol.column_id = fkc.referenced_column_id AND rcol.object_id = rt.object_id
|
|
102
|
+
`);
|
|
103
|
+
for (const row of fkRes.recordset) {
|
|
104
|
+
if (!schema.tables[row.table_name]) continue;
|
|
105
|
+
schema.tables[row.table_name].foreignKeys.push({
|
|
106
|
+
name: row.constraint_name,
|
|
107
|
+
columns: [row.column_name],
|
|
108
|
+
referencedTable: row.referenced_table_name,
|
|
109
|
+
referencedColumns: [row.referenced_column_name]
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
const pkRes = await this.getRequest().query(`
|
|
113
|
+
SELECT
|
|
114
|
+
t.name AS table_name,
|
|
115
|
+
c.name AS column_name
|
|
116
|
+
FROM sys.indexes i
|
|
117
|
+
INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
|
|
118
|
+
INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
|
|
119
|
+
INNER JOIN sys.tables t ON i.object_id = t.object_id
|
|
120
|
+
WHERE i.is_primary_key = 1
|
|
121
|
+
`);
|
|
122
|
+
for (const row of pkRes.recordset) {
|
|
123
|
+
if (!schema.tables[row.table_name]) continue;
|
|
124
|
+
if (!schema.tables[row.table_name].primaryKey) {
|
|
125
|
+
schema.tables[row.table_name].primaryKey = { columns: [] };
|
|
126
|
+
}
|
|
127
|
+
schema.tables[row.table_name].primaryKey.columns.push(row.column_name);
|
|
128
|
+
}
|
|
129
|
+
return schema;
|
|
130
|
+
}
|
|
131
|
+
async insertBatch(batch) {
|
|
132
|
+
if (!this.pool) throw new Error("Not connected");
|
|
133
|
+
const { tableName, rows } = batch;
|
|
134
|
+
if (rows.length === 0) return;
|
|
135
|
+
const columns = Object.keys(rows[0]);
|
|
136
|
+
const tableSchema = (await this.introspectSchema()).tables[tableName];
|
|
137
|
+
const hasIdentity = Object.values(tableSchema.columns).some((c) => c.isAutoIncrement);
|
|
138
|
+
const request = this.getRequest();
|
|
139
|
+
if (hasIdentity) {
|
|
140
|
+
await this.getRequest().query(`SET IDENTITY_INSERT [${tableName}] ON`);
|
|
141
|
+
}
|
|
142
|
+
try {
|
|
143
|
+
const valuesStrings = [];
|
|
144
|
+
for (let i = 0; i < rows.length; i++) {
|
|
145
|
+
const row = rows[i];
|
|
146
|
+
const rowParams = [];
|
|
147
|
+
for (let j = 0; j < columns.length; j++) {
|
|
148
|
+
const colName = columns[j];
|
|
149
|
+
const paramName = `p${i}_${j}`;
|
|
150
|
+
request.input(paramName, row[colName]);
|
|
151
|
+
rowParams.push(`@${paramName}`);
|
|
152
|
+
}
|
|
153
|
+
valuesStrings.push(`(${rowParams.join(", ")})`);
|
|
154
|
+
}
|
|
155
|
+
const query = `INSERT INTO [${tableName}] (${columns.map((c) => `[${c}]`).join(", ")}) VALUES ${valuesStrings.join(", ")}`;
|
|
156
|
+
await request.query(query);
|
|
157
|
+
} finally {
|
|
158
|
+
if (hasIdentity) {
|
|
159
|
+
await this.getRequest().query(`SET IDENTITY_INSERT [${tableName}] OFF`);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
async truncateTables(tableNames) {
|
|
164
|
+
if (!this.pool) throw new Error("Not connected");
|
|
165
|
+
for (const table of tableNames) {
|
|
166
|
+
try {
|
|
167
|
+
await this.getRequest().query(`TRUNCATE TABLE [${table}]`);
|
|
168
|
+
} catch (err) {
|
|
169
|
+
await this.getRequest().query(`DELETE FROM [${table}]`);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
capabilities = {
|
|
174
|
+
enums: false,
|
|
175
|
+
deferrableConstraints: false,
|
|
176
|
+
returning: true,
|
|
177
|
+
identityInsert: true
|
|
178
|
+
};
|
|
179
|
+
mapMssqlType(mssqlType) {
|
|
180
|
+
const type = mssqlType.toLowerCase();
|
|
181
|
+
if (type.includes("int")) return NormalizedSqlType.INT;
|
|
182
|
+
if (type.includes("bigint")) return NormalizedSqlType.BIGINT;
|
|
183
|
+
if (type.includes("char") || type.includes("text") || type === "varchar" || type === "nvarchar") return NormalizedSqlType.STRING;
|
|
184
|
+
if (type === "bit") return NormalizedSqlType.BOOLEAN;
|
|
185
|
+
if (type === "date") return NormalizedSqlType.DATE;
|
|
186
|
+
if (type === "datetime" || type === "datetime2" || type === "smalldatetime") return NormalizedSqlType.DATETIME;
|
|
187
|
+
if (type === "decimal" || type === "numeric" || type === "money" || type === "smallmoney") return NormalizedSqlType.DECIMAL;
|
|
188
|
+
if (type === "float" || type === "real") return NormalizedSqlType.FLOAT;
|
|
189
|
+
if (type === "uniqueidentifier") return NormalizedSqlType.UUID;
|
|
190
|
+
if (type === "varbinary" || type === "binary" || type === "image") return NormalizedSqlType.BINARY;
|
|
191
|
+
return NormalizedSqlType.STRING;
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
function createMssqlAdapter(config) {
|
|
195
|
+
return new MssqlAdapter(config);
|
|
196
|
+
}
|
|
197
|
+
export {
|
|
198
|
+
MssqlAdapter,
|
|
199
|
+
createMssqlAdapter
|
|
200
|
+
};
|
|
201
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import mssql from 'mssql'\nimport {\n SqlAdapter,\n SchemaGraph,\n SeedBatch,\n NormalizedSqlType,\n TableSchema,\n ColumnSchema\n} from 'schema-seed-core'\n\nexport class MssqlAdapter implements SqlAdapter {\n private pool: mssql.ConnectionPool | null = null\n private transaction: mssql.Transaction | null = null\n private config: string | mssql.config\n\n constructor(config: string | mssql.config) {\n this.config = config\n }\n\n async connect(): Promise<void> {\n this.pool = await new mssql.ConnectionPool(this.config as any).connect()\n }\n\n async disconnect(): Promise<void> {\n if (this.pool) {\n await this.pool.close()\n this.pool = null\n }\n }\n\n async begin(): Promise<void> {\n this.transaction = new mssql.Transaction(this.pool!)\n await this.transaction.begin()\n }\n\n async commit(): Promise<void> {\n if (this.transaction) {\n await this.transaction.commit()\n this.transaction = null\n }\n }\n\n async rollback(): Promise<void> {\n if (this.transaction) {\n await this.transaction.rollback()\n this.transaction = null\n }\n }\n\n private getRequest(): mssql.Request {\n if (this.transaction) return new mssql.Request(this.transaction)\n if (this.pool) return new mssql.Request(this.pool)\n throw new Error('Not connected')\n }\n\n async introspectSchema(): Promise<SchemaGraph> {\n const schema: SchemaGraph = { tables: {} }\n\n // Get tables\n const tablesRes = await this.getRequest().query(`\n SELECT t.name AS table_name, s.name AS schema_name\n FROM sys.tables t\n JOIN sys.schemas s ON t.schema_id = s.schema_id\n WHERE t.is_ms_shipped = 0\n `)\n\n for (const row of tablesRes.recordset) {\n const tableName = row.table_name\n schema.tables[tableName] = {\n name: tableName,\n schema: row.schema_name,\n columns: {},\n foreignKeys: [],\n uniqueConstraints: []\n }\n }\n\n // Get columns\n const columnsRes = await this.getRequest().query(`\n SELECT \n t.name AS table_name,\n c.name AS column_name,\n ty.name AS data_type,\n c.is_nullable,\n dc.definition AS column_default,\n c.is_identity\n FROM sys.columns c\n JOIN sys.tables t ON c.object_id = t.object_id\n JOIN sys.types ty ON c.user_type_id = ty.user_type_id\n LEFT JOIN sys.default_constraints dc ON c.default_object_id = dc.object_id\n WHERE t.is_ms_shipped = 0\n `)\n\n for (const row of columnsRes.recordset) {\n if (!schema.tables[row.table_name]) continue\n\n const col: ColumnSchema = {\n name: row.column_name,\n type: this.mapMssqlType(row.data_type),\n rawType: row.data_type,\n nullable: row.is_nullable,\n defaultValue: row.column_default,\n isAutoIncrement: row.is_identity\n }\n schema.tables[row.table_name].columns[row.column_name] = col\n }\n\n // Get Foreign Keys\n const fkRes = await this.getRequest().query(`\n SELECT \n obj.name AS constraint_name,\n sch.name AS schema_name,\n t.name AS table_name,\n col.name AS column_name,\n rt.name AS referenced_table_name,\n rcol.name AS referenced_column_name\n FROM sys.foreign_key_columns fkc\n INNER JOIN sys.objects obj ON obj.object_id = fkc.constraint_object_id\n INNER JOIN sys.tables t ON t.object_id = fkc.parent_object_id\n INNER JOIN sys.schemas sch ON sch.schema_id = t.schema_id\n INNER JOIN sys.columns col ON col.column_id = fkc.parent_column_id AND col.object_id = t.object_id\n INNER JOIN sys.tables rt ON rt.object_id = fkc.referenced_object_id\n INNER JOIN sys.columns rcol ON rcol.column_id = fkc.referenced_column_id AND rcol.object_id = rt.object_id\n `)\n\n for (const row of fkRes.recordset) {\n if (!schema.tables[row.table_name]) continue\n schema.tables[row.table_name].foreignKeys.push({\n name: row.constraint_name,\n columns: [row.column_name],\n referencedTable: row.referenced_table_name,\n referencedColumns: [row.referenced_column_name]\n })\n }\n\n // Get Primary Keys\n const pkRes = await this.getRequest().query(`\n SELECT \n t.name AS table_name,\n c.name AS column_name\n FROM sys.indexes i\n INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id\n INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id\n INNER JOIN sys.tables t ON i.object_id = t.object_id\n WHERE i.is_primary_key = 1\n `)\n\n for (const row of pkRes.recordset) {\n if (!schema.tables[row.table_name]) continue\n if (!schema.tables[row.table_name].primaryKey) {\n schema.tables[row.table_name].primaryKey = { columns: [] }\n }\n schema.tables[row.table_name].primaryKey!.columns.push(row.column_name)\n }\n\n return schema\n }\n\n async insertBatch(batch: SeedBatch): Promise<void> {\n if (!this.pool) 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\n // Check if any column is an identity column\n const tableSchema = (await this.introspectSchema()).tables[tableName]\n const hasIdentity = Object.values(tableSchema.columns).some(c => c.isAutoIncrement)\n\n const request = this.getRequest()\n\n if (hasIdentity) {\n await this.getRequest().query(`SET IDENTITY_INSERT [${tableName}] ON`)\n }\n\n try {\n // MSSQL doesn't support multi-row INSERT with parameters in a simple way like MySQL/Postgres\n // We'll use a Table-Valued Parameter or just multiple inserts in a transaction if small\n // For simplicity here, we'll build a large query string with parameters\n\n const valuesStrings = []\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i]\n const rowParams = []\n for (let j = 0; j < columns.length; j++) {\n const colName = columns[j]\n const paramName = `p${i}_${j}`\n request.input(paramName, row[colName])\n rowParams.push(`@${paramName}`)\n }\n valuesStrings.push(`(${rowParams.join(', ')})`)\n }\n\n const query = `INSERT INTO [${tableName}] (${columns.map(c => `[${c}]`).join(', ')}) VALUES ${valuesStrings.join(', ')}`\n await request.query(query)\n } finally {\n if (hasIdentity) {\n await this.getRequest().query(`SET IDENTITY_INSERT [${tableName}] OFF`)\n }\n }\n }\n\n async truncateTables(tableNames: string[]): Promise<void> {\n if (!this.pool) throw new Error('Not connected')\n\n for (const table of tableNames) {\n try {\n await this.getRequest().query(`TRUNCATE TABLE [${table}]`)\n } catch (err) {\n // If TRUNCATE fails (e.g. due to FK), fallback to DELETE\n await this.getRequest().query(`DELETE FROM [${table}]`)\n }\n }\n }\n\n readonly capabilities = {\n enums: false,\n deferrableConstraints: false,\n returning: true,\n identityInsert: true\n }\n\n private mapMssqlType(mssqlType: string): NormalizedSqlType {\n const type = mssqlType.toLowerCase()\n if (type.includes('int')) return NormalizedSqlType.INT\n if (type.includes('bigint')) return NormalizedSqlType.BIGINT\n if (type.includes('char') || type.includes('text') || type === 'varchar' || type === 'nvarchar') return NormalizedSqlType.STRING\n if (type === 'bit') return NormalizedSqlType.BOOLEAN\n if (type === 'date') return NormalizedSqlType.DATE\n if (type === 'datetime' || type === 'datetime2' || type === 'smalldatetime') return NormalizedSqlType.DATETIME\n if (type === 'decimal' || type === 'numeric' || type === 'money' || type === 'smallmoney') return NormalizedSqlType.DECIMAL\n if (type === 'float' || type === 'real') return NormalizedSqlType.FLOAT\n if (type === 'uniqueidentifier') return NormalizedSqlType.UUID\n if (type === 'varbinary' || type === 'binary' || type === 'image') return NormalizedSqlType.BINARY\n\n return NormalizedSqlType.STRING\n }\n}\n\nexport function createMssqlAdapter(config: string | mssql.config): MssqlAdapter {\n return new MssqlAdapter(config)\n}\n"],"mappings":";AAAA,OAAO,WAAW;AAClB;AAAA,EAIE;AAAA,OAGK;AAEA,IAAM,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
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "schema-seed-adapter-mssql",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "MSSQL 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
|
+
"mssql": "^11.0.1",
|
|
42
|
+
"schema-seed-core": "0.1.0"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@types/mssql": "^9.1.5",
|
|
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
|
+
}
|