@sqb/connect 4.0.9 → 4.0.13

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 (89) hide show
  1. package/dist/client/Adapter.d.ts +57 -0
  2. package/dist/client/Adapter.js +2 -0
  3. package/dist/client/Cursor.d.ts +116 -0
  4. package/dist/client/Cursor.js +250 -0
  5. package/dist/client/CursorStream.d.ts +29 -0
  6. package/dist/client/CursorStream.js +98 -0
  7. package/dist/client/FieldInfoMap.d.ts +10 -0
  8. package/dist/client/FieldInfoMap.js +33 -0
  9. package/dist/client/SqbClient.d.ts +70 -0
  10. package/dist/client/SqbClient.js +165 -0
  11. package/dist/client/SqbConnection.d.ts +74 -0
  12. package/dist/client/SqbConnection.js +272 -0
  13. package/dist/client/extensions.d.ts +4 -0
  14. package/dist/client/extensions.js +14 -0
  15. package/dist/client/helpers.d.ts +9 -0
  16. package/dist/client/helpers.js +133 -0
  17. package/dist/client/types.d.ts +189 -0
  18. package/dist/client/types.js +5 -0
  19. package/dist/index.d.ts +28 -0
  20. package/dist/index.js +37 -0
  21. package/dist/orm/base-entity.class.d.ts +16 -0
  22. package/dist/orm/base-entity.class.js +56 -0
  23. package/dist/orm/commands/command.helper.d.ts +14 -0
  24. package/dist/orm/commands/command.helper.js +140 -0
  25. package/dist/orm/commands/count.command.d.ts +11 -0
  26. package/dist/orm/commands/count.command.js +30 -0
  27. package/dist/orm/commands/create.command.d.ts +20 -0
  28. package/dist/orm/commands/create.command.js +83 -0
  29. package/dist/orm/commands/destroy.command.d.ts +11 -0
  30. package/dist/orm/commands/destroy.command.js +30 -0
  31. package/dist/orm/commands/find.command.d.ts +44 -0
  32. package/dist/orm/commands/find.command.js +308 -0
  33. package/dist/orm/commands/row-converter.d.ts +55 -0
  34. package/dist/orm/commands/row-converter.js +187 -0
  35. package/dist/orm/commands/update.command.d.ts +22 -0
  36. package/dist/orm/commands/update.command.js +82 -0
  37. package/dist/orm/decorators/column.decorator.d.ts +4 -0
  38. package/dist/orm/decorators/column.decorator.js +14 -0
  39. package/dist/orm/decorators/embedded.decorator.d.ts +2 -0
  40. package/dist/orm/decorators/embedded.decorator.js +17 -0
  41. package/dist/orm/decorators/entity.decorator.d.ts +6 -0
  42. package/dist/orm/decorators/entity.decorator.js +23 -0
  43. package/dist/orm/decorators/events.decorator.d.ts +6 -0
  44. package/dist/orm/decorators/events.decorator.js +76 -0
  45. package/dist/orm/decorators/foreignkey.decorator.d.ts +2 -0
  46. package/dist/orm/decorators/foreignkey.decorator.js +13 -0
  47. package/dist/orm/decorators/index.decorator.d.ts +3 -0
  48. package/dist/orm/decorators/index.decorator.js +22 -0
  49. package/dist/orm/decorators/link.decorator.d.ts +23 -0
  50. package/dist/orm/decorators/link.decorator.js +88 -0
  51. package/dist/orm/decorators/primarykey.decorator.d.ts +3 -0
  52. package/dist/orm/decorators/primarykey.decorator.js +23 -0
  53. package/dist/orm/decorators/transform.decorator.d.ts +3 -0
  54. package/dist/orm/decorators/transform.decorator.js +24 -0
  55. package/dist/orm/model/abstract-entityelement.d.ts +8 -0
  56. package/dist/orm/model/abstract-entityelement.js +10 -0
  57. package/dist/orm/model/association-node.d.ts +9 -0
  58. package/dist/orm/model/association-node.js +25 -0
  59. package/dist/orm/model/association.d.ts +28 -0
  60. package/dist/orm/model/association.js +129 -0
  61. package/dist/orm/model/entity-association-element.d.ts +9 -0
  62. package/dist/orm/model/entity-association-element.js +13 -0
  63. package/dist/orm/model/entity-column-element.d.ts +68 -0
  64. package/dist/orm/model/entity-column-element.js +27 -0
  65. package/dist/orm/model/entity-model.d.ts +59 -0
  66. package/dist/orm/model/entity-model.js +295 -0
  67. package/dist/orm/model/entity-object-element.d.ts +12 -0
  68. package/dist/orm/model/entity-object-element.js +24 -0
  69. package/dist/orm/model/index-meta.d.ts +9 -0
  70. package/dist/orm/model/index-meta.js +16 -0
  71. package/dist/orm/model/link-chain.d.ts +15 -0
  72. package/dist/orm/model/link-chain.js +50 -0
  73. package/dist/orm/orm.const.d.ts +2 -0
  74. package/dist/orm/orm.const.js +5 -0
  75. package/dist/orm/orm.type.d.ts +112 -0
  76. package/dist/orm/orm.type.js +2 -0
  77. package/dist/orm/repository.class.d.ts +125 -0
  78. package/dist/orm/repository.class.js +217 -0
  79. package/dist/orm/util/entity-mapping.d.ts +12 -0
  80. package/dist/orm/util/entity-mapping.js +154 -0
  81. package/dist/orm/util/extract-keyvalues.d.ts +2 -0
  82. package/dist/orm/util/extract-keyvalues.js +60 -0
  83. package/dist/orm/util/orm.helper.d.ts +14 -0
  84. package/dist/orm/util/orm.helper.js +39 -0
  85. package/dist/orm/util/serialize-element.d.ts +2 -0
  86. package/dist/orm/util/serialize-element.js +43 -0
  87. package/dist/types.d.ts +2 -0
  88. package/dist/types.js +2 -0
  89. package/package.json +3 -3
@@ -0,0 +1,189 @@
1
+ import { Maybe } from 'ts-gems';
2
+ import { DataType, ParamOptions } from '@sqb/builder';
3
+ import type { SqbConnection } from './SqbConnection';
4
+ import type { FieldInfoMap } from './FieldInfoMap';
5
+ import type { Cursor } from './Cursor';
6
+ import type { PoolConfiguration } from 'lightning-pool';
7
+ import type { Adapter } from './Adapter';
8
+ export { DataType } from '@sqb/builder';
9
+ export declare type ExecuteHookFunction = (connection: SqbConnection, request: QueryRequest) => Promise<void>;
10
+ export declare type FetchFunction = (row: any, request: QueryRequest) => void;
11
+ export declare type ValueTransformFunction = (value: any, fieldInfo?: FieldInfo) => any;
12
+ export declare type TransactionFunction = (connection: SqbConnection) => Promise<any>;
13
+ export declare type RowType = 'array' | 'object';
14
+ export declare type FieldNaming = 'original' | 'lowercase' | 'uppercase' | 'camelcase' | 'pascalcase' | ((fieldName: string) => Maybe<string>);
15
+ export declare type ObjectRow = Record<string, any>;
16
+ export declare type ArrayRow = any[];
17
+ export declare type ObjectRowset = ObjectRow[];
18
+ export declare type ArrayRowset = ArrayRow[];
19
+ export interface ClientConfiguration {
20
+ /**
21
+ * Dialect to be used
22
+ */
23
+ dialect?: string;
24
+ /**
25
+ * Database connection driver to be used
26
+ */
27
+ driver?: string;
28
+ /**
29
+ * Connection name
30
+ */
31
+ name?: string;
32
+ /**
33
+ * Database server address or url
34
+ */
35
+ host?: string;
36
+ /**
37
+ * Database listener port number
38
+ *
39
+ */
40
+ port?: number;
41
+ /**
42
+ * Database username.
43
+ */
44
+ user?: string;
45
+ /**
46
+ * Database password.
47
+ */
48
+ password?: string;
49
+ /**
50
+ * Database name
51
+ */
52
+ database?: string;
53
+ /**
54
+ * Database schema
55
+ */
56
+ schema?: string;
57
+ /**
58
+ * Connection options to be passed to the underlying driver
59
+ */
60
+ driverOptions?: any;
61
+ /**
62
+ * Pooling options
63
+ */
64
+ pool?: PoolConfiguration;
65
+ /**
66
+ * Default options
67
+ */
68
+ defaults?: ClientDefaults;
69
+ }
70
+ export interface ClientDefaults {
71
+ autoCommit?: boolean;
72
+ cursor?: boolean;
73
+ objectRows?: boolean;
74
+ fieldNaming?: FieldNaming;
75
+ showSql?: boolean;
76
+ prettyPrint?: boolean;
77
+ ignoreNulls?: boolean;
78
+ /**
79
+ * Sets how many row will be fetched at a time
80
+ * Default = 10
81
+ */
82
+ fetchRows?: number;
83
+ transform?: ValueTransformFunction;
84
+ }
85
+ export interface ConnectionOptions {
86
+ /**
87
+ * If this property is true, the transaction committed at the end of query execution.
88
+ * Default = false
89
+ */
90
+ autoCommit?: boolean;
91
+ }
92
+ export interface QueryExecuteOptions {
93
+ /**
94
+ * Array of values or object that contains param/value pairs.
95
+ */
96
+ params?: Record<string, any> | any[];
97
+ /**
98
+ * If this property is true, the transaction committed at the end of query execution.
99
+ * Default = false
100
+ */
101
+ autoCommit?: boolean;
102
+ /**
103
+ * If this property is true, query returns a Cursor object that works
104
+ * in unidirectional "cursor" mode.
105
+ * Important! Cursor keeps connection open until cursor.close() method is called.
106
+ */
107
+ cursor?: boolean;
108
+ /**
109
+ * Function for converting data before returning response.
110
+ */
111
+ transform?: ValueTransformFunction;
112
+ /**
113
+ * In "cursor" mode; it provides an initial suggested number of rows to prefetch.
114
+ * Prefetching is a tuning option to maximize data transfer efficiency and
115
+ * minimize round-trips to the database. In regular mode;
116
+ * it provides the maximum number of rows that are fetched from Connection instance.
117
+ * Default = 10
118
+ */
119
+ fetchRows?: number;
120
+ /**
121
+ * If set true, NULL fields will be ignored
122
+ * Default = false
123
+ */
124
+ ignoreNulls?: boolean;
125
+ /**
126
+ * Sets the naming strategy for fields. It affects field names in object rows and metadata
127
+ */
128
+ namingStrategy?: FieldNaming;
129
+ /**
130
+ * Determines whether query rows should be returned as Objects or Arrays.
131
+ * This property applies to ResultSet.objectRows property also.
132
+ * Default = driver default
133
+ */
134
+ objectRows?: boolean;
135
+ /**
136
+ * If set true, result object contains executed sql and values.
137
+ * Default = false
138
+ */
139
+ showSql?: boolean;
140
+ prettyPrint?: boolean;
141
+ action?: string;
142
+ fetchAsString?: DataType[];
143
+ }
144
+ export interface QueryResult {
145
+ executeTime: number;
146
+ fields?: FieldInfoMap;
147
+ rows?: Record<string, any>[] | any[][];
148
+ rowType?: RowType;
149
+ query?: QueryRequest;
150
+ returns?: any;
151
+ rowsAffected?: number;
152
+ cursor?: Cursor;
153
+ }
154
+ export interface ObjectQueryResult extends QueryResult {
155
+ rows?: Record<string, any>[];
156
+ rowType?: 'object';
157
+ }
158
+ export interface ArrayQueryResult extends QueryResult {
159
+ rows?: any[][];
160
+ rowType?: 'array';
161
+ }
162
+ export declare type FieldInfo = {
163
+ index: number;
164
+ name: string;
165
+ } & Adapter.Field;
166
+ export interface QueryRequest {
167
+ dialect?: string;
168
+ dialectVersion?: string;
169
+ sql: string;
170
+ params?: any;
171
+ paramOptions?: Record<string, ParamOptions> | ParamOptions[];
172
+ returningFields?: {
173
+ field: string;
174
+ alias?: string;
175
+ }[];
176
+ autoCommit?: boolean;
177
+ cursor?: boolean;
178
+ objectRows?: boolean;
179
+ ignoreNulls?: boolean;
180
+ fetchRows?: number;
181
+ fieldNaming?: FieldNaming;
182
+ transform?: ValueTransformFunction;
183
+ showSql?: boolean;
184
+ prettyPrint?: boolean;
185
+ action?: string;
186
+ fetchAsString?: DataType[];
187
+ executeHooks?: ExecuteHookFunction[];
188
+ fetchHooks?: FetchFunction[];
189
+ }
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DataType = void 0;
4
+ var builder_1 = require("@sqb/builder");
5
+ Object.defineProperty(exports, "DataType", { enumerable: true, get: function () { return builder_1.DataType; } });
@@ -0,0 +1,28 @@
1
+ export { Type, Maybe, DeepPartial, DeepPickWritable, DeepBuildable } from 'ts-gems';
2
+ export * from './types';
3
+ export * from './client/types';
4
+ export * from './client/Adapter';
5
+ export * from './client/SqbClient';
6
+ export * from './client/SqbConnection';
7
+ export * from './client/Cursor';
8
+ export { registerAdapter, unRegisterAdapter } from './client/extensions';
9
+ export * from './orm/orm.type';
10
+ export * from './orm/base-entity.class';
11
+ export * from './orm/decorators/entity.decorator';
12
+ export * from './orm/decorators/primarykey.decorator';
13
+ export * from './orm/decorators/index.decorator';
14
+ export * from './orm/decorators/column.decorator';
15
+ export * from './orm/decorators/link.decorator';
16
+ export * from './orm/decorators/embedded.decorator';
17
+ export * from './orm/decorators/foreignkey.decorator';
18
+ export * from './orm/decorators/events.decorator';
19
+ export * from './orm/decorators/transform.decorator';
20
+ export * from './orm/repository.class';
21
+ export * from './orm/model/entity-model';
22
+ export * from './orm/model/entity-column-element';
23
+ export * from './orm/model/entity-object-element';
24
+ export * from './orm/model/entity-association-element';
25
+ export * from './orm/model/association';
26
+ export * from './orm/model/index-meta';
27
+ export * from './orm/util/entity-mapping';
28
+ export { isColumnElement, isObjectElement, isAssociationElement, isEntityClass } from './orm/util/orm.helper';
package/dist/index.js ADDED
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isEntityClass = exports.isAssociationElement = exports.isObjectElement = exports.isColumnElement = exports.unRegisterAdapter = exports.registerAdapter = void 0;
4
+ const tslib_1 = require("tslib");
5
+ tslib_1.__exportStar(require("./types"), exports);
6
+ tslib_1.__exportStar(require("./client/types"), exports);
7
+ tslib_1.__exportStar(require("./client/Adapter"), exports);
8
+ tslib_1.__exportStar(require("./client/SqbClient"), exports);
9
+ tslib_1.__exportStar(require("./client/SqbConnection"), exports);
10
+ tslib_1.__exportStar(require("./client/Cursor"), exports);
11
+ var extensions_1 = require("./client/extensions");
12
+ Object.defineProperty(exports, "registerAdapter", { enumerable: true, get: function () { return extensions_1.registerAdapter; } });
13
+ Object.defineProperty(exports, "unRegisterAdapter", { enumerable: true, get: function () { return extensions_1.unRegisterAdapter; } });
14
+ tslib_1.__exportStar(require("./orm/orm.type"), exports);
15
+ tslib_1.__exportStar(require("./orm/base-entity.class"), exports);
16
+ tslib_1.__exportStar(require("./orm/decorators/entity.decorator"), exports);
17
+ tslib_1.__exportStar(require("./orm/decorators/primarykey.decorator"), exports);
18
+ tslib_1.__exportStar(require("./orm/decorators/index.decorator"), exports);
19
+ tslib_1.__exportStar(require("./orm/decorators/column.decorator"), exports);
20
+ tslib_1.__exportStar(require("./orm/decorators/link.decorator"), exports);
21
+ tslib_1.__exportStar(require("./orm/decorators/embedded.decorator"), exports);
22
+ tslib_1.__exportStar(require("./orm/decorators/foreignkey.decorator"), exports);
23
+ tslib_1.__exportStar(require("./orm/decorators/events.decorator"), exports);
24
+ tslib_1.__exportStar(require("./orm/decorators/transform.decorator"), exports);
25
+ tslib_1.__exportStar(require("./orm/repository.class"), exports);
26
+ tslib_1.__exportStar(require("./orm/model/entity-model"), exports);
27
+ tslib_1.__exportStar(require("./orm/model/entity-column-element"), exports);
28
+ tslib_1.__exportStar(require("./orm/model/entity-object-element"), exports);
29
+ tslib_1.__exportStar(require("./orm/model/entity-association-element"), exports);
30
+ tslib_1.__exportStar(require("./orm/model/association"), exports);
31
+ tslib_1.__exportStar(require("./orm/model/index-meta"), exports);
32
+ tslib_1.__exportStar(require("./orm/util/entity-mapping"), exports);
33
+ var orm_helper_1 = require("./orm/util/orm.helper");
34
+ Object.defineProperty(exports, "isColumnElement", { enumerable: true, get: function () { return orm_helper_1.isColumnElement; } });
35
+ Object.defineProperty(exports, "isObjectElement", { enumerable: true, get: function () { return orm_helper_1.isObjectElement; } });
36
+ Object.defineProperty(exports, "isAssociationElement", { enumerable: true, get: function () { return orm_helper_1.isAssociationElement; } });
37
+ Object.defineProperty(exports, "isEntityClass", { enumerable: true, get: function () { return orm_helper_1.isEntityClass; } });
@@ -0,0 +1,16 @@
1
+ import { PickReadonly, PickWritable, Type } from 'ts-gems';
2
+ import { REPOSITORY_KEY } from './orm.const';
3
+ export declare abstract class BaseEntity {
4
+ private [REPOSITORY_KEY];
5
+ constructor(partial?: any);
6
+ destroy(): Promise<boolean>;
7
+ exists(): Promise<boolean>;
8
+ toJSON(): any;
9
+ }
10
+ export declare function getElementNames<T, K extends keyof T>(classRef: Type<T>): K[];
11
+ export declare function getColumnNames<T, K extends keyof PickWritable<T>>(classRef: Type<T>): K[];
12
+ export declare function getObjectElementNames<T, K extends keyof PickWritable<T>>(classRef: Type<T>): K[];
13
+ export declare function getAssociationElementNames<T, K extends keyof PickReadonly<T>>(classRef: Type<T>): K[];
14
+ export declare function getNonAssociationElementNames<T, K extends keyof PickWritable<T>>(classRef: Type<T>): K[];
15
+ export declare function getInsertColumnNames<T, K extends keyof PickWritable<T>>(classRef: Type<T>): K[];
16
+ export declare function getUpdateColumnNames<T, K extends keyof PickWritable<T>>(classRef: Type<T>): K[];
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getUpdateColumnNames = exports.getInsertColumnNames = exports.getNonAssociationElementNames = exports.getAssociationElementNames = exports.getObjectElementNames = exports.getColumnNames = exports.getElementNames = exports.BaseEntity = void 0;
4
+ const orm_const_1 = require("./orm.const");
5
+ const entity_model_1 = require("./model/entity-model");
6
+ class BaseEntity {
7
+ constructor(partial) {
8
+ const elements = entity_model_1.EntityModel.getColumnNames(Object.getPrototypeOf(this).constructor);
9
+ if (elements && partial) {
10
+ for (const k of elements)
11
+ if (partial[k] !== undefined)
12
+ this[k] = partial[k];
13
+ }
14
+ }
15
+ async destroy() {
16
+ const repo = this[orm_const_1.REPOSITORY_KEY];
17
+ return repo.destroy(this);
18
+ }
19
+ async exists() {
20
+ const repo = this[orm_const_1.REPOSITORY_KEY];
21
+ return repo.exists(this);
22
+ }
23
+ toJSON() {
24
+ // this method is an placeholder an will be overwritten by declareEntity() method
25
+ return this;
26
+ }
27
+ }
28
+ exports.BaseEntity = BaseEntity;
29
+ function getElementNames(classRef) {
30
+ return (entity_model_1.EntityModel.getElementNames(classRef) || []);
31
+ }
32
+ exports.getElementNames = getElementNames;
33
+ function getColumnNames(classRef) {
34
+ return (entity_model_1.EntityModel.getColumnNames(classRef) || []);
35
+ }
36
+ exports.getColumnNames = getColumnNames;
37
+ function getObjectElementNames(classRef) {
38
+ return (entity_model_1.EntityModel.getObjectElementNames(classRef) || []);
39
+ }
40
+ exports.getObjectElementNames = getObjectElementNames;
41
+ function getAssociationElementNames(classRef) {
42
+ return (entity_model_1.EntityModel.getAssociationElementNames(classRef) || []);
43
+ }
44
+ exports.getAssociationElementNames = getAssociationElementNames;
45
+ function getNonAssociationElementNames(classRef) {
46
+ return (entity_model_1.EntityModel.getNonAssociationElementNames(classRef) || []);
47
+ }
48
+ exports.getNonAssociationElementNames = getNonAssociationElementNames;
49
+ function getInsertColumnNames(classRef) {
50
+ return (entity_model_1.EntityModel.getInsertColumnNames(classRef) || []);
51
+ }
52
+ exports.getInsertColumnNames = getInsertColumnNames;
53
+ function getUpdateColumnNames(classRef) {
54
+ return (entity_model_1.EntityModel.getUpdateColumnNames(classRef) || []);
55
+ }
56
+ exports.getUpdateColumnNames = getUpdateColumnNames;
@@ -0,0 +1,14 @@
1
+ import { JoinStatement, LogicalOperator } from '@sqb/builder';
2
+ import { EntityModel } from '../model/entity-model';
3
+ import { AssociationNode } from '../model/association-node';
4
+ export interface JoinInfo {
5
+ association: AssociationNode;
6
+ sourceEntity: EntityModel;
7
+ targetEntity: EntityModel;
8
+ joinAlias: string;
9
+ join: JoinStatement;
10
+ }
11
+ export declare function joinAssociationGetFirst(joinInfos: JoinInfo[], association: AssociationNode, parentAlias: string, innerJoin?: boolean): Promise<JoinInfo>;
12
+ export declare function joinAssociationGetLast(joinInfos: JoinInfo[], association: AssociationNode, parentAlias: string, innerJoin?: boolean): Promise<JoinInfo>;
13
+ export declare function joinAssociation(joinInfos: JoinInfo[], association: AssociationNode, parentAlias: string, innerJoin?: boolean): Promise<JoinInfo[]>;
14
+ export declare function prepareFilter(entityDef: EntityModel, filter: any, trgOp: LogicalOperator, tableAlias?: string): Promise<void>;
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.prepareFilter = exports.joinAssociation = exports.joinAssociationGetLast = exports.joinAssociationGetFirst = void 0;
4
+ const builder_1 = require("@sqb/builder");
5
+ const orm_helper_1 = require("../util/orm.helper");
6
+ async function joinAssociationGetFirst(joinInfos, association, parentAlias, innerJoin) {
7
+ const joins = await joinAssociation(joinInfos, association, parentAlias, innerJoin);
8
+ return joins[0];
9
+ }
10
+ exports.joinAssociationGetFirst = joinAssociationGetFirst;
11
+ async function joinAssociationGetLast(joinInfos, association, parentAlias, innerJoin) {
12
+ const joins = await joinAssociation(joinInfos, association, parentAlias, innerJoin);
13
+ return joins[joins.length - 1];
14
+ }
15
+ exports.joinAssociationGetLast = joinAssociationGetLast;
16
+ async function joinAssociation(joinInfos, association, parentAlias, innerJoin) {
17
+ let joinInfo;
18
+ let node = association;
19
+ const result = [];
20
+ while (node) {
21
+ joinInfo = joinInfos.find(j => j.association === node);
22
+ if (!joinInfo) {
23
+ const targetEntity = await node.resolveTarget();
24
+ const sourceEntity = await node.resolveSource();
25
+ const keyCol = await node.resolveSourceProperty();
26
+ const targetCol = await node.resolveTargetProperty();
27
+ const joinAlias = 'J' + (joinInfos.length + 1);
28
+ const join = innerJoin ? (0, builder_1.InnerJoin)(targetEntity.tableName + ' as ' + joinAlias) :
29
+ (0, builder_1.LeftOuterJoin)(targetEntity.tableName + ' as ' + joinAlias);
30
+ join.on((0, builder_1.Eq)((0, builder_1.Field)(joinAlias + '.' + targetCol.fieldName, targetCol.dataType, targetCol.isArray), (0, builder_1.Field)(parentAlias + '.' + keyCol.fieldName, keyCol.dataType, keyCol.isArray)));
31
+ if (node.conditions)
32
+ await prepareFilter(targetEntity, node.conditions, join._conditions, joinAlias);
33
+ joinInfo = {
34
+ association: node,
35
+ sourceEntity,
36
+ targetEntity,
37
+ joinAlias,
38
+ join
39
+ };
40
+ joinInfos.push(joinInfo);
41
+ }
42
+ result.push(joinInfo);
43
+ if (!node.next)
44
+ break;
45
+ parentAlias = joinInfo.joinAlias;
46
+ node = node.next;
47
+ }
48
+ return result;
49
+ }
50
+ exports.joinAssociation = joinAssociation;
51
+ async function prepareFilter(entityDef, filter, trgOp, tableAlias = 'T') {
52
+ let srcOp;
53
+ if ((0, builder_1.isLogicalOperator)(filter))
54
+ srcOp = filter;
55
+ else {
56
+ srcOp = (0, builder_1.And)();
57
+ if (Array.isArray(filter))
58
+ srcOp.add(...filter);
59
+ else
60
+ srcOp.add(filter);
61
+ }
62
+ for (const item of srcOp._items) {
63
+ if ((0, builder_1.isLogicalOperator)(item)) {
64
+ const ctor = Object.getPrototypeOf(item).constructor;
65
+ const logOp = new ctor();
66
+ await prepareFilter(entityDef, item, logOp, tableAlias);
67
+ trgOp.add(logOp);
68
+ continue;
69
+ }
70
+ if ((0, builder_1.isCompOperator)(item)) {
71
+ if (typeof item._left === 'string') {
72
+ const itemPath = item._left.split('.');
73
+ const l = itemPath.length;
74
+ let pt;
75
+ let _curEntity = entityDef;
76
+ let _curAlias = tableAlias;
77
+ let _curPrefix = '';
78
+ let _curSuffix = '';
79
+ let subSelect;
80
+ for (let i = 0; i < l; i++) {
81
+ pt = itemPath[i];
82
+ const col = _curEntity.getElement(pt);
83
+ if (!col)
84
+ throw new Error(`Unknown property (${item._left}) defined in filter`);
85
+ // if last item on path
86
+ if (i === l - 1) {
87
+ if (!(0, orm_helper_1.isColumnElement)(col))
88
+ throw new Error(`Invalid column expression (${item._left}) defined in filter`);
89
+ const ctor = Object.getPrototypeOf(item).constructor;
90
+ trgOp.add(new ctor((0, builder_1.Field)(_curAlias + '.' + _curPrefix + col.fieldName + _curSuffix, col.dataType, col.isArray), item._right));
91
+ }
92
+ else {
93
+ if ((0, orm_helper_1.isColumnElement)(col))
94
+ throw new Error(`Invalid column (${item._left}) defined in filter`);
95
+ if ((0, orm_helper_1.isObjectElement)(col)) {
96
+ _curEntity = await col.resolveType();
97
+ _curPrefix = _curPrefix + (col.fieldNamePrefix || '');
98
+ _curSuffix = (col.fieldNameSuffix || '') + _curSuffix;
99
+ continue;
100
+ }
101
+ if (!(0, orm_helper_1.isAssociationElement)(col))
102
+ throw new Error(`Invalid column (${item._left}) defined in filter`);
103
+ let node;
104
+ _curEntity = await col.association.resolveTarget();
105
+ if (!subSelect) {
106
+ const keyCol = await col.association.resolveSourceProperty();
107
+ const targetCol = await col.association.resolveTargetProperty();
108
+ subSelect = (0, builder_1.Select)((0, builder_1.Raw)('1'))
109
+ .from(_curEntity.tableName + ' K');
110
+ subSelect.where((0, builder_1.Eq)((0, builder_1.Field)('K.' + targetCol.fieldName, targetCol.dataType, targetCol.isArray), (0, builder_1.Field)(tableAlias + '.' + keyCol.fieldName, keyCol.dataType, keyCol.isArray)));
111
+ trgOp.add((0, builder_1.Exists)(subSelect));
112
+ trgOp = subSelect._where;
113
+ if (col.association.conditions) {
114
+ await prepareFilter(_curEntity, col.association.conditions, trgOp, 'K');
115
+ }
116
+ node = col.association.next;
117
+ _curAlias = 'K';
118
+ }
119
+ else
120
+ node = col.association;
121
+ while (node) {
122
+ const targetEntity = await node.resolveTarget();
123
+ const sourceColumn = await node.resolveSourceProperty();
124
+ const targetColumn = await node.resolveTargetProperty();
125
+ const joinAlias = 'J' + (((subSelect?._joins?.length) || 0) + 1);
126
+ subSelect.join((0, builder_1.InnerJoin)(targetEntity.tableName + ' ' + joinAlias)
127
+ .on((0, builder_1.Eq)((0, builder_1.Field)(joinAlias + '.' + targetColumn.fieldName, targetColumn.dataType, targetColumn.isArray), (0, builder_1.Field)(_curAlias + '.' + sourceColumn.fieldName, sourceColumn.dataType, sourceColumn.isArray))));
128
+ _curEntity = targetEntity;
129
+ _curAlias = joinAlias;
130
+ node = node.next;
131
+ }
132
+ }
133
+ }
134
+ continue;
135
+ }
136
+ }
137
+ trgOp.add(item);
138
+ }
139
+ }
140
+ exports.prepareFilter = prepareFilter;
@@ -0,0 +1,11 @@
1
+ import { EntityModel } from '../model/entity-model';
2
+ import { Repository } from '../repository.class';
3
+ import { SqbConnection } from '../../client/SqbConnection';
4
+ export declare type CountCommandArgs = {
5
+ entity: EntityModel;
6
+ connection: SqbConnection;
7
+ } & Repository.CountOptions;
8
+ export declare class CountCommand {
9
+ protected constructor();
10
+ static execute(args: CountCommandArgs): Promise<number>;
11
+ }
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CountCommand = void 0;
4
+ const builder_1 = require("@sqb/builder");
5
+ const command_helper_1 = require("./command.helper");
6
+ class CountCommand {
7
+ // istanbul ignore next
8
+ constructor() {
9
+ throw new Error('This class is abstract');
10
+ }
11
+ static async execute(args) {
12
+ const { connection, entity, filter, params } = args;
13
+ let where;
14
+ if (filter) {
15
+ where = (0, builder_1.And)();
16
+ await (0, command_helper_1.prepareFilter)(entity, filter, where, 'T');
17
+ }
18
+ const query = (0, builder_1.Select)((0, builder_1.Count)()).from(entity.tableName + ' T');
19
+ if (where)
20
+ query.where(where);
21
+ // Execute query
22
+ const resp = await connection.execute(query, {
23
+ params,
24
+ objectRows: false,
25
+ cursor: false,
26
+ });
27
+ return (resp && resp.rows && resp.rows[0][0]) || 0;
28
+ }
29
+ }
30
+ exports.CountCommand = CountCommand;
@@ -0,0 +1,20 @@
1
+ import type { EntityModel } from '../model/entity-model';
2
+ import { SqbConnection } from '../../client/SqbConnection';
3
+ export declare type CreateCommandArgs = {
4
+ entity: EntityModel;
5
+ connection: SqbConnection;
6
+ values: any;
7
+ returning?: boolean;
8
+ };
9
+ declare type CreateCommandContext = {
10
+ entity: EntityModel;
11
+ queryParams: any;
12
+ queryValues: any;
13
+ colCount: number;
14
+ };
15
+ export declare class CreateCommand {
16
+ protected constructor();
17
+ static execute(args: CreateCommandArgs): Promise<any>;
18
+ protected static _prepareParams(ctx: CreateCommandContext, entity: EntityModel, values: any, prefix?: string, suffix?: string): Promise<void>;
19
+ }
20
+ export {};
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CreateCommand = void 0;
4
+ const builder_1 = require("@sqb/builder");
5
+ const orm_helper_1 = require("../util/orm.helper");
6
+ class CreateCommand {
7
+ // istanbul ignore next
8
+ constructor() {
9
+ throw new Error('This class is abstract');
10
+ }
11
+ static async execute(args) {
12
+ const { entity } = args;
13
+ const tableName = entity.tableName;
14
+ if (!tableName)
15
+ throw new Error(`${entity.ctor.name} is not decorated with @Entity decorator`);
16
+ // Create a context
17
+ const ctx = {
18
+ entity,
19
+ queryParams: {},
20
+ queryValues: {},
21
+ colCount: 0
22
+ };
23
+ // Prepare
24
+ await this._prepareParams(ctx, entity, args.values);
25
+ if (!ctx.colCount)
26
+ throw new Error('No element given to create new entity instance');
27
+ const query = (0, builder_1.Insert)(tableName, ctx.queryValues);
28
+ if (args.returning && entity.primaryIndex)
29
+ query.returning(...entity.getPrimaryIndexColumns().map(col => col.fieldName));
30
+ const qr = await args.connection.execute(query, {
31
+ params: ctx.queryParams,
32
+ objectRows: false,
33
+ cursor: false
34
+ });
35
+ if (args.returning && qr.fields && qr.rows?.length) {
36
+ const keyValues = {};
37
+ for (const f of qr.fields.values()) {
38
+ const el = entity.getColumnElementByFieldName(f.fieldName);
39
+ if (el)
40
+ keyValues[el.name] = qr.rows[0][f.index];
41
+ }
42
+ return keyValues;
43
+ }
44
+ }
45
+ static async _prepareParams(ctx, entity, values, prefix, suffix) {
46
+ let v;
47
+ prefix = prefix || '';
48
+ suffix = suffix || '';
49
+ for (const col of entity.elements.values()) {
50
+ v = values[col.name];
51
+ if ((0, orm_helper_1.isColumnElement)(col)) {
52
+ if (col.noInsert)
53
+ continue;
54
+ if (v == null && col.default !== undefined) {
55
+ v = typeof col.default === 'function' ?
56
+ col.default(values) : col.default;
57
+ }
58
+ if (typeof col.serialize === 'function')
59
+ v = col.serialize(v, col.name);
60
+ if (v == null) {
61
+ if (col.notNull && !col.autoGenerated)
62
+ throw new Error(`${entity.name}.${col.name} is required and can't be null`);
63
+ continue;
64
+ }
65
+ col.checkEnumValue(v);
66
+ const fieldName = prefix + col.fieldName + suffix;
67
+ const k = '$input_' + fieldName;
68
+ ctx.queryValues[fieldName] = (0, builder_1.Param)({
69
+ name: k,
70
+ dataType: col.dataType,
71
+ isArray: col.isArray
72
+ });
73
+ ctx.queryParams[k] = v;
74
+ ctx.colCount++;
75
+ }
76
+ else if (v != null && (0, orm_helper_1.isObjectElement)(col)) {
77
+ const type = await col.resolveType();
78
+ await this._prepareParams(ctx, type, v, col.fieldNamePrefix, col.fieldNameSuffix);
79
+ }
80
+ }
81
+ }
82
+ }
83
+ exports.CreateCommand = CreateCommand;
@@ -0,0 +1,11 @@
1
+ import { EntityModel } from '../model/entity-model';
2
+ import { Repository } from '../repository.class';
3
+ import { SqbConnection } from '../../client/SqbConnection';
4
+ export declare type DestroyCommandArgs = {
5
+ entity: EntityModel;
6
+ connection: SqbConnection;
7
+ } & Repository.DestroyOptions;
8
+ export declare class DestroyCommand {
9
+ protected constructor();
10
+ static execute(args: DestroyCommandArgs): Promise<number>;
11
+ }