fib-orm 1.4.2 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (295) hide show
  1. package/License +1 -1
  2. package/README.md +53 -0
  3. package/lib/cli/commands/ddlFrom.d.ts +2 -0
  4. package/lib/cli/commands/ddlFrom.js +75 -0
  5. package/lib/cli/commands/dumpModel.d.ts +2 -0
  6. package/lib/cli/commands/dumpModel.js +107 -0
  7. package/lib/cli/commands/escape.d.ts +2 -0
  8. package/lib/cli/commands/escape.js +69 -0
  9. package/lib/cli/commands/spinner.d.ts +2 -0
  10. package/lib/cli/commands/spinner.js +37 -0
  11. package/lib/cli/commands/upgrade.d.ts +2 -0
  12. package/lib/cli/commands/upgrade.js +66 -0
  13. package/lib/cli/helpers/ddl.d.ts +17 -0
  14. package/lib/cli/helpers/ddl.js +55 -0
  15. package/lib/cli/helpers/package.d.ts +25 -0
  16. package/lib/cli/helpers/package.js +56 -0
  17. package/lib/cli/index.d.ts +2 -0
  18. package/lib/cli/index.js +19 -0
  19. package/lib/codepoints-map.json +762 -0
  20. package/lib/db-driver/Typo.d.ts +111 -0
  21. package/lib/db-driver/Typo.js +2 -0
  22. package/lib/db-driver/built-ins/base.class.d.ts +91 -0
  23. package/lib/db-driver/built-ins/base.class.js +187 -0
  24. package/lib/db-driver/built-ins/driver-dm.d.ts +17 -0
  25. package/lib/db-driver/built-ins/driver-dm.js +54 -0
  26. package/lib/db-driver/built-ins/driver-mongodb.d.ts +23 -0
  27. package/lib/db-driver/built-ins/driver-mongodb.js +47 -0
  28. package/lib/db-driver/built-ins/driver-mysql.d.ts +17 -0
  29. package/lib/db-driver/built-ins/driver-mysql.js +38 -0
  30. package/lib/db-driver/built-ins/driver-postgresql.d.ts +21 -0
  31. package/lib/db-driver/built-ins/driver-postgresql.js +77 -0
  32. package/lib/db-driver/built-ins/driver-redis.d.ts +11 -0
  33. package/lib/db-driver/built-ins/driver-redis.js +36 -0
  34. package/lib/db-driver/built-ins/driver-sqlite.d.ts +16 -0
  35. package/lib/db-driver/built-ins/driver-sqlite.js +35 -0
  36. package/lib/db-driver/index.d.ts +3 -0
  37. package/lib/db-driver/index.js +5 -0
  38. package/lib/db-driver/utils.d.ts +14 -0
  39. package/lib/db-driver/utils.js +187 -0
  40. package/lib/knex/deps/tarn/dist/PendingOperation.d.ts +12 -0
  41. package/lib/knex/deps/tarn/dist/PendingOperation.js +48 -0
  42. package/lib/knex/deps/tarn/dist/Pool.d.ts +97 -0
  43. package/lib/knex/deps/tarn/dist/Pool.js +516 -0
  44. package/lib/knex/deps/tarn/dist/PromiseInspection.d.ts +16 -0
  45. package/lib/knex/deps/tarn/dist/PromiseInspection.js +21 -0
  46. package/lib/knex/deps/tarn/dist/Resource.d.ts +9 -0
  47. package/lib/knex/deps/tarn/dist/Resource.js +19 -0
  48. package/lib/knex/deps/tarn/dist/TimeoutError.d.ts +2 -0
  49. package/lib/knex/deps/tarn/dist/TimeoutError.js +5 -0
  50. package/lib/knex/deps/tarn/dist/tarn.d.ts +3 -0
  51. package/lib/knex/deps/tarn/dist/tarn.js +10 -0
  52. package/lib/knex/deps/tarn/dist/utils.d.ts +14 -0
  53. package/lib/knex/deps/tarn/dist/utils.js +60 -0
  54. package/lib/knex/knex.d.ts +2 -0
  55. package/lib/knex/knex.js +4 -0
  56. package/lib/knex/sandbox.d.ts +4 -0
  57. package/lib/knex/sandbox.js +23 -0
  58. package/lib/orm/Adapters.d.ts +3 -0
  59. package/lib/orm/Adapters.js +44 -0
  60. package/lib/orm/AggregateFunctions.d.ts +3 -0
  61. package/lib/orm/AggregateFunctions.js +177 -0
  62. package/lib/orm/Associations/Extend.d.ts +22 -0
  63. package/lib/orm/Associations/Extend.js +274 -0
  64. package/lib/orm/Associations/Many.d.ts +16 -0
  65. package/lib/orm/Associations/Many.js +569 -0
  66. package/lib/orm/Associations/One.d.ts +16 -0
  67. package/lib/orm/Associations/One.js +310 -0
  68. package/lib/orm/Associations/_utils.d.ts +14 -0
  69. package/lib/orm/Associations/_utils.js +53 -0
  70. package/lib/orm/ChainFind.d.ts +3 -0
  71. package/lib/orm/ChainFind.js +328 -0
  72. package/lib/orm/ChainInstance.d.ts +6 -0
  73. package/lib/orm/ChainInstance.js +74 -0
  74. package/lib/orm/Debug.d.ts +2 -0
  75. package/lib/orm/Debug.js +17 -0
  76. package/lib/orm/Drivers/DB/base.d.ts +2 -0
  77. package/lib/orm/Drivers/DB/base.js +4 -0
  78. package/lib/orm/Drivers/DB/dm.d.ts +9 -0
  79. package/lib/orm/Drivers/DB/dm.js +24 -0
  80. package/lib/orm/Drivers/DB/mysql.d.ts +9 -0
  81. package/lib/orm/Drivers/DB/mysql.js +24 -0
  82. package/lib/orm/Drivers/DB/postgres.d.ts +9 -0
  83. package/lib/orm/Drivers/DB/postgres.js +23 -0
  84. package/lib/orm/Drivers/DB/sqlite3.d.ts +14 -0
  85. package/lib/orm/Drivers/DB/sqlite3.js +40 -0
  86. package/lib/orm/Drivers/DML/_ddl-sql.d.ts +3 -0
  87. package/lib/orm/Drivers/DML/_ddl-sql.js +52 -0
  88. package/lib/orm/Drivers/DML/_dml-helpers.d.ts +19 -0
  89. package/lib/orm/Drivers/DML/_dml-helpers.js +51 -0
  90. package/lib/orm/Drivers/DML/_shared.d.ts +9 -0
  91. package/lib/orm/Drivers/DML/_shared.js +39 -0
  92. package/lib/orm/Drivers/DML/_utils.d.ts +8 -0
  93. package/lib/orm/Drivers/DML/_utils.js +67 -0
  94. package/lib/orm/Drivers/DML/constants.d.ts +3 -0
  95. package/lib/orm/Drivers/DML/constants.js +3 -0
  96. package/lib/orm/Drivers/DML/dm.d.ts +2 -0
  97. package/lib/orm/Drivers/DML/dm.js +294 -0
  98. package/lib/orm/Drivers/DML/index.d.ts +4 -0
  99. package/lib/orm/Drivers/DML/index.js +7 -0
  100. package/lib/orm/Drivers/DML/mysql.d.ts +2 -0
  101. package/lib/orm/Drivers/DML/mysql.js +252 -0
  102. package/lib/orm/Drivers/DML/postgres.d.ts +2 -0
  103. package/lib/orm/Drivers/DML/postgres.js +277 -0
  104. package/lib/orm/Drivers/DML/sqlite.d.ts +2 -0
  105. package/lib/orm/Drivers/DML/sqlite.js +267 -0
  106. package/lib/orm/Error.d.ts +11 -0
  107. package/lib/orm/Error.js +41 -0
  108. package/lib/orm/Helpers.d.ts +35 -0
  109. package/lib/orm/Helpers.js +234 -0
  110. package/lib/orm/Hook.d.ts +13 -0
  111. package/lib/orm/Hook.js +100 -0
  112. package/lib/orm/Instance.d.ts +2 -0
  113. package/lib/orm/Instance.js +698 -0
  114. package/lib/orm/LazyLoad.d.ts +4 -0
  115. package/lib/orm/LazyLoad.js +76 -0
  116. package/lib/orm/Model.d.ts +6 -0
  117. package/lib/orm/Model.js +974 -0
  118. package/lib/orm/ORM.d.ts +37 -0
  119. package/lib/orm/ORM.js +242 -0
  120. package/lib/orm/Patch/fib-cache.d.ts +39 -0
  121. package/lib/orm/Patch/fib-cache.js +2 -0
  122. package/lib/orm/Patch/plugin.d.ts +4 -0
  123. package/lib/orm/Patch/plugin.js +14 -0
  124. package/lib/orm/Property.d.ts +9 -0
  125. package/lib/orm/Property.js +71 -0
  126. package/lib/orm/Settings.d.ts +42 -0
  127. package/lib/orm/Settings.js +120 -0
  128. package/lib/orm/Singleton.d.ts +5 -0
  129. package/lib/orm/Singleton.js +73 -0
  130. package/lib/orm/Typo/Adapter.d.ts +5 -0
  131. package/lib/orm/Typo/Adapter.js +2 -0
  132. package/lib/orm/Typo/DMLDriver.d.ts +209 -0
  133. package/lib/orm/Typo/DMLDriver.js +2 -0
  134. package/lib/orm/Typo/Db.d.ts +35 -0
  135. package/lib/orm/Typo/Db.js +2 -0
  136. package/lib/orm/Typo/Error.d.ts +29 -0
  137. package/lib/orm/Typo/Error.js +2 -0
  138. package/lib/orm/Typo/ORM.d.ts +231 -0
  139. package/lib/orm/Typo/ORM.js +4 -0
  140. package/lib/orm/Typo/Validators.d.ts +31 -0
  141. package/lib/orm/Typo/Validators.js +3 -0
  142. package/lib/orm/Typo/_common.d.ts +37 -0
  143. package/lib/orm/Typo/_common.js +2 -0
  144. package/lib/orm/Typo/assoc.d.ts +221 -0
  145. package/lib/orm/Typo/assoc.js +2 -0
  146. package/lib/orm/Typo/hook.d.ts +42 -0
  147. package/lib/orm/Typo/hook.js +2 -0
  148. package/lib/orm/Typo/instance.d.ts +156 -0
  149. package/lib/orm/Typo/instance.js +2 -0
  150. package/lib/orm/Typo/model.d.ts +311 -0
  151. package/lib/orm/Typo/model.js +7 -0
  152. package/lib/orm/Typo/patch.d.ts +31 -0
  153. package/lib/orm/Typo/patch.js +2 -0
  154. package/lib/orm/Typo/property.d.ts +57 -0
  155. package/lib/orm/Typo/property.js +2 -0
  156. package/lib/orm/Typo/query.d.ts +216 -0
  157. package/lib/orm/Typo/query.js +2 -0
  158. package/lib/orm/Typo/settings.d.ts +35 -0
  159. package/lib/orm/Typo/settings.js +6 -0
  160. package/lib/orm/Typo/synchronous.d.ts +47 -0
  161. package/lib/orm/Typo/synchronous.js +2 -0
  162. package/lib/orm/Utilities.d.ts +178 -0
  163. package/lib/orm/Utilities.js +975 -0
  164. package/lib/orm/Validators.d.ts +33 -0
  165. package/lib/orm/Validators.js +101 -0
  166. package/lib/orm/Where/common.d.ts +1 -0
  167. package/lib/orm/Where/common.js +7 -0
  168. package/lib/orm/Where/filterDate.d.ts +11 -0
  169. package/lib/orm/Where/filterDate.js +58 -0
  170. package/lib/orm/index.d.ts +67 -0
  171. package/lib/orm/index.js +158 -0
  172. package/lib/orm-core/callback.d.ts +12 -0
  173. package/lib/orm-core/callback.js +2 -0
  174. package/lib/orm-core/dialect.d.ts +80 -0
  175. package/lib/orm-core/dialect.js +2 -0
  176. package/lib/orm-core/error.d.ts +16 -0
  177. package/lib/orm-core/error.js +29 -0
  178. package/lib/orm-core/index.d.ts +6 -0
  179. package/lib/orm-core/index.js +7 -0
  180. package/lib/orm-core/sync.d.ts +12 -0
  181. package/lib/orm-core/sync.js +2 -0
  182. package/lib/orm-core/utils.d.ts +1 -0
  183. package/lib/orm-core/utils.js +6 -0
  184. package/lib/orm-property/Property.d.ts +78 -0
  185. package/lib/orm-property/Property.js +2 -0
  186. package/lib/orm-property/Utils.d.ts +9 -0
  187. package/lib/orm-property/Utils.js +13 -0
  188. package/lib/orm-property/customTypes.d.ts +2 -0
  189. package/lib/orm-property/customTypes.js +13 -0
  190. package/lib/orm-property/index.d.ts +10 -0
  191. package/lib/orm-property/index.js +23 -0
  192. package/lib/orm-property/transformer.d.ts +5 -0
  193. package/lib/orm-property/transformer.js +10 -0
  194. package/lib/orm-property/transformers/dm.d.ts +29 -0
  195. package/lib/orm-property/transformers/dm.js +238 -0
  196. package/lib/orm-property/transformers/index.d.ts +4 -0
  197. package/lib/orm-property/transformers/index.js +6 -0
  198. package/lib/orm-property/transformers/mysql.d.ts +101 -0
  199. package/lib/orm-property/transformers/mysql.js +262 -0
  200. package/lib/orm-property/transformers/postgresql.d.ts +54 -0
  201. package/lib/orm-property/transformers/postgresql.js +190 -0
  202. package/lib/orm-property/transformers/sqlite.d.ts +19 -0
  203. package/lib/orm-property/transformers/sqlite.js +172 -0
  204. package/lib/sql-ddl-sync/Dialects/dm.d.ts +39 -0
  205. package/lib/sql-ddl-sync/Dialects/dm.js +297 -0
  206. package/lib/sql-ddl-sync/Dialects/index.d.ts +6 -0
  207. package/lib/sql-ddl-sync/Dialects/index.js +8 -0
  208. package/lib/sql-ddl-sync/Dialects/mysql.d.ts +38 -0
  209. package/lib/sql-ddl-sync/Dialects/mysql.js +241 -0
  210. package/lib/sql-ddl-sync/Dialects/postgresql.d.ts +39 -0
  211. package/lib/sql-ddl-sync/Dialects/postgresql.js +287 -0
  212. package/lib/sql-ddl-sync/Dialects/sqlite.d.ts +43 -0
  213. package/lib/sql-ddl-sync/Dialects/sqlite.js +257 -0
  214. package/lib/sql-ddl-sync/SQL.d.ts +12 -0
  215. package/lib/sql-ddl-sync/SQL.js +108 -0
  216. package/lib/sql-ddl-sync/Typo/Collection.d.ts +13 -0
  217. package/lib/sql-ddl-sync/Typo/Collection.js +2 -0
  218. package/lib/sql-ddl-sync/Typo/DbIndex.d.ts +13 -0
  219. package/lib/sql-ddl-sync/Typo/DbIndex.js +2 -0
  220. package/lib/sql-ddl-sync/Typo/Dialect.d.ts +81 -0
  221. package/lib/sql-ddl-sync/Typo/Dialect.js +2 -0
  222. package/lib/sql-ddl-sync/Typo/Driver.d.ts +53 -0
  223. package/lib/sql-ddl-sync/Typo/Driver.js +2 -0
  224. package/lib/sql-ddl-sync/Typo/Query.d.ts +7 -0
  225. package/lib/sql-ddl-sync/Typo/Query.js +2 -0
  226. package/lib/sql-ddl-sync/Typo/SQL.d.ts +31 -0
  227. package/lib/sql-ddl-sync/Typo/SQL.js +2 -0
  228. package/lib/sql-ddl-sync/Typo/_common.d.ts +29 -0
  229. package/lib/sql-ddl-sync/Typo/_common.js +2 -0
  230. package/lib/sql-ddl-sync/Utils.d.ts +39 -0
  231. package/lib/sql-ddl-sync/Utils.js +217 -0
  232. package/lib/sql-ddl-sync/index.d.ts +87 -0
  233. package/lib/sql-ddl-sync/index.js +372 -0
  234. package/lib/sql-query/Comparators.d.ts +3 -0
  235. package/lib/sql-query/Comparators.js +95 -0
  236. package/lib/sql-query/Create.d.ts +35 -0
  237. package/lib/sql-query/Create.js +78 -0
  238. package/lib/sql-query/Dialects/dm.d.ts +3 -0
  239. package/lib/sql-query/Dialects/dm.js +75 -0
  240. package/lib/sql-query/Dialects/index.d.ts +10 -0
  241. package/lib/sql-query/Dialects/index.js +13 -0
  242. package/lib/sql-query/Dialects/mssql.d.ts +3 -0
  243. package/lib/sql-query/Dialects/mssql.js +74 -0
  244. package/lib/sql-query/Dialects/mysql.d.ts +3 -0
  245. package/lib/sql-query/Dialects/mysql.js +101 -0
  246. package/lib/sql-query/Dialects/postgresql.d.ts +3 -0
  247. package/lib/sql-query/Dialects/postgresql.js +77 -0
  248. package/lib/sql-query/Dialects/sqlite.d.ts +3 -0
  249. package/lib/sql-query/Dialects/sqlite.js +62 -0
  250. package/lib/sql-query/Helpers.d.ts +37 -0
  251. package/lib/sql-query/Helpers.js +260 -0
  252. package/lib/sql-query/Insert.d.ts +12 -0
  253. package/lib/sql-query/Insert.js +34 -0
  254. package/lib/sql-query/Query.d.ts +28 -0
  255. package/lib/sql-query/Query.js +120 -0
  256. package/lib/sql-query/Remove.d.ts +16 -0
  257. package/lib/sql-query/Remove.js +94 -0
  258. package/lib/sql-query/Select.d.ts +62 -0
  259. package/lib/sql-query/Select.js +534 -0
  260. package/lib/sql-query/Set.d.ts +4 -0
  261. package/lib/sql-query/Set.js +16 -0
  262. package/lib/sql-query/Typo/Aggregation.d.ts +32 -0
  263. package/lib/sql-query/Typo/Aggregation.js +2 -0
  264. package/lib/sql-query/Typo/Comparators.d.ts +140 -0
  265. package/lib/sql-query/Typo/Comparators.js +2 -0
  266. package/lib/sql-query/Typo/Dialect.d.ts +39 -0
  267. package/lib/sql-query/Typo/Dialect.js +2 -0
  268. package/lib/sql-query/Typo/Field.d.ts +8 -0
  269. package/lib/sql-query/Typo/Field.js +2 -0
  270. package/lib/sql-query/Typo/Helper.d.ts +4 -0
  271. package/lib/sql-query/Typo/Helper.js +2 -0
  272. package/lib/sql-query/Typo/Query-ChainBuilder.d.ts +80 -0
  273. package/lib/sql-query/Typo/Query-ChainBuilder.js +2 -0
  274. package/lib/sql-query/Typo/Query.d.ts +34 -0
  275. package/lib/sql-query/Typo/Query.js +17 -0
  276. package/lib/sql-query/Typo/Sql.d.ts +143 -0
  277. package/lib/sql-query/Typo/Sql.js +2 -0
  278. package/lib/sql-query/Typo/SubQuery.d.ts +39 -0
  279. package/lib/sql-query/Typo/SubQuery.js +2 -0
  280. package/lib/sql-query/Typo/index.d.ts +9 -0
  281. package/lib/sql-query/Typo/index.js +2 -0
  282. package/lib/sql-query/Update.d.ts +15 -0
  283. package/lib/sql-query/Update.js +39 -0
  284. package/lib/sql-query/Where.d.ts +4 -0
  285. package/lib/sql-query/Where.js +280 -0
  286. package/package.json +71 -36
  287. package/.travis.yml +0 -14
  288. package/@types/index.d.ts +0 -254
  289. package/@types/orm_mirror/orm.d.ts +0 -275
  290. package/@types/orm_mirror/sql-query.d.ts +0 -79
  291. package/Readme.md +0 -843
  292. package/lib/index.js +0 -13
  293. package/lib/modules/mysql.js +0 -35
  294. package/lib/modules/sqlite3.js +0 -27
  295. package/lib/patch.js +0 -271
@@ -0,0 +1,975 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_GENERATE_SQL_QUERY_SELECT = exports.createHookHelper = exports.takeAwayResult = exports.catchBlocking = void 0;
4
+ exports.standardizeOrder = standardizeOrder;
5
+ exports.addTableToStandardedOrder = addTableToStandardedOrder;
6
+ exports.checkConditions = checkConditions;
7
+ exports.values = values;
8
+ exports.hasValues = hasValues;
9
+ exports.populateModelIdKeysConditions = populateModelIdKeysConditions;
10
+ exports.getConditions = getConditions;
11
+ exports.wrapFieldObject = wrapFieldObject;
12
+ exports.formatAssociatedField = formatAssociatedField;
13
+ exports.extractHasManyExtraConditions = extractHasManyExtraConditions;
14
+ exports.extractSelectTopConditions = extractSelectTopConditions;
15
+ exports.convertPropToJoinKeyProp = convertPropToJoinKeyProp;
16
+ exports.getRealPath = getRealPath;
17
+ exports.transformPropertyNames = transformPropertyNames;
18
+ exports.transformOrderPropertyNames = transformOrderPropertyNames;
19
+ exports.renameDatastoreFieldsToPropertyNames = renameDatastoreFieldsToPropertyNames;
20
+ exports.camelCaseHasMany = camelCaseHasMany;
21
+ exports.ucfirst = ucfirst;
22
+ exports.formatNameFor = formatNameFor;
23
+ exports.combineMergeInfoToArray = combineMergeInfoToArray;
24
+ exports.parseTableInputForSelect = parseTableInputForSelect;
25
+ exports.tableAlias = tableAlias;
26
+ exports.tableAliasCalculatorInOneQuery = tableAliasCalculatorInOneQuery;
27
+ exports.ORM_Error = ORM_Error;
28
+ exports.queryParamCast = queryParamCast;
29
+ exports.isDriverNotSupportedError = isDriverNotSupportedError;
30
+ exports.doWhenErrIs = doWhenErrIs;
31
+ exports.getErrWaitor = getErrWaitor;
32
+ exports.getValueWaitor = getValueWaitor;
33
+ exports.parallelQueryIfPossible = parallelQueryIfPossible;
34
+ exports.filterWhereConditionsInput = filterWhereConditionsInput;
35
+ exports.addUnwritableProperty = addUnwritableProperty;
36
+ exports.addHiddenReadonlyProperty = addHiddenReadonlyProperty;
37
+ exports.addHiddenUnwritableMethodToInstance = addHiddenUnwritableMethodToInstance;
38
+ exports.addHiddenPropertyToInstance = addHiddenPropertyToInstance;
39
+ exports.addHiddenReadonlyPropertyToInstance = addHiddenReadonlyPropertyToInstance;
40
+ exports.fillSyncVersionAccessorForAssociation = fillSyncVersionAccessorForAssociation;
41
+ exports.addHookPatchHelperForAssociation = addHookPatchHelperForAssociation;
42
+ exports.generateUID4SoloGet = generateUID4SoloGet;
43
+ exports.generateUID4ChainFind = generateUID4ChainFind;
44
+ exports.generateUID4Model = generateUID4Model;
45
+ exports.makeIdForDriverTable = makeIdForDriverTable;
46
+ exports.bindInstance = bindInstance;
47
+ exports.buildAssocHooksContext = buildAssocHooksContext;
48
+ exports.makeHandlerDecorator = makeHandlerDecorator;
49
+ exports.reusableChannelGenerator = reusableChannelGenerator;
50
+ exports.attachOnceTypedHookRefToInstance = attachOnceTypedHookRefToInstance;
51
+ exports.arraify = arraify;
52
+ exports.firstEl = firstEl;
53
+ exports.isKeyProperty = isKeyProperty;
54
+ exports.isKeyPrimaryProperty = isKeyPrimaryProperty;
55
+ exports.coercePositiveInt = coercePositiveInt;
56
+ exports.getUUID = getUUID;
57
+ exports.isVirtualViewModel = isVirtualViewModel;
58
+ exports.disAllowOpForVModel = disAllowOpForVModel;
59
+ exports.normalizeVirtualViewOption = normalizeVirtualViewOption;
60
+ exports.__wrapTableSourceAsGneratingSqlSelect = __wrapTableSourceAsGneratingSqlSelect;
61
+ const util = require("util");
62
+ const uuid = require("uuid");
63
+ const coroutine = require("coroutine");
64
+ const events = require("events");
65
+ const _cloneDeep = require("lodash.clonedeep");
66
+ const FxORMCore = require("../orm-core/index");
67
+ const Query_1 = require("../sql-query/Query");
68
+ const Helpers_1 = require("./Helpers");
69
+ const filterDate_1 = require("./Where/filterDate");
70
+ const Error_1 = require("./Error");
71
+ const ZIS = ["A", "Z"];
72
+ function standardizeOrder(order) {
73
+ if (typeof order === "string") {
74
+ let item = [order.substr(1), "Z"];
75
+ if (order[0] === "-") {
76
+ return [item];
77
+ }
78
+ item = [order, "A"];
79
+ return [item];
80
+ }
81
+ // maybe `FxSqlQuery.OrderNormalizedResult`
82
+ if (Array.isArray(order)
83
+ && (Array.isArray(order[1]) || Array.isArray(order[0]))) {
84
+ // is `FxSqlQuery.OrderSqlStyleTuple`
85
+ if (Array.isArray(order[1]))
86
+ return [order];
87
+ // is `FxSqlQuery.OrderNormalizedTuple`
88
+ return [order];
89
+ }
90
+ const new_order = [];
91
+ let minus;
92
+ for (let i = 0, item; i < order.length; i++) {
93
+ item = order[i];
94
+ // deprecate all non-string item
95
+ if (typeof item !== 'string')
96
+ continue;
97
+ /**
98
+ * order from here would not be add table name afterwards
99
+ */
100
+ minus = (item[0] === "-");
101
+ const next_one = order[i + 1];
102
+ const maybe_Z = typeof next_one === 'string' ? next_one.toUpperCase() : 'Z';
103
+ if (i < order.length - 1 && ZIS.indexOf(maybe_Z) >= 0) {
104
+ new_order.push([
105
+ (minus ? item.substr(1) : item),
106
+ maybe_Z
107
+ ]);
108
+ i += 1;
109
+ }
110
+ else if (minus) {
111
+ new_order.push([item.substr(1), "Z"]);
112
+ }
113
+ else {
114
+ new_order.push([item, "A"]);
115
+ }
116
+ }
117
+ return new_order;
118
+ }
119
+ ;
120
+ function addTableToStandardedOrder(order, table_alias) {
121
+ const new_order = [];
122
+ for (let i = 0, item; i < order.length; i++) {
123
+ item = order[i];
124
+ // strange here, we support item[0] here as `FxOrmQuery.OrderNormalizedTuple` :)
125
+ if (Array.isArray(item[0])) {
126
+ new_order.push(item);
127
+ continue;
128
+ }
129
+ new_order.push([
130
+ [table_alias, item[0]],
131
+ item[1]
132
+ ]);
133
+ }
134
+ return new_order;
135
+ }
136
+ /**
137
+ * @description filtered out FxOrmInstance.Instance in mixed FxSqlQuerySubQuery.SubQueryConditions | { [k: string]: FxOrmInstance.Instance }
138
+ */
139
+ function checkConditions(conditions, one_associations) {
140
+ // A) Build an index of associations, with their name as the key
141
+ var associations = {};
142
+ for (let i = 0; i < one_associations.length; i++) {
143
+ associations[one_associations[i].name] = one_associations[i];
144
+ }
145
+ for (let k in conditions) {
146
+ // B) Check for any conditions with a key in the association index
147
+ if (!associations.hasOwnProperty(k))
148
+ continue;
149
+ // C) Ensure that our condition supports array values
150
+ var values = conditions[k];
151
+ if (!Array.isArray(values))
152
+ values = [values];
153
+ // D) Remove original condition (it's instance rather conditon, we would replace it later; not DB compatible)
154
+ delete conditions[k];
155
+ // E) Convert our association fields into an array, indexes are the same as model.id
156
+ const association_fields = Object.keys(associations[k].field);
157
+ const model = associations[k].model;
158
+ // F) Iterate through values for the condition, only accept instances of the same type as the association
159
+ for (let i = 0; i < values.length; i++) {
160
+ const instance = (values[i].isInstance && values[i]);
161
+ if (instance && instance.model().uid === model.uid) {
162
+ if (association_fields.length === 1) {
163
+ const cond_k = association_fields[0];
164
+ if (conditions[cond_k] === undefined) {
165
+ conditions[cond_k] = instance[model.id[0]];
166
+ }
167
+ else if (Array.isArray(conditions[cond_k])) {
168
+ conditions[cond_k].push(instance[model.id[0]]);
169
+ }
170
+ else {
171
+ conditions[cond_k] = [conditions[cond_k], instance[model.id[0]]];
172
+ }
173
+ }
174
+ else {
175
+ var _conds = {};
176
+ for (let j = 0; j < association_fields.length; i++) {
177
+ _conds[association_fields[j]] = instance[model.id[j]];
178
+ }
179
+ conditions.or = conditions.or || [];
180
+ conditions.or.push(_conds);
181
+ }
182
+ }
183
+ }
184
+ }
185
+ return conditions;
186
+ }
187
+ ;
188
+ /**
189
+ * Gets all the values within an object or array, optionally
190
+ * using a keys array to get only specific values
191
+ */
192
+ function values(obj, keys) {
193
+ var vals = [];
194
+ if (keys) {
195
+ const non_arr = obj;
196
+ for (let i = 0; i < keys.length; i++) {
197
+ vals.push(non_arr[keys[i]]);
198
+ }
199
+ }
200
+ else if (Array.isArray(obj)) {
201
+ for (let i = 0; i < obj.length; i++) {
202
+ vals.push(obj[i]);
203
+ }
204
+ }
205
+ else {
206
+ for (let k in obj) {
207
+ if (!/[0-9]+/.test(k)) {
208
+ vals.push(obj[k]);
209
+ }
210
+ }
211
+ }
212
+ return vals;
213
+ }
214
+ ;
215
+ // Qn: is Zero a valid value for a FK column?
216
+ // Why? Well I've got a pre-existing database that started all its 'serial' IDs at zero...
217
+ // Answer: hasValues() is only used in hasOne association, so it's probably ok...
218
+ function hasValues(obj, keys) {
219
+ for (let i = 0; i < keys.length; i++) {
220
+ if (!obj[keys[i]] && obj[keys[i]] !== 0)
221
+ return false; // 0 is also a good value...
222
+ }
223
+ return true;
224
+ }
225
+ ;
226
+ /**
227
+ * @description from from <source> object, copy specific ids(determined by <source_model>) to <target> object as
228
+ * correspoding <associacted_fields>, for example:
229
+ *
230
+ * if <source_model> id: id1, id2
231
+ * if <associacted_fields>: user_id, production_id
232
+ * source.id1 = 1, source.id2 = 2
233
+ * target.user_id = undefined, target.production_id = undefined
234
+ *
235
+ * Then, we will get:
236
+ *
237
+ * target.user_id = 1, target.production_id = 2
238
+ *
239
+ * if target.user_id is not undefined, it wouldn't be overwritten unless <overwrite> is true
240
+ *
241
+ * @param source_model
242
+ * @param associacted_fields
243
+ * @param source
244
+ * @param target
245
+ * @param overwrite
246
+ */
247
+ function populateModelIdKeysConditions(source_model, associacted_fields, source, target, overwrite) {
248
+ const mids = source_model.id;
249
+ for (let i = 0; i < mids.length; i++) {
250
+ if (typeof target[associacted_fields[i]] === 'undefined' || overwrite !== false) {
251
+ target[associacted_fields[i]] = source[mids[i]];
252
+ }
253
+ else if (Array.isArray(target[associacted_fields[i]])) { // that might be conjunction query conditions
254
+ target[associacted_fields[i]]
255
+ .push(source[mids[i]]);
256
+ }
257
+ else {
258
+ target[associacted_fields[i]] = [target[associacted_fields[i]], source[mids[i]]];
259
+ }
260
+ }
261
+ }
262
+ ;
263
+ function getConditions(model, fields, from) {
264
+ var conditions = {};
265
+ populateModelIdKeysConditions(model, fields, from, conditions);
266
+ return conditions;
267
+ }
268
+ ;
269
+ /**
270
+ * TODO: add comment for this method
271
+ *
272
+ * @description WIP
273
+ * @param params
274
+ * @returns
275
+ */
276
+ function wrapFieldObject(params) {
277
+ if (!params.field) {
278
+ var assoc_key = params.model.settings.get("properties.association_key");
279
+ if (typeof assoc_key === "function") {
280
+ params.field = assoc_key(params.altName.toLowerCase(), params.model.id[0]);
281
+ }
282
+ else {
283
+ params.field = assoc_key.replace("{name}", params.altName.toLowerCase())
284
+ .replace("{field}", params.model.id[0]);
285
+ }
286
+ }
287
+ if (typeof params.field == 'object') {
288
+ for (let k in params.field) {
289
+ /* 1st self-own & non-array kv */
290
+ if (!/[0-9]+/.test(k) && params.field.hasOwnProperty(k)) {
291
+ return params.field;
292
+ }
293
+ }
294
+ }
295
+ const field_str = params.field;
296
+ var newProp, propPreDefined, propFromKey;
297
+ propPreDefined = params.model.properties[field_str];
298
+ propFromKey = params.model.properties[params.model.id[0]];
299
+ newProp = { type: 'integer' };
300
+ var prop = _cloneDeep(propPreDefined || propFromKey || newProp);
301
+ if (!propPreDefined) {
302
+ util.extend(prop, {
303
+ name: field_str,
304
+ mapsTo: params.mapsTo || field_str
305
+ });
306
+ }
307
+ return {
308
+ [field_str]: prop
309
+ };
310
+ }
311
+ ;
312
+ /**
313
+ * TODO: add comment for this method
314
+ * @param model related Model
315
+ * @param name field name
316
+ * @param required is field required for relationship
317
+ * @param reversed is model is reversed in relationship
318
+ */
319
+ function formatAssociatedField(model, name, required, reversed) {
320
+ let fields = {}, field_opts, field_name;
321
+ var keys = model.id;
322
+ var assoc_key = model.settings.get("properties.association_key");
323
+ for (let i = 0; i < keys.length; i++) {
324
+ if (reversed) {
325
+ field_name = keys[i];
326
+ }
327
+ else if (typeof assoc_key === "function") {
328
+ field_name = assoc_key(name.toLowerCase(), keys[i]);
329
+ }
330
+ else {
331
+ field_name = assoc_key.replace("{name}", name.toLowerCase())
332
+ .replace("{field}", keys[i]);
333
+ }
334
+ if (model.properties.hasOwnProperty(keys[i])) {
335
+ var p = model.properties[keys[i]];
336
+ field_opts = {
337
+ type: p.type || "integer",
338
+ // TODO: make 32 when p.type === 'text'
339
+ size: p.size || 4,
340
+ unsigned: p.unsigned || true,
341
+ time: p.time || false,
342
+ big: p.big || false,
343
+ values: p.values || null,
344
+ required: required,
345
+ name: field_name,
346
+ mapsTo: field_name
347
+ };
348
+ }
349
+ else {
350
+ field_opts = {
351
+ type: "integer",
352
+ unsigned: true,
353
+ size: 4,
354
+ required: required,
355
+ name: field_name,
356
+ mapsTo: field_name
357
+ };
358
+ }
359
+ fields[field_name] = field_opts;
360
+ }
361
+ return fields;
362
+ }
363
+ ;
364
+ /** @internal */
365
+ function extractHasManyExtraConditions(association, conditions, extra_where) {
366
+ // extract extra info on conditions
367
+ extra_where = Object.assign({}, extra_where);
368
+ // populate out conditions in extra, not belonging to either one model of associations
369
+ for (let k in conditions) {
370
+ if (association.props[k]) {
371
+ extra_where[k] = conditions[k];
372
+ delete conditions[k];
373
+ }
374
+ }
375
+ return extra_where;
376
+ }
377
+ /**
378
+ * @description top conditions means that conditions which matches query's top select.
379
+ */
380
+ function extractSelectTopConditions(conditions, topFields) {
381
+ const topConditions = util.pick(conditions, topFields);
382
+ return {
383
+ topConditions,
384
+ tableConditions: util.omit(conditions, topFields)
385
+ };
386
+ }
387
+ // If the parent associations key is `serial`, the join tables
388
+ // key should be changed to `integer`.
389
+ function convertPropToJoinKeyProp(props, opts) {
390
+ var prop;
391
+ for (let k in props) {
392
+ prop = props[k];
393
+ prop.required = opts.required;
394
+ if (prop.type == 'serial') {
395
+ prop.type = 'integer';
396
+ }
397
+ if (opts.makeKey) {
398
+ prop.key = true;
399
+ }
400
+ else {
401
+ delete prop.key;
402
+ }
403
+ }
404
+ return props;
405
+ }
406
+ function getRealPath(path_str, stack_index) {
407
+ const path = require("path"); // for now, load here (only when needed)
408
+ let cwd = process.cwd();
409
+ const err = new Error();
410
+ let tmp = err.stack.split(/\r?\n/)[typeof stack_index !== "undefined" ? stack_index : 3], m;
411
+ if ((m = tmp.match(/^\s*at\s+(.+):\d+:\d+$/)) !== null) {
412
+ cwd = path.dirname(m[1]);
413
+ }
414
+ else if ((m = tmp.match(/^\s*at\s+module\.exports\s+\((.+?)\)/)) !== null) {
415
+ cwd = path.dirname(m[1]);
416
+ }
417
+ else if ((m = tmp.match(/^\s*at\s+.+\s+\((.+):\d+:\d+\)$/)) !== null) {
418
+ cwd = path.dirname(m[1]);
419
+ }
420
+ const pathIsAbsolute = path.isAbsolute || require('path-is-absolute');
421
+ if (!pathIsAbsolute(path_str)) {
422
+ path_str = path.join(cwd, path_str);
423
+ }
424
+ if (path_str.substr(-1) === path.sep) {
425
+ path_str += "index";
426
+ }
427
+ return path_str;
428
+ }
429
+ ;
430
+ /**
431
+ * @description rename a field name in <dataIn> according to the name map in <properties>
432
+ * @example
433
+ * ```
434
+ * dataIn: { a: 1, b: 2 };
435
+ * properties: { a: { mapsTo: 'a1' }, b: { mapsTo: 'b' } };
436
+ * -->
437
+ * result: { a1: 1, b: 2 };
438
+ * ```
439
+ *
440
+ * @param dataIn
441
+ * @param properties
442
+ */
443
+ function transformPropertyNames(dataIn, properties) {
444
+ var prop;
445
+ var dataOut = {};
446
+ for (let k in dataIn) {
447
+ prop = properties[k];
448
+ if (prop) {
449
+ dataOut[prop.mapsTo] = dataIn[k];
450
+ }
451
+ else {
452
+ dataOut[k] = dataIn[k];
453
+ }
454
+ }
455
+ return dataOut;
456
+ }
457
+ ;
458
+ function transformOrderPropertyNames(order, properties) {
459
+ if (!order)
460
+ return order;
461
+ const newOrder = JSON.parse(JSON.stringify(order));
462
+ // Rename order properties according to mapsTo
463
+ for (let i = 0, item; i < newOrder.length; i++) {
464
+ item = newOrder[i];
465
+ // [ 'SQL..??', [arg1, arg2]]
466
+ if (Array.isArray(item[1]))
467
+ continue;
468
+ if (Array.isArray(item[0])) {
469
+ // [ ['table or alias Name', 'propName'], 'Z']
470
+ let maybePropertyName = item[0][1], orderFlag = 'A';
471
+ [maybePropertyName, orderFlag] = standardizeOrder(maybePropertyName)[0];
472
+ if (!item[1]) {
473
+ item[1] = orderFlag;
474
+ }
475
+ item[0][1] = properties[maybePropertyName].mapsTo;
476
+ }
477
+ else {
478
+ const [maybePropertyName] = standardizeOrder(item[0])[0];
479
+ // normal order
480
+ item[0] = properties[maybePropertyName].mapsTo;
481
+ }
482
+ }
483
+ return newOrder;
484
+ }
485
+ function renameDatastoreFieldsToPropertyNames(data, fieldToPropertyMap) {
486
+ for (let k in data) {
487
+ const prop = fieldToPropertyMap[k];
488
+ if (prop && prop.name != k) {
489
+ data[prop.name] = data[k];
490
+ delete data[k];
491
+ }
492
+ }
493
+ return data;
494
+ }
495
+ function camelCaseHasMany(text) {
496
+ return ucfirst(text[0]) + text.substr(1).replace(/_([a-z])/, function (m, l) {
497
+ return l.toUpperCase();
498
+ });
499
+ }
500
+ function ucfirst(text) {
501
+ return text[0].toUpperCase() + text.substr(1);
502
+ }
503
+ function formatNameFor(key, name) {
504
+ switch (key) {
505
+ case 'assoc:hasMany':
506
+ return camelCaseHasMany(name);
507
+ case 'findBy:common':
508
+ case 'assoc:hasOne':
509
+ case 'findBy:hasOne':
510
+ return ucfirst(name);
511
+ case 'assoc:extendsTo':
512
+ case 'findBy:extendsTo':
513
+ return ucfirst(name);
514
+ case 'field:lazyload':
515
+ return ucfirst(name.toLocaleLowerCase());
516
+ case 'syncify:assoc':
517
+ return name + 'Sync';
518
+ }
519
+ }
520
+ function combineMergeInfoToArray(merges) {
521
+ if (!Array.isArray(merges))
522
+ merges = [merges];
523
+ return merges.filter(Boolean);
524
+ }
525
+ function parseTableInputForSelect(ta_str) {
526
+ const [pure_table, alias = typeof pure_table === 'string' ? pure_table : ''] = Query_1.Helpers.parseTableInputStr(ta_str);
527
+ return {
528
+ pure_table,
529
+ alias,
530
+ from_tuple: [pure_table, alias]
531
+ };
532
+ }
533
+ function tableAlias(table, alias = typeof table === 'string' ? table : '', same_suffix = '') {
534
+ if (Query_1.Helpers.maybeKnexRawOrQueryBuilder(table)) {
535
+ if (!alias) {
536
+ throw new Error(`[tableAlias] when table is knex.raw or knex.queryBuilder, alias must be provided!`);
537
+ }
538
+ return alias;
539
+ }
540
+ return `${table} ${alias}${same_suffix ? ` ${same_suffix}` : ''}`;
541
+ }
542
+ function tableAliasCalculatorInOneQuery() {
543
+ const countHash = {};
544
+ return function increment(tableName, get_only = false) {
545
+ countHash[tableName] = countHash[tableName] || 0;
546
+ if (!get_only) {
547
+ countHash[tableName]++;
548
+ }
549
+ return countHash[tableName];
550
+ };
551
+ }
552
+ function ORM_Error(err, cb) {
553
+ var Emitter = new events.EventEmitter();
554
+ Emitter.use = Emitter.define = Emitter.sync = Emitter.load = function () { };
555
+ if (typeof cb === "function")
556
+ cb(err);
557
+ process.nextTick(function () {
558
+ Emitter.emit("connect", err);
559
+ });
560
+ return Emitter;
561
+ }
562
+ function queryParamCast(val) {
563
+ if (typeof val == 'string') {
564
+ switch (val) {
565
+ case '1':
566
+ case 'true':
567
+ return true;
568
+ case '0':
569
+ case 'false':
570
+ return false;
571
+ }
572
+ }
573
+ return val;
574
+ }
575
+ function isDriverNotSupportedError(err) {
576
+ if (err.code === 'MODULE_NOT_FOUND')
577
+ return true;
578
+ if ([
579
+ // windows not found
580
+ 'The system cannot find the file specified',
581
+ // unix like not found
582
+ 'No such file or directory',
583
+ ].some((msg) => {
584
+ return err.message.indexOf(msg) > -1 || (err.message.toLocaleLowerCase()).indexOf(msg.toLowerCase()) > -1;
585
+ }))
586
+ return true;
587
+ if ([
588
+ 'find module',
589
+ ].some((msg) => {
590
+ return err.message.indexOf(msg) > -1;
591
+ }))
592
+ return true;
593
+ return false;
594
+ }
595
+ exports.catchBlocking = FxORMCore.catchBlocking;
596
+ exports.takeAwayResult = FxORMCore.takeAwayResult;
597
+ function doWhenErrIs(compare, callback, err) {
598
+ if (!err || util.isEmpty(compare))
599
+ return;
600
+ if (!(err instanceof Error))
601
+ return;
602
+ if (compare.hasOwnProperty('message') && err.message !== compare.message)
603
+ return;
604
+ if (compare.hasOwnProperty('literalCode') && err.literalCode !== compare.literalCode)
605
+ return;
606
+ callback(err);
607
+ }
608
+ function getErrWaitor(shouldWait = false) {
609
+ return {
610
+ evt: shouldWait ? new coroutine.Event : null,
611
+ err: null,
612
+ };
613
+ }
614
+ function getValueWaitor(shouldWait = false) {
615
+ return {
616
+ evt: shouldWait ? new coroutine.Event : null,
617
+ value: null,
618
+ };
619
+ }
620
+ function parallelQueryIfPossible(can_parallel, iteratee, iterator) {
621
+ if (can_parallel && iteratee.length > 1)
622
+ return coroutine.parallel(iteratee, (item) => iterator(item));
623
+ return iteratee.map(iterator);
624
+ }
625
+ /**
626
+ * @description do some mutation for field-value in conditions
627
+ *
628
+ * @param conditions
629
+ * @param host
630
+ */
631
+ function filterWhereConditionsInput(conditions, host) {
632
+ if (host.properties) {
633
+ (0, filterDate_1.filterDate)(conditions, { properties: host.properties });
634
+ }
635
+ else {
636
+ (0, filterDate_1.filterDate)(conditions, { properties: host.allProperties });
637
+ }
638
+ return conditions;
639
+ }
640
+ function addUnwritableProperty(obj, property, value, propertyConfiguration = {}) {
641
+ Object.defineProperty(obj, property, Object.assign(Object.assign({ value }, propertyConfiguration), { writable: false }));
642
+ }
643
+ function addHiddenReadonlyProperty(obj, property, getter, propertyConfiguration = {}) {
644
+ Object.defineProperty(obj, property, Object.assign(Object.assign({ get: getter }, propertyConfiguration), { enumerable: false }));
645
+ }
646
+ function addHiddenUnwritableMethodToInstance(instance, method_name, fn, propertyConfiguration = {}) {
647
+ Object.defineProperty(instance, method_name, Object.assign(Object.assign({ value: fn.bind(instance) }, propertyConfiguration), { writable: true, enumerable: false }));
648
+ }
649
+ function addHiddenPropertyToInstance(instance, property_name, value, propertyConfiguration = {}) {
650
+ Object.defineProperty(instance, property_name, Object.assign(Object.assign({ value: value }, propertyConfiguration), { enumerable: false }));
651
+ }
652
+ function addHiddenReadonlyPropertyToInstance(instance, property_name, getter, propertyConfiguration = {}) {
653
+ Object.defineProperty(instance, property_name, Object.assign(Object.assign({ get: getter }, propertyConfiguration), { enumerable: false }));
654
+ }
655
+ function fillSyncVersionAccessorForAssociation(association) {
656
+ if (!association.getSyncAccessor)
657
+ association.getSyncAccessor = formatNameFor('syncify:assoc', association.getAccessor);
658
+ if (!association.setSyncAccessor)
659
+ association.setSyncAccessor = formatNameFor('syncify:assoc', association.setAccessor);
660
+ if (!association.delSyncAccessor)
661
+ association.delSyncAccessor = formatNameFor('syncify:assoc', association.delAccessor);
662
+ if (!association.hasSyncAccessor)
663
+ association.hasSyncAccessor = formatNameFor('syncify:assoc', association.hasAccessor);
664
+ if (!association.addSyncAccessor && association.addAccessor)
665
+ association.addSyncAccessor = formatNameFor('syncify:assoc', association.addAccessor);
666
+ if (!association.modelFindBySyncAccessor && association.modelFindByAccessor)
667
+ association.modelFindBySyncAccessor = formatNameFor('syncify:assoc', association.modelFindByAccessor);
668
+ return association;
669
+ }
670
+ const AvailableHooks = [
671
+ 'beforeSet', 'afterSet',
672
+ 'beforeRemove', 'afterRemove',
673
+ 'beforeAdd', 'afterAdd'
674
+ ];
675
+ function addHookPatchHelperForAssociation(association) {
676
+ // setup hooks
677
+ for (let k in AvailableHooks) {
678
+ association[AvailableHooks[k]] = (0, exports.createHookHelper)(association.hooks, AvailableHooks[k], { initialHooks: Object.assign({}, association.hooks) });
679
+ }
680
+ }
681
+ function generateUID4SoloGet(m_opts, ids) {
682
+ return m_opts.driver.uid + "/" + m_opts.table + "/" + ids.join("/");
683
+ }
684
+ function generateUID4ChainFind(m_opts, merges = [], data) {
685
+ const merge_id = merges.map(merge => (merge ? merge.from.table : "")).join(',');
686
+ let uid = m_opts.driver.uid + "/" + m_opts.table + (merge_id ? `+${merge_id}` : "");
687
+ for (let i = 0; i < m_opts.keys.length; i++) {
688
+ uid += "/" + data[m_opts.keys[i]];
689
+ }
690
+ return uid;
691
+ }
692
+ function generateUID4Model(m_opts) {
693
+ return m_opts.driver.uid + "/" + m_opts.table + "/" + m_opts.keys.join("/");
694
+ }
695
+ function makeIdForDriverTable(driver_uid, table) {
696
+ return `${driver_uid}/${table}`;
697
+ }
698
+ function bindInstance(instance, fn) {
699
+ return fn.bind(instance);
700
+ }
701
+ function buildAssocHooksContext(hookName, payload) {
702
+ const { $ref = {}, useChannel = $ref.useChannel || reusableChannelGenerator() } = payload;
703
+ const { instance = null, association = null, associations = [], association_ids = [], removeConditions = {}, } = $ref;
704
+ if (!instance)
705
+ throw `[buildAssocHooksContext] instance is required`;
706
+ if (!$ref || typeof $ref !== 'object')
707
+ throw `[buildAssocHooksContext]$ref must be valid Object`;
708
+ const ctx = $ref;
709
+ if (!ctx.hasOwnProperty('$ref') || Object.getOwnPropertyDescriptor(ctx, '$ref').configurable)
710
+ Object.defineProperty(ctx, '$ref', { get() { return ctx; }, configurable: false, enumerable: true });
711
+ ctx.association = association;
712
+ ctx.associations = associations;
713
+ ctx.association_ids = association_ids;
714
+ ctx.useChannel = useChannel;
715
+ switch (hookName) {
716
+ case 'beforeSet':
717
+ case 'afterSet':
718
+ break;
719
+ case 'beforeAdd':
720
+ case 'afterAdd':
721
+ break;
722
+ case 'beforeRemove':
723
+ ctx.removeConditions = removeConditions;
724
+ break;
725
+ case 'afterRemove':
726
+ ctx.removeConditions = removeConditions;
727
+ break;
728
+ }
729
+ return ctx;
730
+ }
731
+ function makeHandlerDecorator(opts = {}, hdlr) {
732
+ const { thisArg = null, onlyOnce = true } = opts;
733
+ let finishOnce = false;
734
+ return (err) => {
735
+ if (onlyOnce && finishOnce) {
736
+ console.warn(`[makeHandlerDecorator] this function was once only`);
737
+ return;
738
+ }
739
+ finishOnce = true;
740
+ if (err)
741
+ throw err;
742
+ if (err === false)
743
+ return;
744
+ return hdlr.call(thisArg);
745
+ };
746
+ }
747
+ function getChannelInfo() {
748
+ return {
749
+ id: uuid.snowflake().hex(),
750
+ executed: false,
751
+ fn: null
752
+ };
753
+ }
754
+ function reusableChannelGenerator() {
755
+ const DEFAULT_KEY = `$$default`;
756
+ const channelInfos = {
757
+ [DEFAULT_KEY]: getChannelInfo()
758
+ };
759
+ return function useChannel() {
760
+ let name, _channel;
761
+ (0, Helpers_1.selectArgs)(Array.prototype.slice.apply(arguments), (arg_type, arg) => {
762
+ switch (arg_type) {
763
+ case 'string':
764
+ name = arg;
765
+ break;
766
+ case 'function':
767
+ _channel = arg;
768
+ break;
769
+ }
770
+ });
771
+ if (!name)
772
+ name = DEFAULT_KEY;
773
+ if (!channelInfos.hasOwnProperty(name))
774
+ channelInfos[name] = getChannelInfo();
775
+ const channelInfo = channelInfos[name];
776
+ _channel = _channel || channelInfo.fn;
777
+ if (!_channel)
778
+ throw `[useChannel] channel is required and must be function type`;
779
+ if (!channelInfo.fn && _channel)
780
+ channelInfo.fn = _channel;
781
+ const results = [
782
+ function (...args) {
783
+ if (channelInfo.executed)
784
+ return;
785
+ channelInfo.executed = true;
786
+ if (typeof channelInfo.fn !== 'function')
787
+ throw `[reusableChannelGenerator/useChannel] channel with name ${name} haven't been set 'fn'!`;
788
+ channelInfo.fn.apply(null, args);
789
+ },
790
+ function (fn) {
791
+ if (typeof fn !== 'function')
792
+ throw `[reusableChannelGenerator/useChannel::setChannel] new channel must be function!`;
793
+ channelInfo.fn = fn;
794
+ }
795
+ ];
796
+ results.run = (...args) => {
797
+ return results[0].apply(null, args);
798
+ };
799
+ results.set = (fn, ...args) => {
800
+ return results[1].apply(null, [fn].concat(args));
801
+ };
802
+ return results;
803
+ };
804
+ }
805
+ const createHookHelper = function (hooks, hook, { initialHooks = [] } = {}) {
806
+ return function (cb, opts) {
807
+ if (typeof cb !== "function") {
808
+ delete hooks[hook];
809
+ return this;
810
+ }
811
+ const { oldhook = undefined } = opts || {};
812
+ let tmp = null;
813
+ switch (oldhook) {
814
+ default:
815
+ case 'initial':
816
+ hooks[hook] = initialHooks[hook];
817
+ break;
818
+ case 'overwrite':
819
+ case undefined:
820
+ hooks[hook] = cb;
821
+ break;
822
+ case 'prepend':
823
+ tmp = arraify(hooks[hook]);
824
+ tmp.push(cb);
825
+ hooks[hook] = tmp;
826
+ break;
827
+ case 'append':
828
+ tmp = arraify(hooks[hook]);
829
+ tmp.unshift(cb);
830
+ hooks[hook] = tmp;
831
+ break;
832
+ }
833
+ return this;
834
+ };
835
+ };
836
+ exports.createHookHelper = createHookHelper;
837
+ function attachOnceTypedHookRefToInstance(instance, type, typedHookRef) {
838
+ // ensure instance.$hookRef existed
839
+ if (!instance.hasOwnProperty('$hookRef')) {
840
+ const hookRef = {};
841
+ addHiddenReadonlyPropertyToInstance(instance, '$hookRef', () => hookRef, {
842
+ configurable: false
843
+ });
844
+ }
845
+ typedHookRef = Object.assign({}, typedHookRef);
846
+ typedHookRef.instance = instance;
847
+ typedHookRef.useChannel = reusableChannelGenerator();
848
+ instance.$hookRef[type] = typedHookRef;
849
+ }
850
+ function arraify(item) {
851
+ return Array.isArray(item) ? item : [item];
852
+ }
853
+ function firstEl(item) {
854
+ return Array.isArray(item) ? item[0] : item;
855
+ }
856
+ function isKeyProperty(prop) {
857
+ return prop.key;
858
+ }
859
+ function isKeyPrimaryProperty(prop) {
860
+ return prop.key && prop.klass === 'primary';
861
+ }
862
+ function coercePositiveInt(value, fallbackValue = undefined) {
863
+ const num = parseInt(value, 10);
864
+ if (Number.isNaN(num))
865
+ return fallbackValue;
866
+ return Math.abs(num);
867
+ }
868
+ function getUUID() {
869
+ return uuid.snowflake().hex();
870
+ }
871
+ const DEFAULT_GENERATE_SQL_QUERY_SELECT = function (ctx) {
872
+ return this.query.select()
873
+ .from(ctx.fromTuple)
874
+ .select(ctx.selectFields);
875
+ };
876
+ exports.DEFAULT_GENERATE_SQL_QUERY_SELECT = DEFAULT_GENERATE_SQL_QUERY_SELECT;
877
+ function isVirtualViewModel(model) {
878
+ return (Object.keys(model.allProperties).length === 0
879
+ && Object.keys(model.virtualProperties).length > 0);
880
+ }
881
+ function disAllowOpForVModel(model, opName) {
882
+ if (isVirtualViewModel(model)) {
883
+ throw new Error_1.default(`operation '${opName}' not supported for virtual model`, 'NO_SUPPORT', { model: model.name });
884
+ }
885
+ }
886
+ function normalizeVirtualViewOption(virtualView, knex) {
887
+ let result = {
888
+ disabled: true,
889
+ subQuery: '()'
890
+ };
891
+ if (!virtualView) {
892
+ return result;
893
+ }
894
+ else if (typeof virtualView === 'string') {
895
+ result = {
896
+ disabled: false,
897
+ subQuery: virtualView
898
+ };
899
+ }
900
+ else if (Query_1.Helpers.maybeKnexRawOrQueryBuilder(virtualView)) {
901
+ result = {
902
+ disabled: false,
903
+ subQuery: knex.raw(virtualView.toQuery()).wrap('(', ')').toQuery()
904
+ };
905
+ }
906
+ else if (typeof virtualView === 'object') {
907
+ result = {
908
+ disabled: !!virtualView.disabled,
909
+ subQuery: virtualView.subQuery
910
+ };
911
+ }
912
+ if (!Query_1.Helpers.isWrapperdSubQuerySelect(result === null || result === void 0 ? void 0 : result.subQuery)) {
913
+ throw new Error(`[normalizeVirtualViewOption] invalid virtualView.subQuery: ${result === null || result === void 0 ? void 0 : result.subQuery}, it must be knex.raw(...), knex's query build, or sub query string wrapped with ()`);
914
+ }
915
+ return result;
916
+ }
917
+ /** @internal only for plugin developers */
918
+ function __wrapTableSourceAsGneratingSqlSelect({ virtualView, customSelect: _customSelect, generateSqlSelect, }, opts) {
919
+ const { modelTable, dialect } = opts;
920
+ if (!virtualView.disabled) {
921
+ return function (ctx, querySelect) {
922
+ querySelect
923
+ .from(`${virtualView.subQuery} as ${modelTable}`)
924
+ .select(ctx.selectVirtualFields);
925
+ return querySelect;
926
+ };
927
+ }
928
+ if (!_customSelect)
929
+ return generateSqlSelect;
930
+ const customSelect = arraify(_customSelect).filter(x => !!x && typeof x === 'object').map((tfq) => {
931
+ return {
932
+ from: arraify(tfq.from).filter(Boolean),
933
+ select: arraify(tfq.select)
934
+ .map(select => {
935
+ return typeof select === 'function' ? select(dialect) : select;
936
+ })
937
+ .filter(Boolean),
938
+ wheres: (typeof tfq.wheres === 'string' ? { __sql: [[tfq.wheres]] } : tfq.wheres),
939
+ };
940
+ });
941
+ return function (ctx) {
942
+ const qSelect = this.query.select()
943
+ .from([ctx.table, ctx.table]) // specify the alias as table name itself
944
+ .select(ctx.selectFields);
945
+ customSelect.forEach((tfq) => {
946
+ if (tfq.from.length) {
947
+ tfq.from.forEach(fromItem => {
948
+ // pre convert string like `a` as `[a, a]`
949
+ if (typeof fromItem === 'string' && !Query_1.Helpers.isWrapperdSubQuerySelect(fromItem)) {
950
+ let [tableName = ctx.table, tableAlias] = Query_1.Helpers.parseTableInputStr(fromItem, this.query.Dialect.type);
951
+ tableAlias = tableAlias || tableName;
952
+ qSelect.from([tableName, tableAlias]);
953
+ }
954
+ else {
955
+ qSelect.from(fromItem);
956
+ }
957
+ });
958
+ }
959
+ else {
960
+ qSelect.from([ctx.table, ctx.table]);
961
+ }
962
+ const select = [...new Set([
963
+ ...ctx.selectVirtualFields,
964
+ ...tfq.select
965
+ ])];
966
+ if (select.length)
967
+ qSelect.select(select);
968
+ if (tfq.wheres) {
969
+ qSelect.where(tfq.wheres);
970
+ }
971
+ ;
972
+ });
973
+ return qSelect;
974
+ };
975
+ }