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