@nocobase/database 1.2.13-alpha → 1.3.0-alpha.20240710084543

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 (247) hide show
  1. package/package.json +4 -4
  2. package/lib/collection-factory.d.ts +0 -25
  3. package/lib/collection-factory.js +0 -61
  4. package/lib/collection-group-manager.d.ts +0 -34
  5. package/lib/collection-group-manager.js +0 -66
  6. package/lib/collection-importer.d.ts +0 -15
  7. package/lib/collection-importer.js +0 -83
  8. package/lib/collection.d.ts +0 -145
  9. package/lib/collection.js +0 -663
  10. package/lib/database-utils/index.d.ts +0 -16
  11. package/lib/database-utils/index.js +0 -75
  12. package/lib/database.d.ts +0 -228
  13. package/lib/database.js +0 -795
  14. package/lib/decorators/must-have-filter-decorator.d.ts +0 -10
  15. package/lib/decorators/must-have-filter-decorator.js +0 -48
  16. package/lib/decorators/target-collection-decorator.d.ts +0 -10
  17. package/lib/decorators/target-collection-decorator.js +0 -56
  18. package/lib/decorators/transaction-decorator.d.ts +0 -9
  19. package/lib/decorators/transaction-decorator.js +0 -95
  20. package/lib/eager-loading/eager-loading-tree.d.ts +0 -39
  21. package/lib/eager-loading/eager-loading-tree.js +0 -448
  22. package/lib/errors/identifier-error.d.ts +0 -11
  23. package/lib/errors/identifier-error.js +0 -44
  24. package/lib/errors/zero-column-table-error.d.ts +0 -10
  25. package/lib/errors/zero-column-table-error.js +0 -40
  26. package/lib/features/references-map.d.ts +0 -29
  27. package/lib/features/references-map.js +0 -120
  28. package/lib/features/referential-integrity-check.d.ts +0 -16
  29. package/lib/features/referential-integrity-check.js +0 -86
  30. package/lib/field-repository/array-field-repository.d.ts +0 -36
  31. package/lib/field-repository/array-field-repository.js +0 -179
  32. package/lib/fields/array-field.d.ts +0 -19
  33. package/lib/fields/array-field.js +0 -66
  34. package/lib/fields/belongs-to-field.d.ts +0 -25
  35. package/lib/fields/belongs-to-field.js +0 -166
  36. package/lib/fields/belongs-to-many-field.d.ts +0 -28
  37. package/lib/fields/belongs-to-many-field.js +0 -196
  38. package/lib/fields/boolean-field.d.ts +0 -16
  39. package/lib/fields/boolean-field.js +0 -45
  40. package/lib/fields/context-field.d.ts +0 -22
  41. package/lib/fields/context-field.js +0 -79
  42. package/lib/fields/date-field.d.ts +0 -21
  43. package/lib/fields/date-field.js +0 -73
  44. package/lib/fields/field.d.ts +0 -52
  45. package/lib/fields/field.js +0 -168
  46. package/lib/fields/has-inverse-field.d.ts +0 -12
  47. package/lib/fields/has-inverse-field.js +0 -24
  48. package/lib/fields/has-many-field.d.ts +0 -76
  49. package/lib/fields/has-many-field.js +0 -165
  50. package/lib/fields/has-one-field.d.ts +0 -76
  51. package/lib/fields/has-one-field.js +0 -159
  52. package/lib/fields/index.d.ts +0 -54
  53. package/lib/fields/index.js +0 -74
  54. package/lib/fields/json-field.d.ts +0 -22
  55. package/lib/fields/json-field.js +0 -63
  56. package/lib/fields/nanoid-field.d.ts +0 -22
  57. package/lib/fields/nanoid-field.js +0 -65
  58. package/lib/fields/number-field.d.ts +0 -49
  59. package/lib/fields/number-field.js +0 -94
  60. package/lib/fields/password-field.d.ts +0 -29
  61. package/lib/fields/password-field.js +0 -106
  62. package/lib/fields/radio-field.d.ts +0 -24
  63. package/lib/fields/radio-field.js +0 -75
  64. package/lib/fields/relation-field.d.ts +0 -31
  65. package/lib/fields/relation-field.js +0 -94
  66. package/lib/fields/set-field.d.ts +0 -18
  67. package/lib/fields/set-field.js +0 -55
  68. package/lib/fields/sort-field.d.ts +0 -22
  69. package/lib/fields/sort-field.js +0 -197
  70. package/lib/fields/string-field.d.ts +0 -16
  71. package/lib/fields/string-field.js +0 -45
  72. package/lib/fields/text-field.d.ts +0 -18
  73. package/lib/fields/text-field.js +0 -53
  74. package/lib/fields/time-field.d.ts +0 -16
  75. package/lib/fields/time-field.js +0 -45
  76. package/lib/fields/uid-field.d.ts +0 -21
  77. package/lib/fields/uid-field.js +0 -72
  78. package/lib/fields/uuid-field.d.ts +0 -20
  79. package/lib/fields/uuid-field.js +0 -63
  80. package/lib/fields/virtual-field.d.ts +0 -16
  81. package/lib/fields/virtual-field.js +0 -45
  82. package/lib/filter-match.d.ts +0 -9
  83. package/lib/filter-match.js +0 -75
  84. package/lib/filter-parser.d.ts +0 -29
  85. package/lib/filter-parser.js +0 -238
  86. package/lib/helpers.d.ts +0 -11
  87. package/lib/helpers.js +0 -182
  88. package/lib/index.d.ts +0 -37
  89. package/lib/index.js +0 -138
  90. package/lib/inherited-collection.d.ts +0 -22
  91. package/lib/inherited-collection.js +0 -147
  92. package/lib/inherited-map.d.ts +0 -29
  93. package/lib/inherited-map.js +0 -125
  94. package/lib/inherited-sync-runner.d.ts +0 -12
  95. package/lib/inherited-sync-runner.js +0 -184
  96. package/lib/interface-manager.d.ts +0 -17
  97. package/lib/interface-manager.js +0 -50
  98. package/lib/interfaces/base-interface.d.ts +0 -33
  99. package/lib/interfaces/base-interface.js +0 -80
  100. package/lib/interfaces/boolean-interface.d.ts +0 -13
  101. package/lib/interfaces/boolean-interface.js +0 -70
  102. package/lib/interfaces/checkboxes-interface.d.ts +0 -11
  103. package/lib/interfaces/checkboxes-interface.js +0 -41
  104. package/lib/interfaces/datetime-interface.d.ts +0 -13
  105. package/lib/interfaces/datetime-interface.js +0 -108
  106. package/lib/interfaces/index.d.ts +0 -14
  107. package/lib/interfaces/index.js +0 -40
  108. package/lib/interfaces/integer-interface.d.ts +0 -12
  109. package/lib/interfaces/integer-interface.js +0 -44
  110. package/lib/interfaces/json-interface.d.ts +0 -13
  111. package/lib/interfaces/json-interface.js +0 -47
  112. package/lib/interfaces/many-to-many-interface.d.ts +0 -11
  113. package/lib/interfaces/many-to-many-interface.js +0 -41
  114. package/lib/interfaces/many-to-one-interface.d.ts +0 -11
  115. package/lib/interfaces/many-to-one-interface.js +0 -41
  116. package/lib/interfaces/multiple-select-interface.d.ts +0 -13
  117. package/lib/interfaces/multiple-select-interface.js +0 -76
  118. package/lib/interfaces/number-interface.d.ts +0 -15
  119. package/lib/interfaces/number-interface.js +0 -72
  120. package/lib/interfaces/one-belongs-to-one-interface.d.ts +0 -11
  121. package/lib/interfaces/one-belongs-to-one-interface.js +0 -41
  122. package/lib/interfaces/one-has-one-interface.d.ts +0 -11
  123. package/lib/interfaces/one-has-one-interface.js +0 -41
  124. package/lib/interfaces/one-to-many-interface.d.ts +0 -11
  125. package/lib/interfaces/one-to-many-interface.js +0 -41
  126. package/lib/interfaces/percent-interface.d.ts +0 -13
  127. package/lib/interfaces/percent-interface.js +0 -55
  128. package/lib/interfaces/select-interface.d.ts +0 -13
  129. package/lib/interfaces/select-interface.js +0 -63
  130. package/lib/interfaces/to-many-interface.d.ts +0 -12
  131. package/lib/interfaces/to-many-interface.js +0 -61
  132. package/lib/interfaces/to-one-interface.d.ts +0 -13
  133. package/lib/interfaces/to-one-interface.js +0 -61
  134. package/lib/interfaces/utils.d.ts +0 -10
  135. package/lib/interfaces/utils.js +0 -72
  136. package/lib/listeners/adjacency-list.d.ts +0 -10
  137. package/lib/listeners/adjacency-list.js +0 -51
  138. package/lib/listeners/append-child-collection-name-after-repository-find.d.ts +0 -14
  139. package/lib/listeners/append-child-collection-name-after-repository-find.js +0 -75
  140. package/lib/listeners/index.d.ts +0 -10
  141. package/lib/listeners/index.js +0 -42
  142. package/lib/magic-attribute-model.d.ts +0 -16
  143. package/lib/magic-attribute-model.js +0 -213
  144. package/lib/migration.d.ts +0 -43
  145. package/lib/migration.js +0 -112
  146. package/lib/mock-database.d.ts +0 -33
  147. package/lib/mock-database.js +0 -136
  148. package/lib/model-hook.d.ts +0 -20
  149. package/lib/model-hook.js +0 -96
  150. package/lib/model.d.ts +0 -32
  151. package/lib/model.js +0 -179
  152. package/lib/operators/array.d.ts +0 -10
  153. package/lib/operators/array.js +0 -196
  154. package/lib/operators/association.d.ts +0 -10
  155. package/lib/operators/association.js +0 -44
  156. package/lib/operators/boolean.d.ts +0 -10
  157. package/lib/operators/boolean.js +0 -47
  158. package/lib/operators/child-collection.d.ts +0 -10
  159. package/lib/operators/child-collection.js +0 -77
  160. package/lib/operators/date.d.ts +0 -10
  161. package/lib/operators/date.js +0 -149
  162. package/lib/operators/empty.d.ts +0 -13
  163. package/lib/operators/empty.js +0 -102
  164. package/lib/operators/eq.d.ts +0 -10
  165. package/lib/operators/eq.js +0 -44
  166. package/lib/operators/index.d.ts +0 -13
  167. package/lib/operators/index.js +0 -63
  168. package/lib/operators/ne.d.ts +0 -10
  169. package/lib/operators/ne.js +0 -49
  170. package/lib/operators/notIn.d.ts +0 -10
  171. package/lib/operators/notIn.js +0 -42
  172. package/lib/operators/string.d.ts +0 -10
  173. package/lib/operators/string.js +0 -118
  174. package/lib/operators/utils.d.ts +0 -12
  175. package/lib/operators/utils.js +0 -53
  176. package/lib/options-parser.d.ts +0 -45
  177. package/lib/options-parser.js +0 -350
  178. package/lib/query-interface/mysql-query-interface.d.ts +0 -44
  179. package/lib/query-interface/mysql-query-interface.js +0 -134
  180. package/lib/query-interface/postgres-query-interface.d.ts +0 -41
  181. package/lib/query-interface/postgres-query-interface.js +0 -207
  182. package/lib/query-interface/query-interface-builder.d.ts +0 -10
  183. package/lib/query-interface/query-interface-builder.js +0 -55
  184. package/lib/query-interface/query-interface.d.ts +0 -52
  185. package/lib/query-interface/query-interface.js +0 -59
  186. package/lib/query-interface/sqlite-query-interface.d.ts +0 -44
  187. package/lib/query-interface/sqlite-query-interface.js +0 -141
  188. package/lib/relation-repository/belongs-to-many-repository.d.ts +0 -28
  189. package/lib/relation-repository/belongs-to-many-repository.js +0 -248
  190. package/lib/relation-repository/belongs-to-repository.d.ts +0 -17
  191. package/lib/relation-repository/belongs-to-repository.js +0 -51
  192. package/lib/relation-repository/hasmany-repository.d.ts +0 -21
  193. package/lib/relation-repository/hasmany-repository.js +0 -158
  194. package/lib/relation-repository/hasone-repository.d.ts +0 -17
  195. package/lib/relation-repository/hasone-repository.js +0 -51
  196. package/lib/relation-repository/multiple-relation-repository.d.ts +0 -27
  197. package/lib/relation-repository/multiple-relation-repository.js +0 -200
  198. package/lib/relation-repository/relation-repository.d.ts +0 -38
  199. package/lib/relation-repository/relation-repository.js +0 -175
  200. package/lib/relation-repository/single-relation-repository.d.ts +0 -36
  201. package/lib/relation-repository/single-relation-repository.js +0 -151
  202. package/lib/relation-repository/types.d.ts +0 -15
  203. package/lib/relation-repository/types.js +0 -24
  204. package/lib/repositories/tree-repository/adjacency-list-repository.d.ts +0 -26
  205. package/lib/repositories/tree-repository/adjacency-list-repository.js +0 -192
  206. package/lib/repositories/view-repository.d.ts +0 -11
  207. package/lib/repositories/view-repository.js +0 -41
  208. package/lib/repository.d.ts +0 -214
  209. package/lib/repository.js +0 -609
  210. package/lib/sql-parser/index.d.ts +0 -13
  211. package/lib/sql-parser/index.js +0 -33
  212. package/lib/sync-runner.d.ts +0 -41
  213. package/lib/sync-runner.js +0 -335
  214. package/lib/types.d.ts +0 -57
  215. package/lib/types.js +0 -24
  216. package/lib/update-associations.d.ts +0 -68
  217. package/lib/update-associations.js +0 -429
  218. package/lib/update-guard.d.ts +0 -36
  219. package/lib/update-guard.js +0 -212
  220. package/lib/utils.d.ts +0 -15
  221. package/lib/utils.js +0 -136
  222. package/lib/value-parsers/array-value-parser.d.ts +0 -16
  223. package/lib/value-parsers/array-value-parser.js +0 -67
  224. package/lib/value-parsers/base-value-parser.d.ts +0 -20
  225. package/lib/value-parsers/base-value-parser.js +0 -72
  226. package/lib/value-parsers/boolean-value-parser.d.ts +0 -12
  227. package/lib/value-parsers/boolean-value-parser.js +0 -61
  228. package/lib/value-parsers/date-value-parser.d.ts +0 -13
  229. package/lib/value-parsers/date-value-parser.js +0 -99
  230. package/lib/value-parsers/index.d.ts +0 -20
  231. package/lib/value-parsers/index.js +0 -87
  232. package/lib/value-parsers/json-value-parser.d.ts +0 -12
  233. package/lib/value-parsers/json-value-parser.js +0 -56
  234. package/lib/value-parsers/number-value-parser.d.ts +0 -12
  235. package/lib/value-parsers/number-value-parser.js +0 -67
  236. package/lib/value-parsers/string-value-parser.d.ts +0 -16
  237. package/lib/value-parsers/string-value-parser.js +0 -73
  238. package/lib/value-parsers/to-many-value-parser.d.ts +0 -21
  239. package/lib/value-parsers/to-many-value-parser.js +0 -117
  240. package/lib/value-parsers/to-one-value-parser.d.ts +0 -12
  241. package/lib/value-parsers/to-one-value-parser.js +0 -57
  242. package/lib/view/field-type-map.d.ts +0 -109
  243. package/lib/view/field-type-map.js +0 -101
  244. package/lib/view/view-inference.d.ts +0 -40
  245. package/lib/view/view-inference.js +0 -157
  246. package/lib/view-collection.d.ts +0 -14
  247. package/lib/view-collection.js +0 -54
package/lib/database.js DELETED
@@ -1,795 +0,0 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
-
10
- var __create = Object.create;
11
- var __defProp = Object.defineProperty;
12
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
- var __getOwnPropNames = Object.getOwnPropertyNames;
14
- var __getProtoOf = Object.getPrototypeOf;
15
- var __hasOwnProp = Object.prototype.hasOwnProperty;
16
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
17
- var __export = (target, all) => {
18
- for (var name in all)
19
- __defProp(target, name, { get: all[name], enumerable: true });
20
- };
21
- var __copyProps = (to, from, except, desc) => {
22
- if (from && typeof from === "object" || typeof from === "function") {
23
- for (let key of __getOwnPropNames(from))
24
- if (!__hasOwnProp.call(to, key) && key !== except)
25
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
26
- }
27
- return to;
28
- };
29
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
30
- // If the importer is in node compatibility mode or this is not an ESM
31
- // file that has been converted to a CommonJS file using a Babel-
32
- // compatible transform (i.e. "__esModule" has not been set), then set
33
- // "default" to the CommonJS "module.exports" for node compatibility.
34
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
35
- mod
36
- ));
37
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
38
- var database_exports = {};
39
- __export(database_exports, {
40
- Database: () => Database,
41
- DialectVersionAccessors: () => DialectVersionAccessors,
42
- default: () => database_default,
43
- defineCollection: () => defineCollection,
44
- extend: () => extend,
45
- extendCollection: () => extendCollection
46
- });
47
- module.exports = __toCommonJS(database_exports);
48
- var import_logger = require("@nocobase/logger");
49
- var import_utils = require("@nocobase/utils");
50
- var import_chalk = __toESM(require("chalk"));
51
- var import_events = require("events");
52
- var import_exponential_backoff = require("exponential-backoff");
53
- var import_glob = __toESM(require("glob"));
54
- var import_lodash = __toESM(require("lodash"));
55
- var import_nanoid = require("nanoid");
56
- var import_path = require("path");
57
- var import_safe_json_stringify = __toESM(require("safe-json-stringify"));
58
- var import_semver = __toESM(require("semver"));
59
- var import_sequelize = require("sequelize");
60
- var import_umzug = require("umzug");
61
- var import_collection_factory = require("./collection-factory");
62
- var import_collection_group_manager = require("./collection-group-manager");
63
- var import_collection_importer = require("./collection-importer");
64
- var import_database_utils = __toESM(require("./database-utils"));
65
- var import_references_map = __toESM(require("./features/references-map"));
66
- var import_referential_integrity_check = require("./features/referential-integrity-check");
67
- var FieldTypes = __toESM(require("./fields"));
68
- var import_helpers = require("./helpers");
69
- var import_inherited_collection = require("./inherited-collection");
70
- var import_inherited_map = __toESM(require("./inherited-map"));
71
- var import_interface_manager = require("./interface-manager");
72
- var import_utils2 = require("./interfaces/utils");
73
- var import_listeners = require("./listeners");
74
- var import_migration = require("./migration");
75
- var import_model_hook = require("./model-hook");
76
- var import_operators = __toESM(require("./operators"));
77
- var import_query_interface_builder = __toESM(require("./query-interface/query-interface-builder"));
78
- var import_utils3 = require("./utils");
79
- var import_value_parsers = require("./value-parsers");
80
- var import_view_collection = require("./view-collection");
81
- const DialectVersionAccessors = {
82
- sqlite: {
83
- sql: "select sqlite_version() as version",
84
- get: (v) => v
85
- },
86
- mysql: {
87
- sql: "select version() as version",
88
- get: (v) => {
89
- const m = /([\d+.]+)/.exec(v);
90
- return m[0];
91
- }
92
- },
93
- mariadb: {
94
- sql: "select version() as version",
95
- get: (v) => {
96
- const m = /([\d+.]+)/.exec(v);
97
- return m[0];
98
- }
99
- },
100
- postgres: {
101
- sql: "select version() as version",
102
- get: (v) => {
103
- const m = /([\d+.]+)/.exec(v);
104
- return import_semver.default.minVersion(m[0]).version;
105
- }
106
- }
107
- };
108
- const _Database = class _Database extends import_events.EventEmitter {
109
- sequelize;
110
- migrator;
111
- migrations;
112
- fieldTypes = /* @__PURE__ */ new Map();
113
- fieldValueParsers = /* @__PURE__ */ new Map();
114
- options;
115
- models = /* @__PURE__ */ new Map();
116
- repositories = /* @__PURE__ */ new Map();
117
- operators = /* @__PURE__ */ new Map();
118
- collections = /* @__PURE__ */ new Map();
119
- pendingFields = /* @__PURE__ */ new Map();
120
- modelCollection = /* @__PURE__ */ new Map();
121
- tableNameCollectionMap = /* @__PURE__ */ new Map();
122
- context = {};
123
- queryInterface;
124
- utils = new import_database_utils.default(this);
125
- referenceMap = new import_references_map.default(this);
126
- inheritanceMap = new import_inherited_map.default();
127
- importedFrom = /* @__PURE__ */ new Map();
128
- modelHook;
129
- delayCollectionExtend = /* @__PURE__ */ new Map();
130
- logger;
131
- collectionGroupManager = new import_collection_group_manager.CollectionGroupManager(this);
132
- interfaceManager = new import_interface_manager.InterfaceManager(this);
133
- collectionFactory = new import_collection_factory.CollectionFactory(this);
134
- constructor(options) {
135
- super();
136
- const opts = {
137
- sync: {
138
- alter: {
139
- drop: false
140
- },
141
- force: false
142
- },
143
- ...import_lodash.default.clone(options)
144
- };
145
- if (options.logger) {
146
- if (typeof options.logger["log"] === "function") {
147
- this.logger = options.logger;
148
- } else {
149
- this.logger = (0, import_logger.createLogger)(options.logger);
150
- }
151
- } else {
152
- this.logger = (0, import_logger.createConsoleLogger)();
153
- }
154
- if (!options.instanceId) {
155
- this._instanceId = (0, import_nanoid.nanoid)();
156
- } else {
157
- this._instanceId = options.instanceId;
158
- }
159
- if (options.storage && options.storage !== ":memory:") {
160
- if (!(0, import_path.isAbsolute)(options.storage)) {
161
- opts.storage = (0, import_path.resolve)(process.cwd(), options.storage);
162
- }
163
- }
164
- if (options.dialect === "sqlite") {
165
- delete opts.timezone;
166
- } else if (!opts.timezone) {
167
- opts.timezone = "+00:00";
168
- }
169
- if (options.dialect === "postgres") {
170
- const types = require("pg").types;
171
- types.setTypeParser(types.builtins.INT8, function(val) {
172
- if (val <= Number.MAX_SAFE_INTEGER) {
173
- return Number(val);
174
- }
175
- return val;
176
- });
177
- }
178
- this.options = opts;
179
- this.logger.debug(
180
- `create database instance: ${(0, import_safe_json_stringify.default)(
181
- // remove sensitive information
182
- import_lodash.default.omit(this.options, ["storage", "host", "password"])
183
- )}`,
184
- {
185
- databaseInstanceId: this.instanceId
186
- }
187
- );
188
- const sequelizeOptions = this.sequelizeOptions(this.options);
189
- this.sequelize = new import_sequelize.Sequelize(sequelizeOptions);
190
- this.queryInterface = (0, import_query_interface_builder.default)(this);
191
- this.collections = /* @__PURE__ */ new Map();
192
- this.modelHook = new import_model_hook.ModelHook(this);
193
- this.on("afterDefineCollection", (collection) => {
194
- var _a, _b;
195
- (_a = this.pendingFields.get(collection.name)) == null ? void 0 : _a.forEach((field) => field.bind());
196
- (_b = this.delayCollectionExtend.get(collection.name)) == null ? void 0 : _b.forEach((collectionExtend) => {
197
- collection.updateOptions(collectionExtend.collectionOptions, collectionExtend.mergeOptions);
198
- });
199
- });
200
- for (const [name, field] of Object.entries(FieldTypes)) {
201
- if (["Field", "RelationField"].includes(name)) {
202
- continue;
203
- }
204
- let key = name.replace(/Field$/g, "");
205
- key = key.substring(0, 1).toLowerCase() + key.substring(1);
206
- this.registerFieldTypes({
207
- [key]: field
208
- });
209
- }
210
- (0, import_utils2.registerInterfaces)(this);
211
- (0, import_value_parsers.registerFieldValueParsers)(this);
212
- this.initOperators();
213
- const migratorOptions = this.options.migrator || {};
214
- const context = {
215
- db: this,
216
- sequelize: this.sequelize,
217
- queryInterface: this.sequelize.getQueryInterface(),
218
- ...migratorOptions.context
219
- };
220
- this.migrations = new import_migration.Migrations(context);
221
- this.sequelize.beforeDefine((model, opts2) => {
222
- if (this.options.tablePrefix) {
223
- if (opts2.tableName && opts2.tableName.startsWith(this.options.tablePrefix)) {
224
- return;
225
- }
226
- opts2.tableName = `${this.options.tablePrefix}${opts2.tableName || opts2.modelName || opts2.name.plural}`;
227
- }
228
- });
229
- this.collection({
230
- name: "migrations",
231
- autoGenId: false,
232
- timestamps: false,
233
- dumpRules: "required",
234
- origin: "@nocobase/database",
235
- fields: [{ type: "string", name: "name", primaryKey: true }]
236
- });
237
- this.migrator = new import_umzug.Umzug({
238
- logger: migratorOptions.logger || console,
239
- migrations: this.migrations.callback(),
240
- context,
241
- storage: new import_umzug.SequelizeStorage({
242
- tableName: `${this.options.tablePrefix || ""}migrations`,
243
- modelName: "migrations",
244
- ...migratorOptions.storage,
245
- sequelize: this.sequelize
246
- })
247
- });
248
- this.initListener();
249
- (0, import_utils3.patchSequelizeQueryInterface)(this);
250
- this.registerCollectionType();
251
- }
252
- _instanceId;
253
- get instanceId() {
254
- return this._instanceId;
255
- }
256
- /**
257
- * @internal
258
- */
259
- createMigrator({ migrations }) {
260
- const migratorOptions = this.options.migrator || {};
261
- const context = {
262
- db: this,
263
- sequelize: this.sequelize,
264
- queryInterface: this.sequelize.getQueryInterface(),
265
- ...migratorOptions.context
266
- };
267
- return new import_umzug.Umzug({
268
- logger: migratorOptions.logger || console,
269
- migrations: Array.isArray(migrations) ? import_lodash.default.sortBy(migrations, (m) => m.name) : migrations,
270
- context,
271
- storage: new import_umzug.SequelizeStorage({
272
- tableName: `${this.options.tablePrefix || ""}migrations`,
273
- modelName: "migrations",
274
- ...migratorOptions.storage,
275
- sequelize: this.sequelize
276
- })
277
- });
278
- }
279
- /**
280
- * @internal
281
- */
282
- setContext(context) {
283
- this.context = context;
284
- }
285
- /**
286
- * @internal
287
- */
288
- sequelizeOptions(options) {
289
- if (options.dialect === "postgres") {
290
- if (!options.hooks) {
291
- options.hooks = {};
292
- }
293
- if (!options.hooks["afterConnect"]) {
294
- options.hooks["afterConnect"] = [];
295
- }
296
- options.hooks["afterConnect"].push(async (connection) => {
297
- await connection.query("SET search_path TO public;");
298
- });
299
- }
300
- return options;
301
- }
302
- /**
303
- * @internal
304
- */
305
- initListener() {
306
- this.on("afterConnect", async (client) => {
307
- if (this.inDialect("postgres")) {
308
- await client.query("SET search_path = public");
309
- }
310
- });
311
- this.on("beforeDefine", (model, options) => {
312
- if (this.options.underscored && options.underscored === void 0) {
313
- options.underscored = true;
314
- }
315
- });
316
- this.on("afterCreate", async (instance) => {
317
- var _a;
318
- (_a = instance == null ? void 0 : instance.toChangedWithAssociations) == null ? void 0 : _a.call(instance);
319
- });
320
- this.on("beforeValidate", async (instance) => {
321
- for (const [key, attribute] of Object.entries(instance.constructor.rawAttributes)) {
322
- if (attribute.unique && instance.changed(key)) {
323
- if (instance.get(key) === "") {
324
- instance.set(key, null);
325
- }
326
- }
327
- }
328
- });
329
- this.on("afterUpdate", async (instance) => {
330
- var _a;
331
- (_a = instance == null ? void 0 : instance.toChangedWithAssociations) == null ? void 0 : _a.call(instance);
332
- });
333
- this.on("beforeDestroy", async (instance, options) => {
334
- await (0, import_referential_integrity_check.referentialIntegrityCheck)({
335
- db: this,
336
- referencedInstance: instance,
337
- transaction: options.transaction
338
- });
339
- });
340
- this.on("afterRemoveCollection", (collection) => {
341
- this.inheritanceMap.removeNode(collection.name);
342
- });
343
- this.on("afterDefine", (model) => {
344
- if (import_lodash.default.get(this.options, "usingBigIntForId", true)) {
345
- const idAttribute = model.rawAttributes["id"];
346
- if (idAttribute && idAttribute.primaryKey) {
347
- model.rawAttributes["id"].type = import_sequelize.DataTypes.BIGINT;
348
- model.refreshAttributes();
349
- }
350
- }
351
- });
352
- this.on("afterUpdateCollection", (collection, options) => {
353
- if (collection.options.schema) {
354
- collection.model._schema = collection.options.schema;
355
- }
356
- if (collection.options.sql) {
357
- collection.modelInit();
358
- }
359
- });
360
- this.on("beforeDefineCollection", (options) => {
361
- if (this.options.underscored && options.underscored === void 0) {
362
- options.underscored = true;
363
- }
364
- if (options.underscored) {
365
- if (import_lodash.default.get(options, "sortable.scopeKey")) {
366
- options.sortable.scopeKey = (0, import_utils3.snakeCase)(options.sortable.scopeKey);
367
- }
368
- if (import_lodash.default.get(options, "indexes")) {
369
- options.indexes = options.indexes.map((index) => {
370
- if (index.fields) {
371
- index.fields = index.fields.map((field) => {
372
- return (0, import_utils3.snakeCase)(field);
373
- });
374
- }
375
- return index;
376
- });
377
- }
378
- }
379
- if (this.options.schema && !options.schema) {
380
- options.schema = this.options.schema;
381
- }
382
- });
383
- this.on("afterDefineCollection", async (collection) => {
384
- const options = collection.options;
385
- if (options.origin) {
386
- const existsSet = this.importedFrom.get(options.origin) || /* @__PURE__ */ new Set();
387
- existsSet.add(collection.name);
388
- this.importedFrom.set(options.origin, existsSet);
389
- }
390
- });
391
- (0, import_listeners.registerBuiltInListeners)(this);
392
- }
393
- addMigration(item) {
394
- return this.migrations.add(item);
395
- }
396
- addMigrations(options) {
397
- const { namespace, context, extensions = ["js", "ts"], directory } = options;
398
- const patten = `${directory}/*.{${extensions.join(",")}}`;
399
- const files = import_glob.default.sync(patten, {
400
- ignore: ["**/*.d.ts"]
401
- });
402
- for (const file of files) {
403
- let filename = (0, import_path.basename)(file);
404
- filename = filename.substring(0, filename.lastIndexOf(".")) || filename;
405
- this.migrations.add({
406
- name: namespace ? `${namespace}/${filename}` : filename,
407
- migration: file,
408
- context
409
- });
410
- }
411
- }
412
- inDialect(...dialect) {
413
- return dialect.includes(this.sequelize.getDialect());
414
- }
415
- isMySQLCompatibleDialect() {
416
- return this.inDialect("mysql", "mariadb");
417
- }
418
- /**
419
- * Add collection to database
420
- * @param options
421
- */
422
- collection(options) {
423
- options = import_lodash.default.cloneDeep(options);
424
- if (this.options.underscored) {
425
- options.underscored = true;
426
- }
427
- this.logger.trace(`beforeDefineCollection: ${(0, import_safe_json_stringify.default)(options)}`, {
428
- databaseInstanceId: this.instanceId
429
- });
430
- this.emit("beforeDefineCollection", options);
431
- const collection = this.collectionFactory.createCollection(options);
432
- this.collections.set(collection.name, collection);
433
- this.emit("afterDefineCollection", collection);
434
- return collection;
435
- }
436
- getTablePrefix() {
437
- return this.options.tablePrefix || "";
438
- }
439
- getFieldByPath(path) {
440
- if (!path) {
441
- return;
442
- }
443
- const [collectionName, associationName, ...args] = path.split(".");
444
- const collection = this.getCollection(collectionName);
445
- if (!collection) {
446
- return;
447
- }
448
- const field = collection.getField(associationName);
449
- if (!field) {
450
- return;
451
- }
452
- if (args.length > 0) {
453
- return this.getFieldByPath(`${field == null ? void 0 : field.target}.${args.join(".")}`);
454
- }
455
- return field;
456
- }
457
- /**
458
- * get exists collection by its name
459
- * @param name
460
- */
461
- getCollection(name) {
462
- var _a;
463
- if (!name) {
464
- return null;
465
- }
466
- const [collectionName, associationName] = name.split(".");
467
- const collection = this.collections.get(collectionName);
468
- if (associationName) {
469
- const target = (_a = collection.getField(associationName)) == null ? void 0 : _a.target;
470
- return target ? this.collections.get(target) : null;
471
- }
472
- return collection;
473
- }
474
- hasCollection(name) {
475
- return !!this.getCollection(name);
476
- }
477
- removeCollection(name) {
478
- const collection = this.collections.get(name);
479
- this.emit("beforeRemoveCollection", collection);
480
- collection.resetFields();
481
- const result = this.collections.delete(name);
482
- this.sequelize.modelManager.removeModel(collection.model);
483
- if (result) {
484
- this.emit("afterRemoveCollection", collection);
485
- }
486
- return collection;
487
- }
488
- getModel(name) {
489
- return this.getCollection(name).model;
490
- }
491
- getRepository(name, relationId) {
492
- var _a, _b, _c;
493
- const [collection, relation] = name.split(".");
494
- if (relation) {
495
- return (_b = (_a = this.getRepository(collection)) == null ? void 0 : _a.relation(relation)) == null ? void 0 : _b.of(relationId);
496
- }
497
- return (_c = this.getCollection(name)) == null ? void 0 : _c.repository;
498
- }
499
- /**
500
- * @internal
501
- */
502
- addPendingField(field) {
503
- const associating = this.pendingFields;
504
- const items = this.pendingFields.get(field.target) || [];
505
- items.push(field);
506
- associating.set(field.target, items);
507
- }
508
- /**
509
- * @internal
510
- */
511
- removePendingField(field) {
512
- const items = this.pendingFields.get(field.target) || [];
513
- const index = items.indexOf(field);
514
- if (index !== -1) {
515
- delete items[index];
516
- this.pendingFields.set(field.target, items);
517
- }
518
- }
519
- registerFieldTypes(fieldTypes) {
520
- for (const [type, fieldType] of Object.entries(fieldTypes)) {
521
- this.fieldTypes.set(type, fieldType);
522
- }
523
- }
524
- registerFieldValueParsers(parsers) {
525
- for (const [type, parser] of Object.entries(parsers)) {
526
- this.fieldValueParsers.set(type, parser);
527
- }
528
- }
529
- buildFieldValueParser(field, ctx) {
530
- const Parser = field && this.fieldValueParsers.has(field.type) ? this.fieldValueParsers.get(field.type) : this.fieldValueParsers.get("default");
531
- const parser = new Parser(field, ctx);
532
- return parser;
533
- }
534
- registerModels(models) {
535
- for (const [type, schemaType] of Object.entries(models)) {
536
- this.models.set(type, schemaType);
537
- }
538
- }
539
- registerRepositories(repositories) {
540
- for (const [type, schemaType] of Object.entries(repositories)) {
541
- this.repositories.set(type, schemaType);
542
- }
543
- }
544
- /**
545
- * @internal
546
- */
547
- initOperators() {
548
- const operators = /* @__PURE__ */ new Map();
549
- for (const key in import_sequelize.Op) {
550
- operators.set("$" + key, import_sequelize.Op[key]);
551
- const val = import_sequelize.Utils.underscoredIf(key, true);
552
- operators.set("$" + val, import_sequelize.Op[key]);
553
- operators.set("$" + val.replace(/_/g, ""), import_sequelize.Op[key]);
554
- }
555
- this.operators = operators;
556
- this.registerOperators({
557
- ...import_operators.default
558
- });
559
- }
560
- registerOperators(operators) {
561
- for (const [key, operator] of Object.entries(operators)) {
562
- this.operators.set(key, operator);
563
- }
564
- }
565
- /**
566
- * @internal
567
- */
568
- buildField(options, context) {
569
- const { type } = options;
570
- const Field2 = this.fieldTypes.get(type);
571
- if (!Field2) {
572
- throw Error(`unsupported field type ${type}`);
573
- }
574
- const { collection } = context;
575
- if (options.field && collection.options.underscored && !collection.isView()) {
576
- options.field = (0, import_utils3.snakeCase)(options.field);
577
- }
578
- if (Object.prototype.hasOwnProperty.call(options, "defaultValue") && options.defaultValue === null) {
579
- delete options.defaultValue;
580
- }
581
- return new Field2(options, context);
582
- }
583
- async sync(options) {
584
- const isMySQL = this.isMySQLCompatibleDialect();
585
- if (isMySQL) {
586
- await this.sequelize.query("SET FOREIGN_KEY_CHECKS = 0", null);
587
- }
588
- if (this.options.schema && this.inDialect("postgres")) {
589
- await this.sequelize.query(`CREATE SCHEMA IF NOT EXISTS "${this.options.schema}"`, null);
590
- }
591
- const result = await this.sequelize.sync(options);
592
- if (isMySQL) {
593
- await this.sequelize.query("SET FOREIGN_KEY_CHECKS = 1", null);
594
- }
595
- return result;
596
- }
597
- async clean(options) {
598
- const { drop, ...others } = options || {};
599
- if (drop !== true) {
600
- return;
601
- }
602
- if (this.options.schema) {
603
- const tableNames = (await this.sequelize.getQueryInterface().showAllTables()).map((table) => {
604
- return `"${this.options.schema}"."${table}"`;
605
- });
606
- const skip = options.skip || [];
607
- for (const tableName of tableNames) {
608
- if (skip.includes(tableName)) {
609
- continue;
610
- }
611
- await this.sequelize.query(`DROP TABLE IF EXISTS ${tableName} CASCADE`);
612
- }
613
- return;
614
- }
615
- await this.queryInterface.dropAll(options);
616
- }
617
- async collectionExistsInDb(name, options) {
618
- const collection = this.getCollection(name);
619
- if (!collection) {
620
- return false;
621
- }
622
- return await this.queryInterface.collectionTableExists(collection, options);
623
- }
624
- isSqliteMemory() {
625
- return this.sequelize.getDialect() === "sqlite" && import_lodash.default.get(this.options, "storage") == ":memory:";
626
- }
627
- /* istanbul ignore next -- @preserve */
628
- async auth(options = {}) {
629
- const { retry = 9, ...others } = options;
630
- const startingDelay = 50;
631
- const timeMultiple = 2;
632
- let attemptNumber = 1;
633
- const authenticate = /* @__PURE__ */ __name(async () => {
634
- try {
635
- await this.sequelize.authenticate(others);
636
- this.logger.info("connection has been established successfully.", { method: "auth" });
637
- } catch (error) {
638
- this.logger.warn(`attempt ${attemptNumber}/${retry}: Unable to connect to the database: ${error.message}`, {
639
- method: "auth"
640
- });
641
- const nextDelay = startingDelay * Math.pow(timeMultiple, attemptNumber - 1);
642
- attemptNumber++;
643
- if (attemptNumber < retry) {
644
- this.logger.warn(`will retry in ${nextDelay}ms...`, { method: "auth" });
645
- }
646
- throw error;
647
- }
648
- }, "authenticate");
649
- try {
650
- await (0, import_exponential_backoff.backOff)(authenticate, {
651
- numOfAttempts: retry,
652
- startingDelay,
653
- timeMultiple
654
- });
655
- } catch (error) {
656
- throw new Error(`Unable to connect to the database`, { cause: error });
657
- }
658
- }
659
- /**
660
- * @internal
661
- */
662
- async checkVersion() {
663
- return await (0, import_helpers.checkDatabaseVersion)(this);
664
- }
665
- /**
666
- * @internal
667
- */
668
- async prepare() {
669
- if (this.isMySQLCompatibleDialect()) {
670
- const result = await this.sequelize.query(`SHOW VARIABLES LIKE 'lower_case_table_names'`, { plain: true });
671
- if ((result == null ? void 0 : result.Value) === "1" && !this.options.underscored) {
672
- throw new Error(
673
- `Your database lower_case_table_names=1, please add ${import_chalk.default.yellow("DB_UNDERSCORED=true")} to the .env file`
674
- );
675
- }
676
- }
677
- if (this.inDialect("postgres") && this.options.schema && this.options.schema != "public") {
678
- await this.sequelize.query(`CREATE SCHEMA IF NOT EXISTS "${this.options.schema}"`, null);
679
- }
680
- }
681
- async reconnect() {
682
- if (this.isSqliteMemory()) {
683
- return;
684
- }
685
- const ConnectionManager = this.sequelize.dialect.connectionManager.constructor;
686
- const connectionManager = new ConnectionManager(this.sequelize.dialect, this.sequelize);
687
- this.sequelize.dialect.connectionManager = connectionManager;
688
- this.sequelize.connectionManager = connectionManager;
689
- }
690
- closed() {
691
- return this.sequelize.connectionManager.pool._draining;
692
- }
693
- async close() {
694
- var _a, _b;
695
- if (this.isSqliteMemory()) {
696
- return;
697
- }
698
- await this.emitAsync("beforeClose", this);
699
- const closeResult = this.sequelize.close();
700
- if ((_b = (_a = this.options) == null ? void 0 : _a.customHooks) == null ? void 0 : _b["afterClose"]) {
701
- await this.options.customHooks["afterClose"](this);
702
- }
703
- return closeResult;
704
- }
705
- on(event, listener) {
706
- const type = this.modelHook.match(event);
707
- if (type && !this.modelHook.hasBoundEvent(type)) {
708
- this.sequelize.addHook(type, this.modelHook.buildSequelizeHook(type));
709
- this.modelHook.bindEvent(type);
710
- }
711
- return super.on(event, listener);
712
- }
713
- extendCollection(collectionOptions, mergeOptions) {
714
- collectionOptions = import_lodash.default.cloneDeep(collectionOptions);
715
- const collectionName = collectionOptions.name;
716
- const existCollection = this.getCollection(collectionName);
717
- if (existCollection) {
718
- existCollection.updateOptions(collectionOptions, mergeOptions);
719
- } else {
720
- const existDelayExtends = this.delayCollectionExtend.get(collectionName) || [];
721
- this.delayCollectionExtend.set(collectionName, [...existDelayExtends, { collectionOptions, mergeOptions }]);
722
- }
723
- }
724
- async import(options) {
725
- const reader = new import_collection_importer.ImporterReader(options.directory, options.extensions);
726
- const modules = await reader.read();
727
- const result = /* @__PURE__ */ new Map();
728
- for (const module2 of modules) {
729
- if (module2.extend) {
730
- this.extendCollection(module2.collectionOptions, module2.mergeOptions);
731
- } else {
732
- const collection = this.collection({
733
- ...module2,
734
- origin: options.from
735
- });
736
- result.set(collection.name, collection);
737
- }
738
- }
739
- return result;
740
- }
741
- registerCollectionType() {
742
- this.collectionFactory.registerCollectionType(import_inherited_collection.InheritedCollection, {
743
- condition: (options) => {
744
- return options.inherits && import_lodash.default.castArray(options.inherits).length > 0;
745
- }
746
- });
747
- this.collectionFactory.registerCollectionType(import_view_collection.ViewCollection, {
748
- condition: (options) => {
749
- return options.viewName || options.view;
750
- },
751
- async onSync() {
752
- return;
753
- },
754
- async onDump(dumper, collection) {
755
- try {
756
- const viewDef = await collection.db.queryInterface.viewDef(collection.getTableNameWithSchemaAsString());
757
- dumper.writeSQLContent(`view-${collection.name}`, {
758
- sql: [
759
- `DROP VIEW IF EXISTS ${collection.getTableNameWithSchemaAsString()}`,
760
- `CREATE VIEW ${collection.getTableNameWithSchemaAsString()} AS ${viewDef}`
761
- ],
762
- group: "required"
763
- });
764
- } catch (e) {
765
- return;
766
- }
767
- return;
768
- }
769
- });
770
- }
771
- };
772
- __name(_Database, "Database");
773
- let Database = _Database;
774
- function extendCollection(collectionOptions, mergeOptions) {
775
- return {
776
- collectionOptions,
777
- mergeOptions,
778
- extend: true
779
- };
780
- }
781
- __name(extendCollection, "extendCollection");
782
- const extend = extendCollection;
783
- const defineCollection = /* @__PURE__ */ __name((collectionOptions) => {
784
- return collectionOptions;
785
- }, "defineCollection");
786
- (0, import_utils.applyMixins)(Database, [import_utils.AsyncEmitter]);
787
- var database_default = Database;
788
- // Annotate the CommonJS export names for ESM import in node:
789
- 0 && (module.exports = {
790
- Database,
791
- DialectVersionAccessors,
792
- defineCollection,
793
- extend,
794
- extendCollection
795
- });