@abedmurrar/objection 0.0.0-stage → 4.0.0-alpha.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 (190) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +69 -2
  3. package/lib/.eslintrc.json +8 -0
  4. package/lib/initialize.js +14 -0
  5. package/lib/model/AjvValidator.js +325 -0
  6. package/lib/model/Model.js +942 -0
  7. package/lib/model/ModifierNotFoundError.js +12 -0
  8. package/lib/model/NotFoundError.js +23 -0
  9. package/lib/model/RelationDoesNotExistError.js +14 -0
  10. package/lib/model/ValidationError.js +54 -0
  11. package/lib/model/Validator.js +26 -0
  12. package/lib/model/getModel.js +9 -0
  13. package/lib/model/graph/ModelGraph.js +80 -0
  14. package/lib/model/graph/ModelGraphBuilder.js +241 -0
  15. package/lib/model/graph/ModelGraphEdge.js +52 -0
  16. package/lib/model/graph/ModelGraphNode.js +240 -0
  17. package/lib/model/inheritModel.js +28 -0
  18. package/lib/model/modelBindKnex.js +83 -0
  19. package/lib/model/modelClone.js +121 -0
  20. package/lib/model/modelColPropMap.js +34 -0
  21. package/lib/model/modelId.js +62 -0
  22. package/lib/model/modelJsonAttributes.js +92 -0
  23. package/lib/model/modelParseRelations.js +82 -0
  24. package/lib/model/modelQueryProps.js +147 -0
  25. package/lib/model/modelSet.js +136 -0
  26. package/lib/model/modelTableMetadata.js +83 -0
  27. package/lib/model/modelToJson.js +187 -0
  28. package/lib/model/modelUtils.js +47 -0
  29. package/lib/model/modelValidate.js +48 -0
  30. package/lib/model/modelValues.js +126 -0
  31. package/lib/model/modelVisitor.js +41 -0
  32. package/lib/objection.js +114 -0
  33. package/lib/queryBuilder/FunctionBuilder.js +339 -0
  34. package/lib/queryBuilder/InternalOptions.js +29 -0
  35. package/lib/queryBuilder/JoinBuilder.js +157 -0
  36. package/lib/queryBuilder/QueryBuilder.js +1398 -0
  37. package/lib/queryBuilder/QueryBuilderBase.js +884 -0
  38. package/lib/queryBuilder/QueryBuilderContext.js +27 -0
  39. package/lib/queryBuilder/QueryBuilderContextBase.js +35 -0
  40. package/lib/queryBuilder/QueryBuilderOperationSupport.js +558 -0
  41. package/lib/queryBuilder/QueryBuilderUserContext.js +31 -0
  42. package/lib/queryBuilder/RawBuilder.js +93 -0
  43. package/lib/queryBuilder/ReferenceBuilder.js +284 -0
  44. package/lib/queryBuilder/RelationExpression.js +431 -0
  45. package/lib/queryBuilder/StaticHookArguments.js +134 -0
  46. package/lib/queryBuilder/ValueBuilder.js +127 -0
  47. package/lib/queryBuilder/expressions.js +151 -0
  48. package/lib/queryBuilder/functions/mysql.js +817 -0
  49. package/lib/queryBuilder/graph/GraphAction.js +69 -0
  50. package/lib/queryBuilder/graph/GraphData.js +14 -0
  51. package/lib/queryBuilder/graph/GraphFetcher.js +191 -0
  52. package/lib/queryBuilder/graph/GraphNodeDbExistence.js +184 -0
  53. package/lib/queryBuilder/graph/GraphOperation.js +27 -0
  54. package/lib/queryBuilder/graph/GraphOptions.js +207 -0
  55. package/lib/queryBuilder/graph/GraphUpsert.js +305 -0
  56. package/lib/queryBuilder/graph/delete/GraphDelete.js +20 -0
  57. package/lib/queryBuilder/graph/delete/GraphDeleteAction.js +74 -0
  58. package/lib/queryBuilder/graph/insert/GraphInsert.js +145 -0
  59. package/lib/queryBuilder/graph/insert/GraphInsertAction.js +225 -0
  60. package/lib/queryBuilder/graph/insert/JoinRowGraphInsertAction.js +92 -0
  61. package/lib/queryBuilder/graph/patch/GraphPatch.js +20 -0
  62. package/lib/queryBuilder/graph/patch/GraphPatchAction.js +258 -0
  63. package/lib/queryBuilder/graph/recursiveUpsert/GraphRecursiveUpsert.js +31 -0
  64. package/lib/queryBuilder/graph/recursiveUpsert/GraphRecursiveUpsertAction.js +126 -0
  65. package/lib/queryBuilder/join/JoinResultColumn.js +23 -0
  66. package/lib/queryBuilder/join/JoinResultParser.js +119 -0
  67. package/lib/queryBuilder/join/RelationJoiner.js +341 -0
  68. package/lib/queryBuilder/join/TableNode.js +163 -0
  69. package/lib/queryBuilder/join/TableTree.js +85 -0
  70. package/lib/queryBuilder/join/utils.js +25 -0
  71. package/lib/queryBuilder/operations/DelegateOperation.js +141 -0
  72. package/lib/queryBuilder/operations/DeleteOperation.js +51 -0
  73. package/lib/queryBuilder/operations/FindByIdOperation.js +37 -0
  74. package/lib/queryBuilder/operations/FindByIdsOperation.js +29 -0
  75. package/lib/queryBuilder/operations/FindOperation.js +164 -0
  76. package/lib/queryBuilder/operations/FirstOperation.js +27 -0
  77. package/lib/queryBuilder/operations/FromOperation.js +110 -0
  78. package/lib/queryBuilder/operations/InsertAndFetchOperation.js +49 -0
  79. package/lib/queryBuilder/operations/InsertGraphAndFetchOperation.js +45 -0
  80. package/lib/queryBuilder/operations/InsertGraphOperation.js +108 -0
  81. package/lib/queryBuilder/operations/InsertOperation.js +206 -0
  82. package/lib/queryBuilder/operations/InstanceDeleteOperation.js +46 -0
  83. package/lib/queryBuilder/operations/InstanceFindOperation.js +21 -0
  84. package/lib/queryBuilder/operations/InstanceInsertOperation.js +24 -0
  85. package/lib/queryBuilder/operations/InstanceUpdateOperation.js +59 -0
  86. package/lib/queryBuilder/operations/JoinRelatedOperation.js +103 -0
  87. package/lib/queryBuilder/operations/KnexOperation.js +14 -0
  88. package/lib/queryBuilder/operations/MergeOperation.js +56 -0
  89. package/lib/queryBuilder/operations/ObjectionToKnexConvertingOperation.js +192 -0
  90. package/lib/queryBuilder/operations/OnBuildKnexOperation.js +29 -0
  91. package/lib/queryBuilder/operations/OnBuildOperation.js +29 -0
  92. package/lib/queryBuilder/operations/OnErrorOperation.js +29 -0
  93. package/lib/queryBuilder/operations/QueryBuilderOperation.js +297 -0
  94. package/lib/queryBuilder/operations/RangeOperation.js +47 -0
  95. package/lib/queryBuilder/operations/RelateOperation.js +27 -0
  96. package/lib/queryBuilder/operations/ReturningOperation.js +30 -0
  97. package/lib/queryBuilder/operations/RunAfterOperation.js +29 -0
  98. package/lib/queryBuilder/operations/RunBeforeOperation.js +29 -0
  99. package/lib/queryBuilder/operations/UnrelateOperation.js +23 -0
  100. package/lib/queryBuilder/operations/UpdateAndFetchOperation.js +80 -0
  101. package/lib/queryBuilder/operations/UpdateOperation.js +155 -0
  102. package/lib/queryBuilder/operations/UpsertGraphAndFetchOperation.js +45 -0
  103. package/lib/queryBuilder/operations/UpsertGraphOperation.js +66 -0
  104. package/lib/queryBuilder/operations/WhereCompositeOperation.js +57 -0
  105. package/lib/queryBuilder/operations/WhereInOperation.js +48 -0
  106. package/lib/queryBuilder/operations/eager/EagerOperation.js +61 -0
  107. package/lib/queryBuilder/operations/eager/JoinEagerOperation.js +51 -0
  108. package/lib/queryBuilder/operations/eager/NaiveEagerOperation.js +13 -0
  109. package/lib/queryBuilder/operations/eager/WhereInEagerOperation.js +285 -0
  110. package/lib/queryBuilder/operations/jsonApi/WhereJsonHasOperation.js +36 -0
  111. package/lib/queryBuilder/operations/jsonApi/WhereJsonNotObjectOperation.js +53 -0
  112. package/lib/queryBuilder/operations/jsonApi/WhereJsonOperation.js +31 -0
  113. package/lib/queryBuilder/operations/jsonApi/WhereJsonOverlapsOperation.js +31 -0
  114. package/lib/queryBuilder/operations/jsonApi/mysqlJsonApi.js +167 -0
  115. package/lib/queryBuilder/operations/jsonApi/postgresJsonApi.js +164 -0
  116. package/lib/queryBuilder/operations/select/SelectOperation.js +66 -0
  117. package/lib/queryBuilder/operations/select/Selection.js +123 -0
  118. package/lib/queryBuilder/operations/whereInComposite/WhereInCompositeMsSqlOperation.js +117 -0
  119. package/lib/queryBuilder/operations/whereInComposite/WhereInCompositeOperation.js +100 -0
  120. package/lib/queryBuilder/operations/whereInComposite/WhereInCompositeSqliteOperation.js +104 -0
  121. package/lib/queryBuilder/parsers/jsonFieldExpressionParser.js +886 -0
  122. package/lib/queryBuilder/parsers/jsonFieldExpressionParser.pegjs +97 -0
  123. package/lib/queryBuilder/parsers/relationExpressionParser.js +1042 -0
  124. package/lib/queryBuilder/parsers/relationExpressionParser.pegjs +141 -0
  125. package/lib/queryBuilder/transformations/CompositeQueryTransformation.js +22 -0
  126. package/lib/queryBuilder/transformations/QueryTransformation.js +11 -0
  127. package/lib/queryBuilder/transformations/WrapMysqlModifySubqueryTransformation.js +71 -0
  128. package/lib/queryBuilder/transformations/index.js +15 -0
  129. package/lib/queryBuilder/whereScopes.js +227 -0
  130. package/lib/relations/Relation.js +401 -0
  131. package/lib/relations/RelationDeleteOperation.js +29 -0
  132. package/lib/relations/RelationFindOperation.js +149 -0
  133. package/lib/relations/RelationInsertOperation.js +33 -0
  134. package/lib/relations/RelationOwner.js +236 -0
  135. package/lib/relations/RelationProperty.js +247 -0
  136. package/lib/relations/RelationUpdateOperation.js +30 -0
  137. package/lib/relations/belongsToOne/BelongsToOneDeleteOperation.js +23 -0
  138. package/lib/relations/belongsToOne/BelongsToOneInsertOperation.js +44 -0
  139. package/lib/relations/belongsToOne/BelongsToOneRelateOperation.js +50 -0
  140. package/lib/relations/belongsToOne/BelongsToOneRelation.js +53 -0
  141. package/lib/relations/belongsToOne/BelongsToOneUnrelateOperation.js +61 -0
  142. package/lib/relations/hasMany/HasManyInsertOperation.js +61 -0
  143. package/lib/relations/hasMany/HasManyRelateOperation.js +64 -0
  144. package/lib/relations/hasMany/HasManyRelation.js +49 -0
  145. package/lib/relations/hasMany/HasManyUnrelateOperation.js +33 -0
  146. package/lib/relations/hasOne/HasOneRelation.js +13 -0
  147. package/lib/relations/hasOneThrough/HasOneThroughRelation.js +13 -0
  148. package/lib/relations/manyToMany/ManyToManyModifyMixin.js +105 -0
  149. package/lib/relations/manyToMany/ManyToManyRelation.js +507 -0
  150. package/lib/relations/manyToMany/ManyToManySqliteModifyMixin.js +36 -0
  151. package/lib/relations/manyToMany/delete/ManyToManyDeleteOperation.js +10 -0
  152. package/lib/relations/manyToMany/delete/ManyToManyDeleteOperationBase.js +26 -0
  153. package/lib/relations/manyToMany/delete/ManyToManyDeleteSqliteOperation.js +12 -0
  154. package/lib/relations/manyToMany/find/ManyToManyFindOperation.js +105 -0
  155. package/lib/relations/manyToMany/insert/ManyToManyInsertOperation.js +52 -0
  156. package/lib/relations/manyToMany/relate/ManyToManyRelateOperation.js +81 -0
  157. package/lib/relations/manyToMany/unrelate/ManyToManyUnrelateOperation.js +14 -0
  158. package/lib/relations/manyToMany/unrelate/ManyToManyUnrelateOperationBase.js +34 -0
  159. package/lib/relations/manyToMany/unrelate/ManyToManyUnrelateSqliteOperation.js +16 -0
  160. package/lib/relations/manyToMany/update/ManyToManyUpdateOperation.js +10 -0
  161. package/lib/relations/manyToMany/update/ManyToManyUpdateOperationBase.js +82 -0
  162. package/lib/relations/manyToMany/update/ManyToManyUpdateSqliteOperation.js +12 -0
  163. package/lib/transaction.js +96 -0
  164. package/lib/utils/assert.js +25 -0
  165. package/lib/utils/buildUtils.js +21 -0
  166. package/lib/utils/classUtils.js +13 -0
  167. package/lib/utils/clone.js +2329 -0
  168. package/lib/utils/createModifier.js +42 -0
  169. package/lib/utils/deprecate.js +15 -0
  170. package/lib/utils/identifierMapping.js +227 -0
  171. package/lib/utils/internalPropUtils.js +11 -0
  172. package/lib/utils/knexUtils.js +76 -0
  173. package/lib/utils/mixin.js +25 -0
  174. package/lib/utils/mysqlJsonPath.js +55 -0
  175. package/lib/utils/normalizeIds.js +144 -0
  176. package/lib/utils/objectUtils.js +416 -0
  177. package/lib/utils/parseFieldExpression.js +51 -0
  178. package/lib/utils/postgresJsonPath.js +110 -0
  179. package/lib/utils/promiseUtils/after.js +17 -0
  180. package/lib/utils/promiseUtils/afterReturn.js +17 -0
  181. package/lib/utils/promiseUtils/index.js +17 -0
  182. package/lib/utils/promiseUtils/isPromise.js +11 -0
  183. package/lib/utils/promiseUtils/map.js +110 -0
  184. package/lib/utils/promiseUtils/mapAfterAllReturn.js +29 -0
  185. package/lib/utils/promiseUtils/try.js +22 -0
  186. package/lib/utils/resolveModel.js +107 -0
  187. package/lib/utils/tmpColumnUtils.js +16 -0
  188. package/package.json +86 -4
  189. package/typings/objection/index.d.ts +4104 -0
  190. package/typings/objection/relation-expression.d.ts +237 -0
@@ -0,0 +1,42 @@
1
+ 'use strict';
2
+
3
+ const { asArray, isString, isFunction, isPlainObject } = require('./objectUtils');
4
+
5
+ function createModifier({ modelClass, modifier, modifiers }) {
6
+ const modelModifiers = modelClass ? modelClass.getModifiers() : {};
7
+
8
+ const modifierFunctions = asArray(modifier).map((modifier) => {
9
+ let modify = null;
10
+
11
+ if (isString(modifier)) {
12
+ modify = (modifiers && modifiers[modifier]) || modelModifiers[modifier];
13
+
14
+ // Modifiers can be pointers to other modifiers. Call this function recursively.
15
+ if (modify && !isFunction(modify)) {
16
+ return createModifier({ modelClass, modifier: modify, modifiers });
17
+ }
18
+ } else if (isFunction(modifier)) {
19
+ modify = modifier;
20
+ } else if (isPlainObject(modifier)) {
21
+ modify = (builder) => builder.where(modifier);
22
+ } else if (Array.isArray(modifier)) {
23
+ return createModifier({ modelClass, modifier, modifiers });
24
+ }
25
+
26
+ if (!modify) {
27
+ modify = (builder) => modelClass.modifierNotFound(builder, modifier);
28
+ }
29
+
30
+ return modify;
31
+ });
32
+
33
+ return (builder, ...args) => {
34
+ for (const modifier of modifierFunctions) {
35
+ modifier.call(builder, builder, ...args);
36
+ }
37
+ };
38
+ }
39
+
40
+ module.exports = {
41
+ createModifier,
42
+ };
@@ -0,0 +1,15 @@
1
+ 'use strict';
2
+
3
+ const LOGGED_DEPRECATIONS = new Set();
4
+
5
+ function deprecate(message) {
6
+ // Only log deprecation messages once.
7
+ if (!LOGGED_DEPRECATIONS.has(message)) {
8
+ LOGGED_DEPRECATIONS.add(message);
9
+ console.warn(message);
10
+ }
11
+ }
12
+
13
+ module.exports = {
14
+ deprecate,
15
+ };
@@ -0,0 +1,227 @@
1
+ 'use strict';
2
+
3
+ const { isObject } = require('./objectUtils');
4
+
5
+ // Super fast memoize for single argument functions.
6
+ function memoize(func) {
7
+ const cache = new Map();
8
+
9
+ return (input) => {
10
+ let output = cache.get(input);
11
+
12
+ if (output === undefined) {
13
+ output = func(input);
14
+ cache.set(input, output);
15
+ }
16
+
17
+ return output;
18
+ };
19
+ }
20
+
21
+ // camelCase to snake_case converter that also works with non-ascii characters
22
+ // This is needed especially so that aliases containing the `:` character,
23
+ // objection uses internally, work.
24
+ function snakeCase(
25
+ str,
26
+ {
27
+ upperCase = false,
28
+ underscoreBeforeDigits = false,
29
+ underscoreBetweenUppercaseLetters = false,
30
+ } = {},
31
+ ) {
32
+ if (str.length === 0) {
33
+ return str;
34
+ }
35
+
36
+ const upper = str.toUpperCase();
37
+ const lower = str.toLowerCase();
38
+
39
+ let out = lower[0];
40
+
41
+ for (let i = 1, l = str.length; i < l; ++i) {
42
+ const char = str[i];
43
+ const prevChar = str[i - 1];
44
+
45
+ const upperChar = upper[i];
46
+ const prevUpperChar = upper[i - 1];
47
+
48
+ const lowerChar = lower[i];
49
+ const prevLowerChar = lower[i - 1];
50
+
51
+ // If underScoreBeforeDigits is true then, well, insert an underscore
52
+ // before digits :). Only the first digit gets an underscore if
53
+ // there are multiple.
54
+ if (underscoreBeforeDigits && isDigit(char) && !isDigit(prevChar)) {
55
+ out += '_' + char;
56
+ continue;
57
+ }
58
+
59
+ // Test if `char` is an upper-case character and that the character
60
+ // actually has different upper and lower case versions.
61
+ if (char === upperChar && upperChar !== lowerChar) {
62
+ const prevCharacterIsUppercase =
63
+ prevChar === prevUpperChar && prevUpperChar !== prevLowerChar;
64
+
65
+ // If underscoreBetweenUppercaseLetters is true, we always place an underscore
66
+ // before consecutive uppercase letters (e.g. "fooBAR" becomes "foo_b_a_r").
67
+ // Otherwise, we don't (e.g. "fooBAR" becomes "foo_bar").
68
+ if (underscoreBetweenUppercaseLetters || !prevCharacterIsUppercase) {
69
+ out += '_' + lowerChar;
70
+ } else {
71
+ out += lowerChar;
72
+ }
73
+ } else {
74
+ out += char;
75
+ }
76
+ }
77
+
78
+ if (upperCase) {
79
+ return out.toUpperCase();
80
+ } else {
81
+ return out;
82
+ }
83
+ }
84
+
85
+ // snake_case to camelCase converter that simply reverses
86
+ // the actions done by `snakeCase` function.
87
+ function camelCase(str, { upperCase = false } = {}) {
88
+ if (str.length === 0) {
89
+ return str;
90
+ }
91
+
92
+ if (upperCase && isAllUpperCaseSnakeCase(str)) {
93
+ // Only convert to lower case if the string is all upper
94
+ // case snake_case. This allowes camelCase strings to go
95
+ // through without changing.
96
+ str = str.toLowerCase();
97
+ }
98
+
99
+ let out = str[0];
100
+
101
+ for (let i = 1, l = str.length; i < l; ++i) {
102
+ const char = str[i];
103
+ const prevChar = str[i - 1];
104
+
105
+ if (char !== '_') {
106
+ if (prevChar === '_') {
107
+ out += char.toUpperCase();
108
+ } else {
109
+ out += char;
110
+ }
111
+ }
112
+ }
113
+
114
+ return out;
115
+ }
116
+
117
+ function isAllUpperCaseSnakeCase(str) {
118
+ for (let i = 1, l = str.length; i < l; ++i) {
119
+ const char = str[i];
120
+
121
+ if (char !== '_' && char !== char.toUpperCase()) {
122
+ return false;
123
+ }
124
+ }
125
+
126
+ return true;
127
+ }
128
+
129
+ function isDigit(char) {
130
+ return char >= '0' && char <= '9';
131
+ }
132
+
133
+ // Returns a function that splits the inputs string into pieces using `separator`,
134
+ // only calls `mapper` for the last part and concatenates the string back together.
135
+ // If no separators are found, `mapper` is called for the entire string.
136
+ function mapLastPart(mapper, separator) {
137
+ return (str) => {
138
+ if (!str) return str;
139
+ const idx = str.lastIndexOf(separator);
140
+ const mapped = mapper(str.slice(idx + separator.length));
141
+ return str.slice(0, idx + separator.length) + mapped;
142
+ };
143
+ }
144
+
145
+ // Returns a function that takes an object as an input and maps the object's keys
146
+ // using `mapper`. If the input is not an object, the input is returned unchanged.
147
+ function keyMapper(mapper) {
148
+ return (obj) => {
149
+ if (!isObject(obj) || Array.isArray(obj)) {
150
+ return obj;
151
+ }
152
+
153
+ const keys = Object.keys(obj);
154
+ const out = {};
155
+
156
+ for (let i = 0, l = keys.length; i < l; ++i) {
157
+ const key = keys[i];
158
+ out[mapper(key)] = obj[key];
159
+ }
160
+
161
+ return out;
162
+ };
163
+ }
164
+
165
+ function snakeCaseMappers(opt = {}) {
166
+ return {
167
+ parse: keyMapper(memoize((str) => camelCase(str, opt))),
168
+ format: keyMapper(memoize((str) => snakeCase(str, opt))),
169
+ };
170
+ }
171
+
172
+ function knexIdentifierMappers({ parse, format, idSeparator = ':' } = {}) {
173
+ const formatId = memoize(mapLastPart(format, idSeparator));
174
+ const parseId = memoize(mapLastPart(parse, idSeparator));
175
+ const parseKeys = keyMapper(parseId);
176
+
177
+ return {
178
+ wrapIdentifier(identifier, origWrap) {
179
+ return origWrap(formatId(identifier));
180
+ },
181
+
182
+ postProcessResponse(result) {
183
+ if (Array.isArray(result)) {
184
+ const output = new Array(result.length);
185
+
186
+ for (let i = 0, l = result.length; i < l; ++i) {
187
+ output[i] = parseKeys(result[i]);
188
+ }
189
+
190
+ return output;
191
+ } else {
192
+ return parseKeys(result);
193
+ }
194
+ },
195
+ };
196
+ }
197
+
198
+ function knexSnakeCaseMappers(opt = {}) {
199
+ return knexIdentifierMappers({
200
+ parse: (str) => camelCase(str, opt),
201
+ format: (str) => snakeCase(str, opt),
202
+ });
203
+ }
204
+
205
+ function knexIdentifierMapping(colToProp) {
206
+ const propToCol = Object.keys(colToProp).reduce((propToCol, column) => {
207
+ propToCol[colToProp[column]] = column;
208
+ return propToCol;
209
+ }, {});
210
+
211
+ return knexIdentifierMappers({
212
+ parse: (column) => colToProp[column] || column,
213
+ format: (prop) => propToCol[prop] || prop,
214
+ });
215
+ }
216
+
217
+ module.exports = {
218
+ snakeCase,
219
+ camelCase,
220
+ snakeCaseMappers,
221
+ knexSnakeCaseMappers,
222
+ knexIdentifierMappers,
223
+ knexIdentifierMapping,
224
+
225
+ camelCaseKeys: keyMapper(memoize(camelCase)),
226
+ snakeCaseKeys: keyMapper(memoize(snakeCase)),
227
+ };
@@ -0,0 +1,11 @@
1
+ 'use strict';
2
+
3
+ const INTERNAL_PROP_PREFIX = '$';
4
+
5
+ function isInternalProp(propName) {
6
+ return propName[0] === INTERNAL_PROP_PREFIX;
7
+ }
8
+
9
+ module.exports = {
10
+ isInternalProp,
11
+ };
@@ -0,0 +1,76 @@
1
+ 'use strict';
2
+
3
+ const { isObject, isFunction } = require('../utils/objectUtils');
4
+
5
+ function getDialect(knex) {
6
+ const type = typeof knex;
7
+
8
+ return (
9
+ (knex !== null &&
10
+ (type === 'object' || type === 'function') &&
11
+ knex.client &&
12
+ knex.client.dialect) ||
13
+ null
14
+ );
15
+ }
16
+
17
+ function isPostgres(knex) {
18
+ return getDialect(knex) === 'postgresql';
19
+ }
20
+
21
+ function isOracle(knex) {
22
+ const dialect = getDialect(knex);
23
+ return dialect === 'oracle' || dialect === 'oracledb';
24
+ }
25
+
26
+ function isMySql(knex) {
27
+ const dialect = getDialect(knex);
28
+ return dialect === 'mysql' || dialect === 'mysql2';
29
+ }
30
+
31
+ function isSqlite(knex) {
32
+ return getDialect(knex) === 'sqlite3';
33
+ }
34
+
35
+ function isMsSql(knex) {
36
+ return getDialect(knex) === 'mssql';
37
+ }
38
+
39
+ function isKnexQueryBuilder(value) {
40
+ return (
41
+ hasConstructor(value) &&
42
+ isFunction(value.select) &&
43
+ isFunction(value.column) &&
44
+ value.select === value.column &&
45
+ 'client' in value
46
+ );
47
+ }
48
+
49
+ function isKnexJoinBuilder(value) {
50
+ return hasConstructor(value) && value.grouping === 'join' && 'joinType' in value;
51
+ }
52
+
53
+ function isKnexRaw(value) {
54
+ return hasConstructor(value) && value.isRawInstance && 'client' in value;
55
+ }
56
+
57
+ function isKnexTransaction(knex) {
58
+ return !!getDialect(knex) && isFunction(knex.commit) && isFunction(knex.rollback);
59
+ }
60
+
61
+ function hasConstructor(value) {
62
+ return isObject(value) && isFunction(value.constructor);
63
+ }
64
+
65
+ module.exports = {
66
+ getDialect,
67
+ isPostgres,
68
+ isMySql,
69
+ isSqlite,
70
+ isMsSql,
71
+ isOracle,
72
+ isKnexQueryBuilder,
73
+ isKnexJoinBuilder,
74
+ isKnexRaw,
75
+ isKnexTransaction,
76
+ };
@@ -0,0 +1,25 @@
1
+ 'use strict';
2
+
3
+ const { flatten } = require('./objectUtils');
4
+
5
+ function mixin() {
6
+ const args = flatten(arguments);
7
+ const mixins = args.slice(1);
8
+
9
+ return mixins.reduce((Class, mixinFunc) => {
10
+ return mixinFunc(Class);
11
+ }, args[0]);
12
+ }
13
+
14
+ function compose() {
15
+ const mixins = flatten(arguments);
16
+
17
+ return function (Class) {
18
+ return mixin(Class, mixins);
19
+ };
20
+ }
21
+
22
+ module.exports = {
23
+ compose,
24
+ mixin,
25
+ };
@@ -0,0 +1,55 @@
1
+ 'use strict';
2
+
3
+ // SQL types of `ReferenceBuilder` casts that MySQL's `CAST()` calls differently.
4
+ // `CAST(x AS integer)` for example is a syntax error on MySQL.
5
+ const MYSQL_CAST_TYPES = {
6
+ text: 'CHAR',
7
+ varchar: 'CHAR',
8
+ integer: 'SIGNED',
9
+ int: 'SIGNED',
10
+ smallint: 'SIGNED',
11
+ bigint: 'SIGNED',
12
+ float: 'FLOAT',
13
+ real: 'DOUBLE',
14
+ double: 'DOUBLE',
15
+ 'double precision': 'DOUBLE',
16
+ decimal: 'DECIMAL(65,30)',
17
+ numeric: 'DECIMAL(65,30)',
18
+ json: 'JSON',
19
+ jsonb: 'JSON',
20
+ };
21
+
22
+ /**
23
+ * Converts the `access` part of a parsed field expression into a MySQL JSON
24
+ * path like `$."a"[1]."b.c"`. Keys are always quoted, so they can contain any
25
+ * characters. The path must be passed to MySQL as a binding.
26
+ */
27
+ function toMySqlJsonPath(access) {
28
+ return (
29
+ '$' +
30
+ access
31
+ .map((it) => {
32
+ if (it.type === 'array' && Number.isInteger(it.ref)) {
33
+ return `[${it.ref}]`;
34
+ } else {
35
+ return `.${JSON.stringify(String(it.ref))}`;
36
+ }
37
+ })
38
+ .join('')
39
+ );
40
+ }
41
+
42
+ function toMySqlCastType(sqlType) {
43
+ return MYSQL_CAST_TYPES[sqlType.toLowerCase()] || sqlType;
44
+ }
45
+
46
+ function isBooleanType(sqlType) {
47
+ const type = sqlType.toLowerCase();
48
+ return type === 'boolean' || type === 'bool';
49
+ }
50
+
51
+ module.exports = {
52
+ toMySqlJsonPath,
53
+ toMySqlCastType,
54
+ isBooleanType,
55
+ };
@@ -0,0 +1,144 @@
1
+ 'use strict';
2
+
3
+ const { isObject } = require('../utils/objectUtils');
4
+
5
+ // ids is of type RelationProperty.
6
+ function normalizeIds(ids, prop, opt) {
7
+ opt = opt || {};
8
+
9
+ let isComposite = prop.size > 1;
10
+ let ret;
11
+
12
+ if (isComposite) {
13
+ // For composite ids these are okay:
14
+ //
15
+ // 1. [1, 'foo', 4]
16
+ // 2. {a: 1, b: 'foo', c: 4}
17
+ // 3. [[1, 'foo', 4], [4, 'bar', 1]]
18
+ // 4. [{a: 1, b: 'foo', c: 4}, {a: 4, b: 'bar', c: 1}]
19
+ //
20
+ if (Array.isArray(ids)) {
21
+ if (Array.isArray(ids[0])) {
22
+ ret = new Array(ids.length);
23
+
24
+ // 3.
25
+ for (let i = 0, l = ids.length; i < l; ++i) {
26
+ ret[i] = convertIdArrayToObject(ids[i], prop);
27
+ }
28
+ } else if (isObject(ids[0])) {
29
+ ret = new Array(ids.length);
30
+
31
+ // 4.
32
+ for (let i = 0, l = ids.length; i < l; ++i) {
33
+ ret[i] = ensureObject(ids[i], prop);
34
+ }
35
+ } else {
36
+ // 1.
37
+ ret = [convertIdArrayToObject(ids, prop)];
38
+ }
39
+ } else if (isObject(ids)) {
40
+ // 2.
41
+ ret = [ids];
42
+ } else {
43
+ throw new Error(`invalid composite key ${JSON.stringify(ids)}`);
44
+ }
45
+ } else {
46
+ // For non-composite ids, these are okay:
47
+ //
48
+ // 1. 1
49
+ // 2. {id: 1}
50
+ // 3. [1, 'foo', 4]
51
+ // 4. [{id: 1}, {id: 'foo'}, {id: 4}]
52
+ //
53
+ if (Array.isArray(ids)) {
54
+ if (isObject(ids[0])) {
55
+ ret = new Array(ids.length);
56
+
57
+ // 4.
58
+ for (let i = 0, l = ids.length; i < l; ++i) {
59
+ ret[i] = ensureObject(ids[i]);
60
+ }
61
+ } else {
62
+ ret = new Array(ids.length);
63
+
64
+ // 3.
65
+ for (let i = 0, l = ids.length; i < l; ++i) {
66
+ ret[i] = {};
67
+ prop.setProp(ret[i], 0, ids[i]);
68
+ }
69
+ }
70
+ } else if (isObject(ids)) {
71
+ // 2.
72
+ ret = [ids];
73
+ } else {
74
+ // 1.
75
+ const obj = {};
76
+ prop.setProp(obj, 0, ids);
77
+ ret = [obj];
78
+ }
79
+ }
80
+
81
+ checkProperties(ret, prop);
82
+
83
+ if (opt.arrayOutput) {
84
+ return normalizedToArray(ret, prop);
85
+ } else {
86
+ return ret;
87
+ }
88
+ }
89
+
90
+ function convertIdArrayToObject(ids, prop) {
91
+ if (!Array.isArray(ids)) {
92
+ throw new Error(`invalid composite key ${JSON.stringify(ids)}`);
93
+ }
94
+
95
+ if (ids.length != prop.size) {
96
+ throw new Error(`composite identifier ${JSON.stringify(ids)} should have ${prop.size} values`);
97
+ }
98
+
99
+ const obj = {};
100
+
101
+ for (let i = 0; i < ids.length; ++i) {
102
+ prop.setProp(obj, i, ids[i]);
103
+ }
104
+
105
+ return obj;
106
+ }
107
+
108
+ function ensureObject(ids) {
109
+ if (isObject(ids)) {
110
+ return ids;
111
+ } else {
112
+ throw new Error(`invalid composite key ${JSON.stringify(ids)}`);
113
+ }
114
+ }
115
+
116
+ function checkProperties(ret, prop) {
117
+ for (let i = 0, l = ret.length; i < l; ++i) {
118
+ const obj = ret[i];
119
+
120
+ for (let j = 0, lp = prop.size; j < lp; ++j) {
121
+ const val = prop.getProp(obj, j);
122
+
123
+ if (typeof val === 'undefined') {
124
+ throw new Error(
125
+ `expected id ${JSON.stringify(obj)} to have property ${prop.propDescription(j)}`,
126
+ );
127
+ }
128
+ }
129
+ }
130
+ }
131
+
132
+ function normalizedToArray(ret, prop) {
133
+ const arr = new Array(ret.length);
134
+
135
+ for (let i = 0, l = ret.length; i < l; ++i) {
136
+ arr[i] = prop.getProps(ret[i]);
137
+ }
138
+
139
+ return arr;
140
+ }
141
+
142
+ module.exports = {
143
+ normalizeIds,
144
+ };