@technicity/data-service-generator 0.8.4 → 0.10.0-next.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.
Files changed (43) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.js +4 -3
  3. package/dist/runtime/Cache.d.ts +18 -0
  4. package/dist/runtime/Cache.js +90 -0
  5. package/dist/runtime/Runtime.d.ts +23 -0
  6. package/dist/runtime/Runtime.js +29 -0
  7. package/dist/runtime/RuntimeKSQL.d.ts +1 -1
  8. package/dist/runtime/RuntimeKSQL.js +13 -11
  9. package/dist/runtime/RuntimeMSSQL.d.ts +18 -14
  10. package/dist/runtime/RuntimeMSSQL.js +48 -43
  11. package/dist/runtime/RuntimeMySQL.d.ts +11 -12
  12. package/dist/runtime/RuntimeMySQL.js +46 -79
  13. package/dist/runtime/lib/create.d.ts +12 -0
  14. package/dist/runtime/lib/create.js +175 -0
  15. package/dist/runtime/lib/delete.d.ts +5 -0
  16. package/dist/runtime/lib/delete.js +43 -0
  17. package/dist/runtime/lib/error.d.ts +9 -0
  18. package/dist/runtime/lib/error.js +22 -0
  19. package/dist/runtime/lib/getData.d.ts +4 -0
  20. package/dist/runtime/lib/getData.js +227 -0
  21. package/dist/runtime/lib/getSqlAst.js +2 -2
  22. package/dist/runtime/lib/getWhere.d.ts +17 -0
  23. package/dist/runtime/lib/getWhere.js +228 -4
  24. package/dist/runtime/lib/prepareWhere.d.ts +2 -0
  25. package/dist/runtime/lib/prepareWhere.js +158 -0
  26. package/dist/runtime/lib/resolve.d.ts +10 -0
  27. package/dist/runtime/lib/resolve.js +66 -0
  28. package/dist/runtime/lib/shared.d.ts +22 -12
  29. package/dist/runtime/lib/shared.js +16 -728
  30. package/dist/runtime/lib/typeCastMSSQL.js +1 -1
  31. package/dist/runtime/lib/update.d.ts +4 -0
  32. package/dist/runtime/lib/update.js +143 -0
  33. package/dist/runtime/lib/utility.d.ts +5 -0
  34. package/dist/runtime/lib/utility.js +15 -0
  35. package/package.json +8 -7
  36. package/dist/runtime/lib/MSSQL.d.ts +0 -13
  37. package/dist/runtime/lib/MSSQL.js +0 -73
  38. package/dist/runtime/lib/SDKNotFoundError.d.ts +0 -4
  39. package/dist/runtime/lib/SDKNotFoundError.js +0 -10
  40. package/dist/runtime/lib/getDateTimeStringMySQL.d.ts +0 -1
  41. package/dist/runtime/lib/getDateTimeStringMySQL.js +0 -8
  42. package/dist/runtime/lib/stringifyWhere.d.ts +0 -18
  43. package/dist/runtime/lib/stringifyWhere.js +0 -228
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export { generate } from "./generation/generate";
2
- export { SDKNotFoundError } from "./runtime/lib/SDKNotFoundError";
2
+ export { SDKNotFoundError, SDKBadWhereError } from "./runtime/lib/error";
3
3
  export { traverseFieldArgs } from "./traverseFieldArgs";
package/dist/index.js CHANGED
@@ -1,9 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.traverseFieldArgs = exports.SDKNotFoundError = exports.generate = void 0;
3
+ exports.traverseFieldArgs = exports.SDKBadWhereError = exports.SDKNotFoundError = exports.generate = void 0;
4
4
  var generate_1 = require("./generation/generate");
5
5
  Object.defineProperty(exports, "generate", { enumerable: true, get: function () { return generate_1.generate; } });
6
- var SDKNotFoundError_1 = require("./runtime/lib/SDKNotFoundError");
7
- Object.defineProperty(exports, "SDKNotFoundError", { enumerable: true, get: function () { return SDKNotFoundError_1.SDKNotFoundError; } });
6
+ var error_1 = require("./runtime/lib/error");
7
+ Object.defineProperty(exports, "SDKNotFoundError", { enumerable: true, get: function () { return error_1.SDKNotFoundError; } });
8
+ Object.defineProperty(exports, "SDKBadWhereError", { enumerable: true, get: function () { return error_1.SDKBadWhereError; } });
8
9
  var traverseFieldArgs_1 = require("./traverseFieldArgs");
9
10
  Object.defineProperty(exports, "traverseFieldArgs", { enumerable: true, get: function () { return traverseFieldArgs_1.traverseFieldArgs; } });
@@ -0,0 +1,18 @@
1
+ import { RedisClientType } from 'redis';
2
+ import { TResolveParams } from './IRuntime';
3
+ declare class Cache {
4
+ protected logs?: boolean | undefined;
5
+ client: RedisClientType;
6
+ waiting?: Set<() => void> | undefined;
7
+ constructor(url: string, logs?: boolean | undefined);
8
+ log(message: string): void;
9
+ pending(): Promise<void>;
10
+ from(input: TResolveParams): Promise<{
11
+ request: string;
12
+ cached: any;
13
+ }>;
14
+ insert(key: string, payload: any): Promise<void>;
15
+ read(key: string): Promise<any>;
16
+ purge(...uuids: string[]): Promise<void>;
17
+ }
18
+ export default Cache;
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const crypto_1 = require("crypto");
4
+ const redis_1 = require("redis");
5
+ const utility_1 = require("./lib/utility");
6
+ class Cache {
7
+ constructor(url, logs) {
8
+ this.logs = logs;
9
+ this.waiting = new Set();
10
+ this.client = (0, redis_1.createClient)({ url: `redis://${url}` });
11
+ this.client.connect();
12
+ this.client.on("connect", () => {
13
+ if (this.waiting)
14
+ this.waiting.forEach(x => x());
15
+ this.waiting = undefined;
16
+ });
17
+ }
18
+ log(message) {
19
+ if (this.logs)
20
+ console.log(message);
21
+ }
22
+ async pending() {
23
+ if (this.waiting)
24
+ return new Promise(res => this.waiting.add(res));
25
+ }
26
+ async from(input) {
27
+ let { action, args, fields, resource } = input;
28
+ const request = JSON.stringify({
29
+ action, resource, args, fields
30
+ });
31
+ const key = (0, crypto_1.createHash)('sha256')
32
+ .update(request)
33
+ .digest('hex');
34
+ const cached = await this.read(key);
35
+ return {
36
+ request: key,
37
+ cached
38
+ };
39
+ }
40
+ async insert(key, payload) {
41
+ const redis = this.client;
42
+ const json = JSON.stringify(payload);
43
+ const regex = /"uuid":"(.+?)"/g;
44
+ const pending = [];
45
+ for (let result; result = regex.exec(json);) {
46
+ const uuid = result[1];
47
+ if (!uuid)
48
+ continue;
49
+ pending.push(redis.sAdd(`deps:${uuid}`, [key]), redis.sAdd(`cached:${key}`, [uuid]));
50
+ }
51
+ if (!pending.length)
52
+ return;
53
+ this.log(`Cache insert: ${key.substring(0, 6)}`);
54
+ await Promise.all([
55
+ redis.set(`cache:${key}`, json),
56
+ ...pending
57
+ ]);
58
+ }
59
+ async read(key) {
60
+ await this.pending();
61
+ const data = await this.client.get(`cache:${key}`);
62
+ const shorthand = key.substring(0, 6);
63
+ if (data) {
64
+ this.log(`Cache hit: ${shorthand}`);
65
+ return JSON.parse(data);
66
+ }
67
+ else {
68
+ this.log(`Cache miss: ${shorthand}`);
69
+ return undefined;
70
+ }
71
+ }
72
+ async purge(...uuids) {
73
+ const redis = this.client;
74
+ await (0, utility_1.mapAsync)(uuids, uuid => {
75
+ const getDependancies = redis.sMembers(`deps:${uuid}`);
76
+ return [
77
+ (0, utility_1.mapAsync)(getDependancies, key => {
78
+ const getDependants = redis.sMembers(`cached:${key}`);
79
+ return [
80
+ (0, utility_1.mapAsync)(getDependants, uuid => (redis.sRem(`deps:${uuid}`, [key]))),
81
+ redis.del(`cache:${key}`),
82
+ redis.del(`cached:${key}`)
83
+ ];
84
+ }),
85
+ redis.del(`deps:${uuid}`)
86
+ ];
87
+ });
88
+ }
89
+ }
90
+ exports.default = Cache;
@@ -0,0 +1,23 @@
1
+ import Cache from './Cache';
2
+ import { IArtifacts, IRuntime, TMiddleware, TResolveParams } from './IRuntime';
3
+ import { MiddlewareHandler } from './lib/resolve';
4
+ declare abstract class Runtime implements IRuntime {
5
+ protected abstract $dialect: "mysql" | "mssql";
6
+ protected $clientCache?: Cache;
7
+ protected $middlewareHandler: MiddlewareHandler<TMiddleware>;
8
+ constructor(otherOpts: {
9
+ redisHost?: string;
10
+ }, clientOpts?: {
11
+ [k: string]: any;
12
+ });
13
+ protected abstract formatQuery(q: string, values: any[]): string;
14
+ protected abstract beginTransaction(): Promise<any>;
15
+ protected abstract dbCall(q: string): Promise<any>;
16
+ abstract $shutdown(): Promise<void>;
17
+ $queryRaw(sql: string, values?: any[]): Promise<any>;
18
+ resolve(input: TResolveParams): Promise<any>;
19
+ $use(middleware: TMiddleware): Promise<void>;
20
+ $prepareWhere(artifacts: IArtifacts, table: string, data: any): Promise<{}>;
21
+ $whereNeedsProcessing(where: any): boolean;
22
+ }
23
+ export default Runtime;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const Cache_1 = require("./Cache");
4
+ const prepareWhere_1 = require("./lib/prepareWhere");
5
+ const resolve_1 = require("./lib/resolve");
6
+ class Runtime {
7
+ constructor(otherOpts, clientOpts) {
8
+ this.$middlewareHandler = new resolve_1.MiddlewareHandler();
9
+ const debugCache = clientOpts?.debug?.includes("Cache");
10
+ if (otherOpts.redisHost)
11
+ this.$clientCache = new Cache_1.default(otherOpts.redisHost, debugCache);
12
+ }
13
+ async $queryRaw(sql, values) {
14
+ return this.dbCall(this.formatQuery(sql, values ?? []));
15
+ }
16
+ async resolve(input) {
17
+ return (0, resolve_1.resolve)(input, this.dbCall.bind(this), this.formatQuery.bind(this), this.beginTransaction.bind(this), this.$dialect, this.$middlewareHandler, input.context ?? {}, this.$clientCache);
18
+ }
19
+ async $use(middleware) {
20
+ this.$middlewareHandler.register(middleware);
21
+ }
22
+ async $prepareWhere(artifacts, table, data) {
23
+ return (0, prepareWhere_1.prepareWhere)(artifacts, table, data, this.dbCall.bind(this), this.formatQuery.bind(this));
24
+ }
25
+ $whereNeedsProcessing(where) {
26
+ return JSON.stringify(where).includes("Uuid");
27
+ }
28
+ }
29
+ exports.default = Runtime;
@@ -1,5 +1,5 @@
1
+ import { KSQL } from '../ksql';
1
2
  import type { IRuntime, TMiddleware, TResolveParams, IArtifacts, TDbCall } from "./IRuntime";
2
- import { KSQL } from "../ksql";
3
3
  declare type TGetTableName = (table: string) => string;
4
4
  export declare class RuntimeKSQL implements IRuntime {
5
5
  #private;
@@ -13,15 +13,17 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
13
13
  var _RuntimeKSQL_ksql, _RuntimeKSQL_middlewareHandler, _RuntimeKSQL_dbCall, _RuntimeKSQL_formatQuery, _RuntimeKSQL_getBaseTableName, _RuntimeKSQL_getMaterializedViewName, _RuntimeKSQL_doNotUseMaterializedViews;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.RuntimeKSQL = void 0;
16
- const SqlString = require("sqlstring");
17
16
  const async_hooks_1 = require("async_hooks");
18
- const _ = require("lodash");
19
17
  const graphql_relay_1 = require("graphql-relay");
20
- const shared_1 = require("./lib/shared");
18
+ const _ = require("lodash");
19
+ const SqlString = require("sqlstring");
21
20
  const ksql_1 = require("../ksql");
22
- const SDKNotFoundError_1 = require("./lib/SDKNotFoundError");
23
- const stringifyWhere_1 = require("./lib/stringifyWhere");
24
21
  const cursor_1 = require("./lib/cursor");
22
+ const error_1 = require("./lib/error");
23
+ const getWhere_1 = require("./lib/getWhere");
24
+ const prepareWhere_1 = require("./lib/prepareWhere");
25
+ const resolve_1 = require("./lib/resolve");
26
+ const shared_1 = require("./lib/shared");
25
27
  const escapeId = SqlString.escapeId.bind(SqlString);
26
28
  class RuntimeKSQL {
27
29
  constructor(clientOpts, otherOpts, artifacts) {
@@ -33,7 +35,7 @@ class RuntimeKSQL {
33
35
  _RuntimeKSQL_getMaterializedViewName.set(this, void 0);
34
36
  _RuntimeKSQL_doNotUseMaterializedViews.set(this, void 0);
35
37
  __classPrivateFieldSet(this, _RuntimeKSQL_ksql, new ksql_1.KSQL(clientOpts ?? {}), "f");
36
- __classPrivateFieldSet(this, _RuntimeKSQL_middlewareHandler, new shared_1.MiddlewareHandler(), "f");
38
+ __classPrivateFieldSet(this, _RuntimeKSQL_middlewareHandler, new resolve_1.MiddlewareHandler(), "f");
37
39
  __classPrivateFieldSet(this, _RuntimeKSQL_dbCall, typeof otherOpts._dbCall === "function"
38
40
  ? (q) => otherOpts._dbCall(q).then(mapResult)
39
41
  : (q) => __classPrivateFieldGet(this, _RuntimeKSQL_ksql, "f").streamQuery(q).then(mapResult), "f");
@@ -52,10 +54,10 @@ class RuntimeKSQL {
52
54
  __classPrivateFieldGet(this, _RuntimeKSQL_middlewareHandler, "f").register(middleware);
53
55
  }
54
56
  $whereNeedsProcessing(where) {
55
- return (0, shared_1.whereNeedsProcessing)(where);
57
+ return JSON.stringify(where).includes("Uuid");
56
58
  }
57
59
  async $prepareWhere(artifacts, table, data) {
58
- return (0, shared_1._prepareWhere)(artifacts, table, data, __classPrivateFieldGet(this, _RuntimeKSQL_dbCall, "f").bind(this), __classPrivateFieldGet(this, _RuntimeKSQL_formatQuery, "f").bind(this));
60
+ return (0, prepareWhere_1.prepareWhere)(artifacts, table, data, __classPrivateFieldGet(this, _RuntimeKSQL_dbCall, "f").bind(this), __classPrivateFieldGet(this, _RuntimeKSQL_formatQuery, "f").bind(this));
59
61
  }
60
62
  async $shutdown() {
61
63
  // Nothing to do here, I think
@@ -116,7 +118,7 @@ async function getData(input, dbCall, formatQuery, getBaseTableName, getMaterial
116
118
  action === "deleteMany";
117
119
  const data = await _getData(input, grabMany, dbCall, formatQuery, getBaseTableName, getMaterializedViewName, doNotUseMaterializedViews);
118
120
  if (data == null && !grabMany) {
119
- throw new SDKNotFoundError_1.SDKNotFoundError();
121
+ throw new error_1.SDKNotFoundError();
120
122
  }
121
123
  const scalarFields = input.artifacts[input.resource].scalarFields;
122
124
  if (action === "findManyPaginated" && data?.results != null) {
@@ -156,7 +158,7 @@ async function _getData(input, grabMany, dbCall, formatQuery, getBaseTableName,
156
158
  argsMapped = _.cloneDeep(argsMapped);
157
159
  argsMapped.$where = argsMapped.$where[table];
158
160
  }
159
- const whereResult = (0, stringifyWhere_1.stringifyWhere)({
161
+ const whereResult = (0, getWhere_1.stringifyWhere)({
160
162
  where: argsMapped.$where,
161
163
  table: escapeId(getTableName(table)),
162
164
  dialect: "mysql",
@@ -320,7 +322,7 @@ async function resolveDependentFields(table, parentData, mappedFields, relationF
320
322
  ],
321
323
  };
322
324
  const key = relationField.relations[1].foreignKey;
323
- const s = formatQuery(`SELECT ?? FROM ?? WHERE ${(0, stringifyWhere_1.stringifyWhere)({
325
+ const s = formatQuery(`SELECT ?? FROM ?? WHERE ${(0, getWhere_1.stringifyWhere)({
324
326
  where: whereJunction,
325
327
  table: escapeId(getBaseTableName(relationField.junctionTable)),
326
328
  dialect: "mysql",
@@ -1,19 +1,23 @@
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;
1
+ import * as mssql from 'mssql';
2
+ import { IArtifacts, ISupplementClientOpts } from './IRuntime';
3
+ import { typeCastMSSQL } from './lib/typeCastMSSQL';
4
+ import Runtime from './Runtime';
5
+ export declare class RuntimeMSSQL extends Runtime {
6
+ readonly $dialect = "mssql";
7
+ private $pool;
8
+ private $poolConnect;
9
+ private $typeCast?;
6
10
  constructor(clientOpts: mssql.config, otherOpts: {
7
11
  supplementClientOpts?: ISupplementClientOpts;
8
12
  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<{}>;
13
+ redisHost?: string;
14
+ }, artifacts?: IArtifacts);
15
15
  $shutdown(): Promise<void>;
16
- private dbCall;
17
- private formatQuery;
18
- private beginTransaction;
16
+ protected dbCall(q: string): Promise<any>;
17
+ protected formatQuery(q: string, values: any[]): any;
18
+ private mapResult;
19
+ protected beginTransaction(): Promise<{
20
+ commit: () => Promise<void>;
21
+ dbCall: (q: string) => Promise<any>;
22
+ }>;
19
23
  }
@@ -1,58 +1,63 @@
1
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
2
  Object.defineProperty(exports, "__esModule", { value: true });
15
3
  exports.RuntimeMSSQL = void 0;
16
- const shared_1 = require("./lib/shared");
17
- const MSSQL_1 = require("./lib/MSSQL");
4
+ const mssql = require("mssql");
5
+ // @ts-ignore
6
+ const TSqlString = require("tsqlstring");
18
7
  const typeCastMSSQL_1 = require("./lib/typeCastMSSQL");
19
- class RuntimeMSSQL {
8
+ const Runtime_1 = require("./Runtime");
9
+ class RuntimeMSSQL extends Runtime_1.default {
20
10
  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
11
+ super(otherOpts, clientOpts);
12
+ this.$dialect = "mssql";
13
+ this.$pool = new mssql.ConnectionPool(clientOpts);
14
+ this.$poolConnect = this.$pool.connect();
15
+ this.$typeCast = otherOpts?.supplementClientOpts
25
16
  ? (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, this.dbCall.bind(this), this.formatQuery.bind(this), this.beginTransaction.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));
17
+ : undefined;
43
18
  }
44
19
  async $shutdown() {
45
- await __classPrivateFieldGet(this, _RuntimeMSSQL_mssqlClient, "f").closePool();
20
+ await this.$pool.close();
46
21
  }
47
22
  async dbCall(q) {
48
- return __classPrivateFieldGet(this, _RuntimeMSSQL_mssqlClient, "f").dbCall(q);
23
+ await this.$poolConnect;
24
+ const request = this.$pool.request();
25
+ const result = await request.query(q);
26
+ return this.mapResult(result);
49
27
  }
50
28
  formatQuery(q, values) {
51
- return __classPrivateFieldGet(this, _RuntimeMSSQL_mssqlClient, "f").formatQuery(q, values);
52
- }
53
- beginTransaction() {
54
- return __classPrivateFieldGet(this, _RuntimeMSSQL_mssqlClient, "f").beginTransaction();
29
+ return TSqlString.format(q, values);
30
+ }
31
+ mapResult(result) {
32
+ // TODO: see https://github.com/tediousjs/node-mssql/pull/1171
33
+ const meta = result.recordset?.columns;
34
+ if (meta != null && typeof this.$typeCast === "function") {
35
+ return this.$typeCast(result, meta);
36
+ }
37
+ return result.recordset;
38
+ }
39
+ async beginTransaction() {
40
+ const transaction = new mssql.Transaction(this.$pool);
41
+ const mapResult = this.mapResult.bind(this);
42
+ let rolledBack = false;
43
+ transaction.on("rollback", (aborted) => {
44
+ // emited with aborted === true
45
+ rolledBack = true;
46
+ });
47
+ async function handleError(err) {
48
+ if (!rolledBack) {
49
+ await transaction.rollback();
50
+ }
51
+ throw err;
52
+ }
53
+ await transaction.begin();
54
+ return {
55
+ commit: () => transaction.commit().catch(handleError),
56
+ dbCall: (q) => new mssql.Request(transaction)
57
+ .query(q)
58
+ .then(mapResult)
59
+ .catch(handleError),
60
+ };
55
61
  }
56
62
  }
57
63
  exports.RuntimeMSSQL = RuntimeMSSQL;
58
- _RuntimeMSSQL_dialect = new WeakMap(), _RuntimeMSSQL_mssqlClient = new WeakMap(), _RuntimeMSSQL_middlewareHandler = new WeakMap();
@@ -1,18 +1,17 @@
1
- import type { IRuntime, TMiddleware, TResolveParams, IArtifacts, ISupplementClientOpts } from "./IRuntime";
2
- export declare class RuntimeMySQL implements IRuntime {
3
- #private;
1
+ import { IArtifacts, ISupplementClientOpts } from './IRuntime';
2
+ import Runtime from './Runtime';
3
+ export declare class RuntimeMySQL extends Runtime {
4
+ readonly $dialect = "mysql";
5
+ protected $pool: any;
4
6
  constructor(clientOpts: {
5
7
  [k: string]: any;
6
8
  }, otherOpts: {
7
9
  supplementClientOpts?: ISupplementClientOpts;
8
- }, artifacts: IArtifacts);
9
- resolve(input: TResolveParams): Promise<any>;
10
- $queryRaw(sql: string, values?: any[]): Promise<any>;
11
- $use(middleware: TMiddleware): Promise<void>;
12
- $whereNeedsProcessing(where: any): boolean;
13
- $prepareWhere(artifacts: IArtifacts, table: string, data: any): Promise<{}>;
10
+ redisHost?: string;
11
+ }, artifacts?: IArtifacts);
14
12
  $shutdown(): Promise<void>;
15
- private dbCall;
16
- private formatQuery;
17
- private beginTransaction;
13
+ dbCall(q: string, args?: any[]): any;
14
+ protected formatQuery(q: string, values: any[]): string;
15
+ protected beginTransaction(): any;
16
+ protected getConnection(): Promise<any>;
18
17
  }
@@ -1,95 +1,62 @@
1
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 _RuntimeMySQL_dialect, _RuntimeMySQL_mysqlClient, _RuntimeMySQL_middlewareHandler;
14
2
  Object.defineProperty(exports, "__esModule", { value: true });
15
3
  exports.RuntimeMySQL = void 0;
16
4
  const SqlString = require("sqlstring");
17
- const MySQL_1 = require("./lib/MySQL");
18
- const shared_1 = require("./lib/shared");
19
- class RuntimeMySQL {
5
+ const Runtime_1 = require("./Runtime");
6
+ const mysql = require("mysql");
7
+ const P = require("bluebird");
8
+ P.promisifyAll(require("mysql/lib/Connection").prototype);
9
+ P.promisifyAll(require("mysql/lib/Pool").prototype);
10
+ class RuntimeMySQL extends Runtime_1.default {
20
11
  constructor(clientOpts, otherOpts, artifacts) {
21
- _RuntimeMySQL_dialect.set(this, "mysql");
22
- _RuntimeMySQL_mysqlClient.set(this, void 0);
23
- _RuntimeMySQL_middlewareHandler.set(this, void 0);
24
- __classPrivateFieldSet(this, _RuntimeMySQL_middlewareHandler, new shared_1.MiddlewareHandler(), "f");
25
- if (otherOpts.supplementClientOpts) {
26
- clientOpts = {
27
- supportBigNumbers: true,
28
- typeCast: (field, next) => {
29
- if (field.type == "TINY" && field.length == 1) {
30
- return field.string() == "1";
31
- }
32
- // if (field.type === "DATE") {
33
- // return field.string();
34
- // }
35
- // if (
36
- // field.type === "TIMESTAMP" ||
37
- // field.type === "DATE" ||
38
- // field.type === "DATETIME"
39
- // ) {
40
- // return new Date(field.string()).toISOString();
41
- // }
42
- if (field.type === "VAR_STRING" || field.type === "STRING") {
43
- return field.string();
44
- }
45
- return next();
46
- },
47
- ...clientOpts,
48
- };
49
- }
50
- else {
51
- clientOpts = {
52
- typeCast: (field, next) => {
53
- if (field.type == "TINY" && field.length == 1) {
54
- return field.string() == "1";
55
- }
56
- if (field.type === "VAR_STRING" || field.type === "STRING") {
57
- return field.string();
58
- }
59
- return next();
60
- },
61
- ...clientOpts,
62
- };
63
- }
64
- __classPrivateFieldSet(this, _RuntimeMySQL_mysqlClient, new MySQL_1.MySQL(clientOpts), "f");
65
- }
66
- async resolve(input) {
67
- return (0, shared_1.resolve)(input, this.dbCall.bind(this), this.formatQuery.bind(this), this.beginTransaction.bind(this), __classPrivateFieldGet(this, _RuntimeMySQL_dialect, "f"), __classPrivateFieldGet(this, _RuntimeMySQL_middlewareHandler, "f"), input.context ?? {});
68
- }
69
- async $queryRaw(sql, values) {
70
- return this.dbCall(this.formatQuery(sql, values ?? []));
71
- }
72
- async $use(middleware) {
73
- __classPrivateFieldGet(this, _RuntimeMySQL_middlewareHandler, "f").register(middleware);
74
- }
75
- $whereNeedsProcessing(where) {
76
- return (0, shared_1.whereNeedsProcessing)(where);
77
- }
78
- async $prepareWhere(artifacts, table, data) {
79
- return (0, shared_1._prepareWhere)(artifacts, table, data, this.dbCall.bind(this), this.formatQuery.bind(this));
12
+ super(otherOpts, clientOpts);
13
+ this.$dialect = "mysql";
14
+ if (otherOpts.supplementClientOpts)
15
+ clientOpts.supportBigNumbers = true;
16
+ clientOpts.typeCast = (field, next) => {
17
+ if (field.type == "TINY" && field.length == 1)
18
+ return field.string() == "1";
19
+ // if(otherOpts.supplementClientOpts){
20
+ // if (field.type === "DATE")
21
+ // return field.string();
22
+ //
23
+ // if (["TIMESTAMP", "DATETIME"].includes(field.type))
24
+ // return new Date(field.string()).toISOString();
25
+ // }
26
+ if (field.type === "VAR_STRING" || field.type === "STRING")
27
+ return field.string();
28
+ return next();
29
+ };
30
+ // this.$client = new MySQL(clientOpts);
31
+ this.$pool = mysql.createPool(clientOpts);
80
32
  }
81
33
  async $shutdown() {
82
- await __classPrivateFieldGet(this, _RuntimeMySQL_mysqlClient, "f").endPool();
34
+ await this.$pool.endAsync();
83
35
  }
84
- dbCall(q) {
85
- return __classPrivateFieldGet(this, _RuntimeMySQL_mysqlClient, "f").query(q);
36
+ dbCall(q, args) {
37
+ return P.using(this.getConnection(), (connection) => connection.queryAsync(q, args));
86
38
  }
87
39
  formatQuery(q, values) {
88
40
  return SqlString.format(q, values);
89
41
  }
90
42
  beginTransaction() {
91
- return __classPrivateFieldGet(this, _RuntimeMySQL_mysqlClient, "f").beginTransaction();
43
+ return P.using(this.getConnection(), async (connection) => {
44
+ async function handleError(err) {
45
+ await connection.rollbackAsync();
46
+ throw err;
47
+ }
48
+ await connection.beginTransactionAsync();
49
+ return {
50
+ commit: () => connection.commitAsync().catch(handleError),
51
+ dbCall: (q) => connection.queryAsync(q).catch(handleError),
52
+ };
53
+ });
54
+ }
55
+ // http://bluebirdjs.com/docs/api/disposer.html
56
+ async getConnection() {
57
+ return this.$pool
58
+ .getConnectionAsync()
59
+ .disposer((connection) => connection.release());
92
60
  }
93
61
  }
94
62
  exports.RuntimeMySQL = RuntimeMySQL;
95
- _RuntimeMySQL_dialect = new WeakMap(), _RuntimeMySQL_mysqlClient = new WeakMap(), _RuntimeMySQL_middlewareHandler = new WeakMap();
@@ -0,0 +1,12 @@
1
+ import { IDialect, TBeginTransaction, TContext, TDbCall, TFormatQuery, TResolveParams } from '../IRuntime';
2
+ export declare function create(input: TResolveParams, dbCall: TDbCall, formatQuery: TFormatQuery, beginTransaction: TBeginTransaction, dialect: IDialect, context: TContext): Promise<any>;
3
+ declare type TRunCreateTreeSQL = (table: string, referencedKey: string | null, referencedKeyValue: number | string | null, columns: string[][], values: any[][], dbCall: TDbCall, formatQuery: TFormatQuery) => Promise<any[]>;
4
+ export declare function runCreateTree(tree: TCreateTree, referencedKeyValue: number | string | null, runCreateTreeSQL: TRunCreateTreeSQL, dbCall: TDbCall, formatQuery: TFormatQuery, dialect: IDialect): Promise<any[]>;
5
+ declare type TCreateTree = {
6
+ table: string;
7
+ referencedKey: string | null;
8
+ columns: string[][];
9
+ values: any[][];
10
+ children: TCreateTree[][];
11
+ };
12
+ export {};