@technicity/data-service-generator 0.17.1 → 0.18.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/README.md CHANGED
@@ -36,7 +36,7 @@ async function main() {
36
36
  | Option | Required | Default | Description |
37
37
  | ------------- | -------- | ------------ | --------------------------------------------------------------- |
38
38
  | outdir | Yes | | The output directory for the SDK. |
39
- | dialect | Yes | | "mysql" \| "mssql" |
39
+ | dialect | Yes | | "mysql" \| "sqlite" |
40
40
  | database | Yes | | Database name |
41
41
  | user | Yes | | Database user |
42
42
  | password | No | | Database password |
@@ -36,9 +36,6 @@ const prettier = __importStar(require("prettier"));
36
36
  const changeCase = __importStar(require("change-case"));
37
37
  const fse = __importStar(require("fs-extra"));
38
38
  const _ = __importStar(require("lodash/fp"));
39
- const mssql = __importStar(require("mssql"));
40
- // @ts-ignore
41
- const TSqlString = __importStar(require("tsqlstring"));
42
39
  const json_schema_to_typescript_1 = require("json-schema-to-typescript");
43
40
  const getDuplicates_1 = require("../lib/getDuplicates");
44
41
  const isNotNullOrUndefined_1 = require("../lib/isNotNullOrUndefined");
@@ -214,24 +211,6 @@ function init(input) {
214
211
  });
215
212
  query = mysql.query.bind(mysql);
216
213
  }
217
- if (dialect === "mssql") {
218
- const pool = new mssql.ConnectionPool({
219
- server: server ?? "localhost",
220
- user,
221
- password,
222
- port,
223
- database
224
- });
225
- const poolConnect = pool.connect();
226
- async function runMSSQLQuery(...input) {
227
- const q = TSqlString.format(...input);
228
- await poolConnect;
229
- const request = pool.request();
230
- const result = await request.query(q);
231
- return result.recordset;
232
- }
233
- query = runMSSQLQuery;
234
- }
235
214
  }
236
215
  // It's a bit awkward to put __whereNeedsProcessing, __prepareWhere on the class,
237
216
  // but it allows us to share the same database pool, clientOpts, etc.
@@ -1545,12 +1524,11 @@ async function getJunctionTables() {
1545
1524
  }
1546
1525
  // `from` relations
1547
1526
  // https://stackoverflow.com/a/54732547
1548
- // Memoize because it seems to be expensive for MSSQL. Note: this function
1527
+ // Note: this function
1549
1528
  // isn't pure (because of `dialect`), but that's fine because its value
1550
1529
  // isn't expected to change.
1551
1530
  const getRelationsManyToOne = _.memoize(async function getRelationsManyToOne(table) {
1552
- const sql = dialect === "mysql"
1553
- ? `
1531
+ const sql = `
1554
1532
  SELECT
1555
1533
  TABLE_SCHEMA as db,
1556
1534
  TABLE_NAME as t1,
@@ -1564,26 +1542,7 @@ const getRelationsManyToOne = _.memoize(async function getRelationsManyToOne(tab
1564
1542
  TABLE_SCHEMA = SCHEMA()
1565
1543
  AND REFERENCED_TABLE_NAME IS NOT NULL
1566
1544
  AND (TABLE_NAME = ?);
1567
- `
1568
- : // https://stackoverflow.com/a/3907999
1569
- `
1570
- SELECT
1571
- KCU1.TABLE_NAME AS t1
1572
- ,KCU1.COLUMN_NAME AS t1Field
1573
- ,KCU2.TABLE_NAME AS t2
1574
- ,KCU2.COLUMN_NAME AS t2Field
1575
- FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC
1576
- INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU1
1577
- ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG
1578
- AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
1579
- AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
1580
- INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU2
1581
- ON KCU2.CONSTRAINT_CATALOG = RC.UNIQUE_CONSTRAINT_CATALOG
1582
- AND KCU2.CONSTRAINT_SCHEMA = RC.UNIQUE_CONSTRAINT_SCHEMA
1583
- AND KCU2.CONSTRAINT_NAME = RC.UNIQUE_CONSTRAINT_NAME
1584
- AND KCU2.ORDINAL_POSITION = KCU1.ORDINAL_POSITION
1585
- WHERE
1586
- KCU1.TABLE_NAME = ?`;
1545
+ `;
1587
1546
  const tableMeta = await getTableMeta(table);
1588
1547
  const rs = await query(sql, [table]);
1589
1548
  const xs = await Promise.all(_.uniqWith(_.isEqual, rs.map(async (v) => {
@@ -1599,8 +1558,7 @@ const getRelationsManyToOne = _.memoize(async function getRelationsManyToOne(tab
1599
1558
  });
1600
1559
  // `to` relations
1601
1560
  const getRelationsOneToMany = _.memoize(async function getRelationsOneToMany(table) {
1602
- const sql = dialect === "mysql"
1603
- ? `
1561
+ const sql = `
1604
1562
  SELECT
1605
1563
  TABLE_SCHEMA as db,
1606
1564
  TABLE_NAME as t1,
@@ -1614,25 +1572,7 @@ const getRelationsOneToMany = _.memoize(async function getRelationsOneToMany(tab
1614
1572
  TABLE_SCHEMA = SCHEMA()
1615
1573
  AND REFERENCED_TABLE_NAME IS NOT NULL
1616
1574
  AND (REFERENCED_TABLE_NAME = ?);
1617
- `
1618
- : `
1619
- SELECT
1620
- KCU1.TABLE_NAME AS t1
1621
- ,KCU1.COLUMN_NAME AS t1Field
1622
- ,KCU2.TABLE_NAME AS t2
1623
- ,KCU2.COLUMN_NAME AS t2Field
1624
- FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC
1625
- INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU1
1626
- ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG
1627
- AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
1628
- AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
1629
- INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU2
1630
- ON KCU2.CONSTRAINT_CATALOG = RC.UNIQUE_CONSTRAINT_CATALOG
1631
- AND KCU2.CONSTRAINT_SCHEMA = RC.UNIQUE_CONSTRAINT_SCHEMA
1632
- AND KCU2.CONSTRAINT_NAME = RC.UNIQUE_CONSTRAINT_NAME
1633
- AND KCU2.ORDINAL_POSITION = KCU1.ORDINAL_POSITION
1634
- WHERE
1635
- KCU2.TABLE_NAME = ?`;
1575
+ `;
1636
1576
  const rs = await query(sql, [table]);
1637
1577
  const xs = await Promise.all(_.uniqWith(_.isEqual, rs.map(async (v) => {
1638
1578
  return {
@@ -1687,47 +1627,6 @@ const getTableMeta = _.memoize(async function getTableMeta(table) {
1687
1627
  if (dialect === "mysql") {
1688
1628
  return query("DESCRIBE ??", [table]).then((xs) => _.sortBy((x) => x.Field, xs));
1689
1629
  }
1690
- if (dialect === "mssql") {
1691
- const primaryColumn = await query(`SELECT columns.name as COLUMN_NAME
1692
- FROM sys.tables tables
1693
- JOIN sys.columns columns
1694
- ON tables.object_id=columns.object_id
1695
- WHERE columns.is_identity=1 AND tables.name = ?`, [table]).then((xs) => xs[0]?.["COLUMN_NAME"]);
1696
- const uniqueColumns =
1697
- // https://stackoverflow.com/a/59095477
1698
- await query(`SELECT c.name AS COLUMN_NAME
1699
- FROM sys.indexes i
1700
- INNER JOIN sys.index_columns ic
1701
- ON i.index_id = ic.index_id AND i.object_id = ic.object_id
1702
- INNER JOIN sys.tables AS t
1703
- ON t.object_id = i.object_id
1704
- INNER JOIN sys.columns c
1705
- ON t.object_id = c.object_id AND ic.column_id = c.column_id
1706
- INNER JOIN sys.objects AS syso
1707
- ON syso.object_id = t.object_id AND syso.is_ms_shipped = 0
1708
- INNER JOIN sys.schemas AS sh
1709
- ON sh.schema_id = t.schema_id
1710
- INNER JOIN information_schema.schemata sch
1711
- ON sch.schema_name = sh.name
1712
- WHERE i.is_unique_constraint = 1
1713
- AND t.name = ?
1714
- -- AND sh.name = 'dbo'
1715
- ORDER BY sh.name, i.name, ic.key_ordinal;`, [table]).then((xs) => xs.map((x) => x["COLUMN_NAME"]));
1716
- return query("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? ORDER BY ORDINAL_POSITION", [table]).then((xs) => _.sortBy((x) => x.Field, xs.map((x) => {
1717
- const Field = x["COLUMN_NAME"];
1718
- return {
1719
- Field,
1720
- Type: x["DATA_TYPE"],
1721
- Key: Field === primaryColumn
1722
- ? "PRI"
1723
- : uniqueColumns.find((u) => u === Field)
1724
- ? "UNI"
1725
- : "",
1726
- Null: x["IS_NULLABLE"],
1727
- Default: x["COLUMN_DEFAULT"]
1728
- };
1729
- })));
1730
- }
1731
1630
  throw new Error("Unsupported dialect: " + dialect);
1732
1631
  });
1733
1632
  function getShowCreateTable(table) {
@@ -1879,24 +1778,10 @@ function getPropertyFormat(sqlType) {
1879
1778
  }
1880
1779
  return undefined;
1881
1780
  }
1882
- const mssqlTableExcludes = new Set([
1883
- "captured_columns",
1884
- "change_tables",
1885
- "ddl_history",
1886
- "index_columns",
1887
- "lsn_time_mapping",
1888
- "systranschemas"
1889
- ]);
1890
1781
  async function getTableNames() {
1891
1782
  if (dialect === "mysql") {
1892
1783
  return query("SHOW TABLES").then((xs) => xs.flatMap((x) => Object.values(x)).sort());
1893
1784
  }
1894
- if (dialect === "mssql") {
1895
- return query("SELECT * FROM INFORMATION_SCHEMA.TABLES").then((xs) => xs
1896
- .map((x) => x["TABLE_NAME"])
1897
- .filter((x) => !x.startsWith("dbo_") && !mssqlTableExcludes.has(x))
1898
- .sort());
1899
- }
1900
1785
  throw new Error("Unsupported dialect: " + dialect);
1901
1786
  }
1902
1787
  function getMysql2sqliteSrc() {
@@ -40,7 +40,7 @@ export type TContext = {
40
40
  [k: string]: any;
41
41
  };
42
42
  export type TMiddleware = (params: TResolveParams, next: (params: TResolveParams) => Promise<any>) => Promise<any>;
43
- export type IDialect = "mysql" | "mssql" | "sqlite";
43
+ export type IDialect = "mysql" | "sqlite";
44
44
  export type TDbCall = (q: string) => Promise<any>;
45
45
  export type TFormatQuery = (q: string, values: any[]) => string;
46
46
  export type TBeginTransaction = () => Promise<TBeginTransactionResult>;
@@ -29,8 +29,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
29
29
  exports.getSqlAst = getSqlAst;
30
30
  const SqlString = __importStar(require("sqlstring"));
31
31
  // @ts-ignore
32
- const TSqlString = __importStar(require("tsqlstring"));
33
- // @ts-ignore
34
32
  const alias_namespace_1 = __importDefault(require("join-monster/dist/alias-namespace"));
35
33
  const _ = __importStar(require("lodash/fp"));
36
34
  const getOrderBy_1 = require("./getOrderBy");
@@ -39,9 +37,7 @@ function getSqlAst(input) {
39
37
  const { table, fieldName, fields, args, grabMany, sqlJoin, sqlBatch, junction, getWhere, artifacts, rowWithMatchingCursor, dialect } = input;
40
38
  const tableArtifacts = artifacts[table];
41
39
  const primaryKey = tableArtifacts.primaryKey;
42
- const format = dialect === "mssql"
43
- ? TSqlString.format.bind(TSqlString)
44
- : SqlString.format.bind(SqlString);
40
+ const format = SqlString.format.bind(SqlString);
45
41
  const orderBy = input.orderBy ?? (0, getOrderBy_1.getOrderBy)(args, primaryKey)?.orderBy;
46
42
  let where = input.where;
47
43
  if (input.where == null) {
@@ -196,18 +196,7 @@ async function getData(input, dbCall, formatQuery, dialect) {
196
196
  acc[x] = true;
197
197
  return acc;
198
198
  }, {});
199
- const orderByListPaginatedRootResult =
200
- // MSSQL's OFFSET and FETCH requires ORDER BY, so we need to provide a fallback
201
- dialect === "mssql" && paginationType === "limit-offset"
202
- ? {
203
- orderBy: (0, getOrderBy_1.getOrderBy)(input.args, primaryKey)?.orderBy ?? [
204
- { column: primaryKey, direction: "asc" }
205
- ],
206
- flip: false
207
- }
208
- : action === "findManyPaginated"
209
- ? (0, getOrderBy_1.getOrderBy)(input.args, primaryKey)
210
- : undefined;
199
+ const orderByListPaginatedRootResult = action === "findManyPaginated" ? (0, getOrderBy_1.getOrderBy)(input.args, primaryKey) : undefined;
211
200
  const grabMany = action === "findMany" ||
212
201
  action === "findManyPaginated" ||
213
202
  action === "updateMany" ||
@@ -233,19 +222,9 @@ async function getData(input, dbCall, formatQuery, dialect) {
233
222
  if (action === "findMany" || action === "findManyPaginated") {
234
223
  if (typeof limit === "number") {
235
224
  const escape = (0, stringifyWhere_1.getEscape)(dialect);
236
- if (dialect === "mssql") {
237
- if (typeof offset === "number") {
238
- sql += ` OFFSET ${escape(offset)} ROWS FETCH NEXT ${escape(limit)} ROWS ONLY`;
239
- }
240
- else {
241
- sql = sql.replace("SELECT", `SELECT TOP ${escape(limit)}`);
242
- }
243
- }
244
- else {
245
- sql += ` LIMIT ${escape(limit)}`;
246
- if (typeof offset === "number") {
247
- sql += ` OFFSET ${escape(offset)}`;
248
- }
225
+ sql += ` LIMIT ${escape(limit)}`;
226
+ if (typeof offset === "number") {
227
+ sql += ` OFFSET ${escape(offset)}`;
249
228
  }
250
229
  }
251
230
  }
@@ -456,37 +435,6 @@ const runCreateTreeMySQL = async (table, referencedKey, referencedKeyValue, colu
456
435
  }
457
436
  return Promise.all(allColumns.map((cs, i) => dbCall(formatQuery(`INSERT INTO ?? (??) VALUES (?)`, [table, cs, allValues[i]])).then((x) => x.insertId)));
458
437
  };
459
- // This doesn't use bulk inserts because:
460
- // 1. columns aren't necessarily uniform
461
- // 2. We don't want to do backflips to get all the inserted IDs
462
- const runCreateTreeMSSQL = async (table, referencedKey, referencedKeyValue, columns, values, dbCall, formatQuery) => {
463
- let allColumns = columns;
464
- if (typeof referencedKey === "string") {
465
- allColumns = allColumns.slice().map((xs) => xs.concat(referencedKey));
466
- }
467
- let allValues = values;
468
- if (referencedKeyValue != null) {
469
- allValues = allValues.slice().map((xs) => xs.concat(referencedKeyValue));
470
- }
471
- // https://github.com/tediousjs/node-mssql/issues/302
472
- // return Promise.all(
473
- // allColumns.map((cs, i) =>
474
- // dbCall(
475
- // formatQuery(
476
- // `INSERT INTO ?? (??) VALUES (?) SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]`,
477
- // [table, cs, allValues[i]]
478
- // )
479
- // ).then((xs) => xs[0]["SCOPE_IDENTITY"])
480
- // )
481
- // );
482
- let out = [];
483
- let i = 0;
484
- for (let cs of allColumns) {
485
- out.push(await dbCall(formatQuery(`INSERT INTO ?? (??) VALUES (?) SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]`, [table, cs, allValues[i]])).then((xs) => xs[0]["SCOPE_IDENTITY"]));
486
- i += 1;
487
- }
488
- return out;
489
- };
490
438
  async function create(input, dbCall, formatQuery, beginTransaction, dialect, context) {
491
439
  async function _create() {
492
440
  // Shallow clone, as we're going to mutate later
@@ -508,28 +456,20 @@ async function create(input, dbCall, formatQuery, beginTransaction, dialect, con
508
456
  });
509
457
  if (hasChildren) {
510
458
  const { dbCall: dbCallTransaction, commit } = await beginTransaction();
511
- const id = await runCreateTree(getCreateTree([data], input.resource, null, context?.specialCaseUuidColumn, dialect, input.artifacts), null, dialect === "mssql" ? runCreateTreeMSSQL : runCreateTreeMySQL, dbCallTransaction, formatQuery, dialect).then((xs) => xs[0]);
459
+ const id = await runCreateTree(getCreateTree([data], input.resource, null, context?.specialCaseUuidColumn, dialect, input.artifacts), null, runCreateTreeMySQL, dbCallTransaction, formatQuery, dialect).then((xs) => xs[0]);
512
460
  await commit();
513
461
  return id;
514
462
  }
515
463
  else {
516
464
  data = processCreateData(data, tableArtifacts, dialect, context?.specialCaseUuidColumn);
517
- if (dialect === "mssql") {
518
- const columns = Object.keys(data);
519
- const values = Object.values(data);
520
- const inserted = await dbCall(formatQuery(`INSERT INTO ?? (??) VALUES (?) SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]`, [input.resource, columns, values]));
521
- return inserted[0]["SCOPE_IDENTITY"];
522
- }
523
- else {
524
- const columns = Object.keys(data);
525
- const values = Object.values(data);
526
- const inserted = await dbCall(formatQuery(`INSERT INTO ?? (??) VALUES (?)`, [
527
- input.resource,
528
- columns,
529
- values
530
- ]));
531
- return inserted.insertId;
532
- }
465
+ const columns = Object.keys(data);
466
+ const values = Object.values(data);
467
+ const inserted = await dbCall(formatQuery(`INSERT INTO ?? (??) VALUES (?)`, [
468
+ input.resource,
469
+ columns,
470
+ values
471
+ ]));
472
+ return inserted.insertId;
533
473
  }
534
474
  }
535
475
  const id = await _create();
@@ -561,20 +501,7 @@ function processCreateData(data, tableArtifacts, dialect, specialCaseUuidColumn)
561
501
  async function runCreateTree(tree, referencedKeyValue, runCreateTreeSQL, dbCall, formatQuery, dialect) {
562
502
  const ids = await runCreateTreeSQL(tree.table, tree.referencedKey, referencedKeyValue, tree.columns, tree.values, dbCall, formatQuery);
563
503
  if (tree.children?.length > 0) {
564
- // https://github.com/tediousjs/node-mssql/issues/302
565
- if (dialect === "mssql") {
566
- const idIndexes = Array(ids.length)
567
- .fill(null)
568
- .map((_, i) => i);
569
- for (let i of idIndexes) {
570
- for (let c of tree.children[i]) {
571
- await runCreateTree(c, ids[i], runCreateTreeSQL, dbCall, formatQuery, dialect);
572
- }
573
- }
574
- }
575
- else {
576
- await Promise.all(ids.flatMap((id, i) => tree.children[i].map((c) => runCreateTree(c, id, runCreateTreeSQL, dbCall, formatQuery, dialect))));
577
- }
504
+ await Promise.all(ids.flatMap((id, i) => tree.children[i].map((c) => runCreateTree(c, id, runCreateTreeSQL, dbCall, formatQuery, dialect))));
578
505
  }
579
506
  return ids;
580
507
  }
@@ -29,8 +29,6 @@ exports.getEscape = getEscape;
29
29
  const _ = __importStar(require("lodash/fp"));
30
30
  const MySqlString = __importStar(require("sqlstring"));
31
31
  // @ts-expect-error
32
- const TSqlString = __importStar(require("tsqlstring"));
33
- // @ts-expect-error
34
32
  const SqliteString = __importStar(require("sqlstring-sqlite"));
35
33
  function stringifyWhere(input) {
36
34
  const { where, table, dialect, args, orderBy, rowWithMatchingCursor } = input;
@@ -141,6 +139,8 @@ function _stringifyWhere(where, table, escapeId, escape, result) {
141
139
  }
142
140
  if (operator === "$in") {
143
141
  if (operand.length === 0) {
142
+ // Edit: no longer relevant, since the MSSQL dialect was
143
+ // removed, but keep the same for stability.
144
144
  // Would do "FALSE" instead, as it's more readable, but it
145
145
  // causes a RequestError in MSSQL.
146
146
  return "(1=0)";
@@ -151,6 +151,8 @@ function _stringifyWhere(where, table, escapeId, escape, result) {
151
151
  }
152
152
  if (operator === "$nin") {
153
153
  if (operand.length === 0) {
154
+ // Edit: no longer relevant, since the MSSQL dialect was
155
+ // removed, but keep the same for stability.
154
156
  // Would do "TRUE" instead, as it's more readable, but it
155
157
  // causes a RequestError in MSSQL.
156
158
  return "(1=1)";
@@ -232,9 +234,6 @@ function getEscapeId(dialect) {
232
234
  if (dialect === "mysql") {
233
235
  return MySqlString.escapeId.bind(MySqlString);
234
236
  }
235
- if (dialect === "mssql") {
236
- return TSqlString.escapeId.bind(TSqlString);
237
- }
238
237
  if (dialect === "sqlite") {
239
238
  return SqliteString.escapeId.bind(SqliteString);
240
239
  }
@@ -244,9 +243,6 @@ function getEscape(dialect) {
244
243
  if (dialect === "mysql") {
245
244
  return MySqlString.escape.bind(MySqlString);
246
245
  }
247
- if (dialect === "mssql") {
248
- return TSqlString.escape.bind(TSqlString);
249
- }
250
246
  if (dialect === "sqlite") {
251
247
  return SqliteString.escape.bind(SqliteString);
252
248
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@technicity/data-service-generator",
3
- "version": "0.17.1",
3
+ "version": "0.18.0",
4
4
  "main": "./dist/index.js",
5
5
  "files": [
6
6
  "dist"
@@ -24,12 +24,10 @@
24
24
  "json-schema-to-typescript": "10.1.5",
25
25
  "lodash": "^4.17.20",
26
26
  "loglevel": "^1.8.1",
27
- "mssql": "^6.3.1",
28
27
  "mysql2": "^3.10.1",
29
28
  "prettier": "^2.1.2",
30
29
  "sqlstring": "^2.3.2",
31
30
  "sqlstring-sqlite": "^0.1.1",
32
- "tsqlstring": "^1.0.1",
33
31
  "uuid": "^8.3.2"
34
32
  },
35
33
  "devDependencies": {
@@ -38,7 +36,6 @@
38
36
  "@swc/jest": "^0.2.24",
39
37
  "@types/fs-extra": "9.0.13",
40
38
  "@types/lodash": "4.14.177",
41
- "@types/mssql": "^6.0.7",
42
39
  "@types/node": "^18.14.1",
43
40
  "@types/prettier": "^2.1.5",
44
41
  "@types/sqlstring": "^2.2.1",
@@ -47,9 +44,5 @@
47
44
  "sinon": "12.0.1",
48
45
  "testcontainers": "^9.1.3",
49
46
  "typescript": "5.5.2"
50
- },
51
- "resolutions": {
52
- "xml2js": "0.5.0",
53
- "tough-cookie": "4.1.3"
54
47
  }
55
48
  }
@@ -1,25 +0,0 @@
1
- import * as mssql from "mssql";
2
- import type { IRuntime, TMiddleware, TResolveParams, IArtifacts, ISupplementClientOpts } from "./IRuntime";
3
- import { typeCastMSSQL } from "./lib/typeCastMSSQL";
4
- export declare class RuntimeMSSQL implements IRuntime {
5
- #private;
6
- constructor(clientOpts: mssql.config, otherOpts: {
7
- supplementClientOpts?: ISupplementClientOpts;
8
- typeCast?: Parameters<typeof typeCastMSSQL>[0];
9
- }, artifacts: IArtifacts);
10
- resolve(input: TResolveParams): Promise<any>;
11
- $queryRaw(sql: string, values?: any[]): Promise<any>;
12
- $use(middleware: TMiddleware): Promise<void>;
13
- $whereNeedsProcessing(where: any): boolean;
14
- $prepareWhere(artifacts: IArtifacts, table: string, data: any): Promise<{}>;
15
- $shutdown(): Promise<void>;
16
- $startTransaction(input?: {
17
- isolationLevel?: "READ UNCOMMITTED" | "READ COMMITTED" | "REPEATABLE READ" | "SERIALIZABLE";
18
- }): Promise<{
19
- commit: () => Promise<void>;
20
- rollback: () => Promise<void>;
21
- dbCall: (q: string) => Promise<any>;
22
- }>;
23
- private dbCall;
24
- private formatQuery;
25
- }
@@ -1,58 +0,0 @@
1
- "use strict";
2
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
- if (kind === "m") throw new TypeError("Private method is not writable");
4
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
- };
8
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
- };
13
- var _RuntimeMSSQL_dialect, _RuntimeMSSQL_mssqlClient, _RuntimeMSSQL_middlewareHandler;
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.RuntimeMSSQL = void 0;
16
- const shared_1 = require("./lib/shared");
17
- const MSSQL_1 = require("./lib/MSSQL");
18
- const typeCastMSSQL_1 = require("./lib/typeCastMSSQL");
19
- class RuntimeMSSQL {
20
- constructor(clientOpts, otherOpts, artifacts) {
21
- _RuntimeMSSQL_dialect.set(this, "mssql");
22
- _RuntimeMSSQL_mssqlClient.set(this, void 0);
23
- _RuntimeMSSQL_middlewareHandler.set(this, void 0);
24
- __classPrivateFieldSet(this, _RuntimeMSSQL_mssqlClient, new MSSQL_1.MSSQL(clientOpts, otherOpts?.supplementClientOpts
25
- ? (0, typeCastMSSQL_1.typeCastMSSQL)(otherOpts?.typeCast)
26
- : undefined), "f");
27
- __classPrivateFieldSet(this, _RuntimeMSSQL_middlewareHandler, new shared_1.MiddlewareHandler(), "f");
28
- }
29
- async resolve(input) {
30
- return (0, shared_1.resolve)(input, input.dbCall ?? this.dbCall.bind(this), this.formatQuery.bind(this), this.$startTransaction.bind(this), __classPrivateFieldGet(this, _RuntimeMSSQL_dialect, "f"), __classPrivateFieldGet(this, _RuntimeMSSQL_middlewareHandler, "f"), input.context ?? {});
31
- }
32
- async $queryRaw(sql, values) {
33
- return this.dbCall(this.formatQuery(sql, values ?? []));
34
- }
35
- async $use(middleware) {
36
- __classPrivateFieldGet(this, _RuntimeMSSQL_middlewareHandler, "f").register(middleware);
37
- }
38
- $whereNeedsProcessing(where) {
39
- return (0, shared_1.whereNeedsProcessing)(where);
40
- }
41
- async $prepareWhere(artifacts, table, data) {
42
- return (0, shared_1._prepareWhere)(artifacts, table, data, this.dbCall.bind(this), this.formatQuery.bind(this));
43
- }
44
- async $shutdown() {
45
- await __classPrivateFieldGet(this, _RuntimeMSSQL_mssqlClient, "f").closePool();
46
- }
47
- async $startTransaction(input) {
48
- return __classPrivateFieldGet(this, _RuntimeMSSQL_mssqlClient, "f").beginTransaction(input?.isolationLevel);
49
- }
50
- async dbCall(q) {
51
- return __classPrivateFieldGet(this, _RuntimeMSSQL_mssqlClient, "f").dbCall(q);
52
- }
53
- formatQuery(q, values) {
54
- return __classPrivateFieldGet(this, _RuntimeMSSQL_mssqlClient, "f").formatQuery(q, values);
55
- }
56
- }
57
- exports.RuntimeMSSQL = RuntimeMSSQL;
58
- _RuntimeMSSQL_dialect = new WeakMap(), _RuntimeMSSQL_mssqlClient = new WeakMap(), _RuntimeMSSQL_middlewareHandler = new WeakMap();
@@ -1,14 +0,0 @@
1
- import * as mssql from "mssql";
2
- export declare class MSSQL {
3
- #private;
4
- constructor(clientOpts: mssql.config, typeCast?: Function);
5
- dbCall(q: string): Promise<any>;
6
- private mapResult;
7
- formatQuery(q: string, values: any[]): any;
8
- beginTransaction(isolationLevel?: "READ UNCOMMITTED" | "READ COMMITTED" | "REPEATABLE READ" | "SERIALIZABLE"): Promise<{
9
- commit: () => Promise<void>;
10
- rollback: () => Promise<void>;
11
- dbCall: (q: string) => Promise<any>;
12
- }>;
13
- closePool(): Promise<void>;
14
- }
@@ -1,101 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
26
- if (kind === "m") throw new TypeError("Private method is not writable");
27
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
28
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
29
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
30
- };
31
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
32
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
33
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
34
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
35
- };
36
- var _MSSQL_pool, _MSSQL_poolConnect, _MSSQL_typeCast;
37
- Object.defineProperty(exports, "__esModule", { value: true });
38
- exports.MSSQL = void 0;
39
- const mssql = __importStar(require("mssql"));
40
- // @ts-ignore
41
- const TSqlString = __importStar(require("tsqlstring"));
42
- class MSSQL {
43
- constructor(clientOpts, typeCast) {
44
- _MSSQL_pool.set(this, void 0);
45
- _MSSQL_poolConnect.set(this, void 0);
46
- _MSSQL_typeCast.set(this, void 0);
47
- __classPrivateFieldSet(this, _MSSQL_typeCast, typeCast, "f");
48
- __classPrivateFieldSet(this, _MSSQL_pool, new mssql.ConnectionPool(clientOpts), "f");
49
- __classPrivateFieldSet(this, _MSSQL_poolConnect, __classPrivateFieldGet(this, _MSSQL_pool, "f").connect(), "f");
50
- }
51
- async dbCall(q) {
52
- await __classPrivateFieldGet(this, _MSSQL_poolConnect, "f");
53
- const request = __classPrivateFieldGet(this, _MSSQL_pool, "f").request();
54
- const result = await request.query(q);
55
- return this.mapResult(result);
56
- }
57
- mapResult(result) {
58
- // TODO: see https://github.com/tediousjs/node-mssql/pull/1171
59
- const meta = result.recordset?.columns;
60
- if (meta != null && typeof __classPrivateFieldGet(this, _MSSQL_typeCast, "f") === "function") {
61
- return __classPrivateFieldGet(this, _MSSQL_typeCast, "f").call(this, result, meta);
62
- }
63
- return result.recordset;
64
- }
65
- formatQuery(q, values) {
66
- return TSqlString.format(q, values);
67
- }
68
- async beginTransaction(isolationLevel) {
69
- const transaction = new mssql.Transaction(__classPrivateFieldGet(this, _MSSQL_pool, "f"));
70
- let rolledBack = false;
71
- transaction.on("rollback", (aborted) => {
72
- // emited with aborted === true
73
- rolledBack = true;
74
- });
75
- async function handleError(err) {
76
- if (!rolledBack) {
77
- await transaction.rollback();
78
- }
79
- throw err;
80
- }
81
- const mapResult = this.mapResult.bind(this);
82
- let isolationLevelNumber;
83
- if (isolationLevel) {
84
- isolationLevelNumber = mssql.ISOLATION_LEVEL[isolationLevel.replace(" ", "_")];
85
- if (isolationLevelNumber == null) {
86
- throw new Error(`Invalid isolationLevel: ${isolationLevel}`);
87
- }
88
- }
89
- await transaction.begin(isolationLevelNumber);
90
- return {
91
- commit: () => transaction.commit().catch(handleError),
92
- rollback: () => transaction.rollback(),
93
- dbCall: (q) => new mssql.Request(transaction).query(q).then(mapResult).catch(handleError)
94
- };
95
- }
96
- async closePool() {
97
- await __classPrivateFieldGet(this, _MSSQL_pool, "f").close();
98
- }
99
- }
100
- exports.MSSQL = MSSQL;
101
- _MSSQL_pool = new WeakMap(), _MSSQL_poolConnect = new WeakMap(), _MSSQL_typeCast = new WeakMap();
@@ -1,3 +0,0 @@
1
- type TValueCast = (value: any) => any;
2
- export declare function typeCastMSSQL(customTypeCast?: (meta: any, mssql: any) => TValueCast): (result: any, meta: any) => any;
3
- export {};
@@ -1,62 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.typeCastMSSQL = typeCastMSSQL;
27
- const mssql = __importStar(require("mssql"));
28
- // TODO: see https://github.com/tediousjs/node-mssql/pull/1171
29
- function typeCastMSSQL(customTypeCast) {
30
- return function (result, meta) {
31
- let typeCasts = {};
32
- for (let k in meta) {
33
- const v = meta[k];
34
- if (typeof customTypeCast === "function") {
35
- const tc = customTypeCast(v, mssql);
36
- if (tc) {
37
- typeCasts[v.name] = tc;
38
- }
39
- }
40
- // ids
41
- if (v.identity === true || v.type === mssql.BigInt) {
42
- typeCasts[v.name] = (x) => (typeof x === "string" ? parseInt(x) : x);
43
- }
44
- // uuids
45
- if (v.type === mssql.UniqueIdentifier) {
46
- typeCasts[v.name] = (x) => typeof x === "string" ? x.toLocaleLowerCase() : x;
47
- }
48
- }
49
- const data = result.recordset;
50
- if (Object.keys(typeCasts).length === 0) {
51
- return data;
52
- }
53
- return data.map((x) => {
54
- for (let k of Object.keys(x)) {
55
- if (typeCasts[k]) {
56
- x[k] = typeCasts[k](x[k]);
57
- }
58
- }
59
- return x;
60
- });
61
- };
62
- }