@nocobase/database 0.20.0-alpha.9 → 0.21.0-alpha.2

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.
package/lib/collection.js CHANGED
@@ -260,9 +260,6 @@ const _Collection = class _Collection extends import_events.EventEmitter {
260
260
  `Field type conflict: cannot set "${name}" on "${this.name}" to ${options.type}, parent "${name}" type is ${oldField.options.type}`
261
261
  );
262
262
  }
263
- if (this.options.autoGenId !== false && options.primaryKey) {
264
- this.model.removeAttribute("id");
265
- }
266
263
  this.removeField(name);
267
264
  this.fields.set(name, field);
268
265
  this.emit("field.afterAdd", field);
package/lib/database.d.ts CHANGED
@@ -10,7 +10,7 @@ import { CollectionFactory } from './collection-factory';
10
10
  import { CollectionGroupManager } from './collection-group-manager';
11
11
  import { ImportFileExtension } from './collection-importer';
12
12
  import DatabaseUtils from './database-utils';
13
- import ReferencesMap from './features/ReferencesMap';
13
+ import ReferencesMap from './features/references-map';
14
14
  import { ArrayFieldRepository } from './field-repository/array-field-repository';
15
15
  import * as FieldTypes from './fields';
16
16
  import { Field, FieldContext, RelationField } from './fields';
package/lib/database.js CHANGED
@@ -52,7 +52,7 @@ var import_collection_factory = require("./collection-factory");
52
52
  var import_collection_group_manager = require("./collection-group-manager");
53
53
  var import_collection_importer = require("./collection-importer");
54
54
  var import_database_utils = __toESM(require("./database-utils"));
55
- var import_ReferencesMap = __toESM(require("./features/ReferencesMap"));
55
+ var import_references_map = __toESM(require("./features/references-map"));
56
56
  var import_referential_integrity_check = require("./features/referential-integrity-check");
57
57
  var FieldTypes = __toESM(require("./fields"));
58
58
  var import_helpers = require("./helpers");
@@ -137,7 +137,7 @@ const _Database = class _Database extends import_events.EventEmitter {
137
137
  context = {};
138
138
  queryInterface;
139
139
  utils = new import_database_utils.default(this);
140
- referenceMap = new import_ReferencesMap.default();
140
+ referenceMap = new import_references_map.default();
141
141
  inheritanceMap = new import_inherited_map.default();
142
142
  importedFrom = /* @__PURE__ */ new Map();
143
143
  modelHook;
@@ -183,7 +183,13 @@ const _Database = class _Database extends import_events.EventEmitter {
183
183
  opts.timezone = "+00:00";
184
184
  }
185
185
  if (options.dialect === "postgres") {
186
- require("pg").defaults.parseInt8 = true;
186
+ const types = require("pg").types;
187
+ types.setTypeParser(types.builtins.INT8, function(val) {
188
+ if (val <= Number.MAX_SAFE_INTEGER) {
189
+ return Number(val);
190
+ }
191
+ return val;
192
+ });
187
193
  }
188
194
  this.options = opts;
189
195
  const sequelizeOptions = this.sequelizeOptions(this.options);
@@ -21,6 +21,7 @@ __export(must_have_filter_decorator_exports, {
21
21
  default: () => must_have_filter_decorator_default
22
22
  });
23
23
  module.exports = __toCommonJS(must_have_filter_decorator_exports);
24
+ var import_utils = require("@nocobase/utils");
24
25
  const mustHaveFilter = /* @__PURE__ */ __name(() => (target, propertyKey, descriptor) => {
25
26
  const oldValue = descriptor.value;
26
27
  descriptor.value = function(...args) {
@@ -28,7 +29,7 @@ const mustHaveFilter = /* @__PURE__ */ __name(() => (target, propertyKey, descri
28
29
  if (Array.isArray(options.values)) {
29
30
  return oldValue.apply(this, args);
30
31
  }
31
- if (!(options == null ? void 0 : options.filter) && !(options == null ? void 0 : options.filterByTk) && !(options == null ? void 0 : options.forceUpdate)) {
32
+ if (!(0, import_utils.isValidFilter)(options == null ? void 0 : options.filter) && !(options == null ? void 0 : options.filterByTk) && !(options == null ? void 0 : options.forceUpdate)) {
32
33
  throw new Error(`must provide filter or filterByTk for ${propertyKey} call, or set forceUpdate to true`);
33
34
  }
34
35
  return oldValue.apply(this, args);
@@ -1,10 +1,13 @@
1
+ export type ReferencePriority = 'default' | 'user';
1
2
  export interface Reference {
2
3
  sourceCollectionName: string;
3
4
  sourceField: string;
4
5
  targetField: string;
5
6
  targetCollectionName: string;
6
7
  onDelete: string;
8
+ priority: ReferencePriority;
7
9
  }
10
+ export declare function buildReference(options: Partial<Reference>): Reference;
8
11
  declare class ReferencesMap {
9
12
  protected map: Map<string, Reference[]>;
10
13
  addReference(reference: Reference): void;
@@ -16,30 +16,56 @@ var __copyProps = (to, from, except, desc) => {
16
16
  return to;
17
17
  };
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var ReferencesMap_exports = {};
20
- __export(ReferencesMap_exports, {
21
- default: () => ReferencesMap_default
19
+ var references_map_exports = {};
20
+ __export(references_map_exports, {
21
+ buildReference: () => buildReference,
22
+ default: () => references_map_default
22
23
  });
23
- module.exports = __toCommonJS(ReferencesMap_exports);
24
+ module.exports = __toCommonJS(references_map_exports);
25
+ const DEFAULT_ON_DELETE = "NO ACTION";
26
+ function buildReference(options) {
27
+ const { sourceCollectionName, sourceField, targetField, targetCollectionName, onDelete, priority } = options;
28
+ return {
29
+ sourceCollectionName,
30
+ sourceField,
31
+ targetField,
32
+ targetCollectionName,
33
+ onDelete: (onDelete || DEFAULT_ON_DELETE).toUpperCase(),
34
+ priority: assignPriority(priority, onDelete)
35
+ };
36
+ }
37
+ __name(buildReference, "buildReference");
38
+ function assignPriority(priority, onDelete) {
39
+ if (priority) {
40
+ return priority;
41
+ }
42
+ return onDelete ? "user" : "default";
43
+ }
44
+ __name(assignPriority, "assignPriority");
45
+ const PRIORITY_MAP = {
46
+ default: 1,
47
+ user: 2
48
+ };
24
49
  const _ReferencesMap = class _ReferencesMap {
25
50
  map = /* @__PURE__ */ new Map();
26
51
  addReference(reference) {
27
- if (!reference.onDelete) {
28
- reference.onDelete = "SET NULL";
29
- }
30
- reference.onDelete = reference.onDelete.toUpperCase();
31
52
  const existReference = this.existReference(reference);
32
53
  if (existReference && existReference.onDelete !== reference.onDelete) {
33
- if (reference.onDelete === "SET NULL") {
34
- return;
35
- } else if (existReference.onDelete === "SET NULL") {
54
+ const existPriority = PRIORITY_MAP[existReference.priority];
55
+ const newPriority = PRIORITY_MAP[reference.priority];
56
+ if (newPriority > existPriority) {
36
57
  existReference.onDelete = reference.onDelete;
37
- } else {
38
- throw new Error(
39
- `On Delete Conflict, exist reference ${JSON.stringify(existReference)}, new reference ${JSON.stringify(
40
- reference
41
- )}`
42
- );
58
+ existReference.priority = reference.priority;
59
+ } else if (newPriority === existPriority && newPriority === PRIORITY_MAP["user"]) {
60
+ if (existReference.onDelete === "SET NULL" && reference.onDelete === "CASCADE") {
61
+ existReference.onDelete = reference.onDelete;
62
+ } else {
63
+ throw new Error(
64
+ `On Delete Conflict, exist reference ${JSON.stringify(existReference)}, new reference ${JSON.stringify(
65
+ reference
66
+ )}`
67
+ );
68
+ }
43
69
  }
44
70
  }
45
71
  if (!existReference) {
@@ -57,7 +83,7 @@ const _ReferencesMap = class _ReferencesMap {
57
83
  if (!references) {
58
84
  return null;
59
85
  }
60
- const keys = Object.keys(reference).filter((k) => k !== "onDelete");
86
+ const keys = Object.keys(reference).filter((k) => k !== "onDelete" && k !== "priority");
61
87
  return references.find((ref) => keys.every((key) => ref[key] === reference[key]));
62
88
  }
63
89
  removeReference(reference) {
@@ -74,4 +100,8 @@ const _ReferencesMap = class _ReferencesMap {
74
100
  };
75
101
  __name(_ReferencesMap, "ReferencesMap");
76
102
  let ReferencesMap = _ReferencesMap;
77
- var ReferencesMap_default = ReferencesMap;
103
+ var references_map_default = ReferencesMap;
104
+ // Annotate the CommonJS export names for ESM import in node:
105
+ 0 && (module.exports = {
106
+ buildReference
107
+ });
@@ -31,6 +31,9 @@ async function referentialIntegrityCheck(options) {
31
31
  }
32
32
  for (const reference of references) {
33
33
  const { sourceCollectionName, sourceField, targetField, onDelete } = reference;
34
+ if (onDelete === "NO ACTION") {
35
+ continue;
36
+ }
34
37
  const sourceCollection = db.collections.get(sourceCollectionName);
35
38
  const sourceRepository = sourceCollection.repository;
36
39
  if (sourceCollection.isView()) {
@@ -1,17 +1,11 @@
1
1
  import { BelongsToOptions as SequelizeBelongsToOptions } from 'sequelize';
2
- import { Reference } from '../features/ReferencesMap';
2
+ import { Reference, ReferencePriority } from '../features/references-map';
3
3
  import { BaseRelationFieldOptions, RelationField } from './relation-field';
4
4
  export declare class BelongsToField extends RelationField {
5
5
  static type: string;
6
6
  get dataType(): string;
7
7
  get target(): any;
8
- static toReference(db: any, association: any, onDelete: any): {
9
- sourceCollectionName: any;
10
- sourceField: any;
11
- targetField: any;
12
- targetCollectionName: any;
13
- onDelete: any;
14
- };
8
+ static toReference(db: any, association: any, onDelete: any, priority?: ReferencePriority): Reference;
15
9
  reference(association: any): Reference;
16
10
  checkAssociationKeys(): void;
17
11
  bind(): boolean;
@@ -38,6 +38,7 @@ __export(belongs_to_field_exports, {
38
38
  module.exports = __toCommonJS(belongs_to_field_exports);
39
39
  var import_lodash = __toESM(require("lodash"));
40
40
  var import_sequelize = require("sequelize");
41
+ var import_references_map = require("../features/references-map");
41
42
  var import_utils = require("../utils");
42
43
  var import_relation_field = require("./relation-field");
43
44
  const _BelongsToField = class _BelongsToField extends import_relation_field.RelationField {
@@ -48,18 +49,24 @@ const _BelongsToField = class _BelongsToField extends import_relation_field.Rela
48
49
  const { target, name } = this.options;
49
50
  return target || import_sequelize.Utils.pluralize(name);
50
51
  }
51
- static toReference(db, association, onDelete) {
52
+ static toReference(db, association, onDelete, priority = "default") {
52
53
  const targetKey = association.targetKey;
53
- return {
54
+ return (0, import_references_map.buildReference)({
54
55
  sourceCollectionName: db.modelCollection.get(association.source).name,
55
56
  sourceField: association.foreignKey,
56
57
  targetField: targetKey,
57
58
  targetCollectionName: db.modelCollection.get(association.target).name,
58
- onDelete
59
- };
59
+ onDelete,
60
+ priority
61
+ });
60
62
  }
61
63
  reference(association) {
62
- return _BelongsToField.toReference(this.database, association, this.options.onDelete);
64
+ return _BelongsToField.toReference(
65
+ this.database,
66
+ association,
67
+ this.options.onDelete,
68
+ this.options.onDelete ? "user" : "default"
69
+ );
63
70
  }
64
71
  checkAssociationKeys() {
65
72
  let { foreignKey, targetKey } = this.options;
@@ -1,5 +1,5 @@
1
1
  import { AssociationScope, BelongsToManyOptions as SequelizeBelongsToManyOptions } from 'sequelize';
2
- import { Reference } from '../features/ReferencesMap';
2
+ import { Reference } from '../features/references-map';
3
3
  import { MultipleRelationFieldOptions, RelationField } from './relation-field';
4
4
  export declare class BelongsToManyField extends RelationField {
5
5
  get dataType(): string;
@@ -41,6 +41,7 @@ const _BelongsToManyField = class _BelongsToManyField extends import_relation_fi
41
41
  references(association) {
42
42
  const db = this.context.database;
43
43
  const onDelete = this.options.onDelete || "CASCADE";
44
+ const priority = this.options.onDelete ? "user" : "default";
44
45
  const targetAssociation = association.toTarget;
45
46
  if (association.targetKey) {
46
47
  targetAssociation.targetKey = association.targetKey;
@@ -50,8 +51,8 @@ const _BelongsToManyField = class _BelongsToManyField extends import_relation_fi
50
51
  sourceAssociation.targetKey = association.sourceKey;
51
52
  }
52
53
  return [
53
- import_belongs_to_field.BelongsToField.toReference(db, targetAssociation, onDelete),
54
- import_belongs_to_field.BelongsToField.toReference(db, sourceAssociation, onDelete)
54
+ import_belongs_to_field.BelongsToField.toReference(db, targetAssociation, onDelete, priority),
55
+ import_belongs_to_field.BelongsToField.toReference(db, sourceAssociation, onDelete, priority)
55
56
  ];
56
57
  }
57
58
  checkAssociationKeys(database) {
@@ -126,9 +127,6 @@ const _BelongsToManyField = class _BelongsToManyField extends import_relation_fi
126
127
  Through = database.collection(throughCollectionOptions);
127
128
  Object.defineProperty(Through.model, "isThrough", { value: true });
128
129
  }
129
- if (!this.options.onDelete) {
130
- this.options.onDelete = "CASCADE";
131
- }
132
130
  const belongsToManyOptions = {
133
131
  constraints: false,
134
132
  ...(0, import_lodash.omit)(this.options, ["name", "type", "target"]),
@@ -1,5 +1,5 @@
1
1
  import { AssociationScope, DataType, ForeignKeyOptions, HasManyOptions, HasManyOptions as SequelizeHasManyOptions } from 'sequelize';
2
- import { Reference } from '../features/ReferencesMap';
2
+ import { Reference } from '../features/references-map';
3
3
  import { MultipleRelationFieldOptions, RelationField } from './relation-field';
4
4
  export interface HasManyFieldOptions extends HasManyOptions {
5
5
  /**
@@ -23,6 +23,7 @@ __export(has_many_field_exports, {
23
23
  module.exports = __toCommonJS(has_many_field_exports);
24
24
  var import_lodash = require("lodash");
25
25
  var import_sequelize = require("sequelize");
26
+ var import_references_map = require("../features/references-map");
26
27
  var import_utils = require("../utils");
27
28
  var import_relation_field = require("./relation-field");
28
29
  const _HasManyField = class _HasManyField extends import_relation_field.RelationField {
@@ -38,13 +39,13 @@ const _HasManyField = class _HasManyField extends import_relation_field.Relation
38
39
  }
39
40
  reference(association) {
40
41
  const sourceKey = association.sourceKey;
41
- return {
42
+ return (0, import_references_map.buildReference)({
42
43
  sourceCollectionName: this.database.modelCollection.get(association.target).name,
43
44
  sourceField: association.foreignKey,
44
45
  targetField: sourceKey,
45
46
  targetCollectionName: this.database.modelCollection.get(association.source).name,
46
47
  onDelete: this.options.onDelete
47
- };
48
+ });
48
49
  }
49
50
  checkAssociationKeys() {
50
51
  let { foreignKey, sourceKey } = this.options;
@@ -1,5 +1,5 @@
1
1
  import { AssociationScope, DataType, ForeignKeyOptions, HasOneOptions, HasOneOptions as SequelizeHasOneOptions } from 'sequelize';
2
- import { Reference } from '../features/ReferencesMap';
2
+ import { Reference } from '../features/references-map';
3
3
  import { BaseRelationFieldOptions, RelationField } from './relation-field';
4
4
  export interface HasOneFieldOptions extends HasOneOptions {
5
5
  /**
@@ -23,6 +23,7 @@ __export(has_one_field_exports, {
23
23
  module.exports = __toCommonJS(has_one_field_exports);
24
24
  var import_lodash = require("lodash");
25
25
  var import_sequelize = require("sequelize");
26
+ var import_references_map = require("../features/references-map");
26
27
  var import_utils = require("../utils");
27
28
  var import_relation_field = require("./relation-field");
28
29
  const _HasOneField = class _HasOneField extends import_relation_field.RelationField {
@@ -45,13 +46,13 @@ const _HasOneField = class _HasOneField extends import_relation_field.RelationFi
45
46
  }
46
47
  reference(association) {
47
48
  const sourceKey = association.sourceKey;
48
- return {
49
+ return (0, import_references_map.buildReference)({
49
50
  sourceCollectionName: this.database.modelCollection.get(association.target).name,
50
51
  sourceField: association.foreignKey,
51
52
  targetField: sourceKey,
52
53
  targetCollectionName: this.database.modelCollection.get(association.source).name,
53
54
  onDelete: this.options.onDelete
54
- };
55
+ });
55
56
  }
56
57
  checkAssociationKeys() {
57
58
  let { foreignKey, sourceKey } = this.options;
@@ -19,6 +19,7 @@ import { TimeFieldOptions } from './time-field';
19
19
  import { UidFieldOptions } from './uid-field';
20
20
  import { UUIDFieldOptions } from './uuid-field';
21
21
  import { VirtualFieldOptions } from './virtual-field';
22
+ import { NanoidFieldOptions } from './nanoid-field';
22
23
  export * from './array-field';
23
24
  export * from './belongs-to-field';
24
25
  export * from './belongs-to-many-field';
@@ -41,4 +42,5 @@ export * from './time-field';
41
42
  export * from './uid-field';
42
43
  export * from './uuid-field';
43
44
  export * from './virtual-field';
44
- export type FieldOptions = BaseFieldOptions | StringFieldOptions | IntegerFieldOptions | FloatFieldOptions | DecimalFieldOptions | DoubleFieldOptions | RealFieldOptions | JsonFieldOptions | JsonbFieldOptions | BooleanFieldOptions | RadioFieldOptions | SortFieldOptions | TextFieldOptions | VirtualFieldOptions | ArrayFieldOptions | SetFieldOptions | TimeFieldOptions | DateFieldOptions | UidFieldOptions | UUIDFieldOptions | PasswordFieldOptions | ContextFieldOptions | BelongsToFieldOptions | HasOneFieldOptions | HasManyFieldOptions | BelongsToManyFieldOptions;
45
+ export * from './nanoid-field';
46
+ export type FieldOptions = BaseFieldOptions | StringFieldOptions | IntegerFieldOptions | FloatFieldOptions | DecimalFieldOptions | DoubleFieldOptions | RealFieldOptions | JsonFieldOptions | JsonbFieldOptions | BooleanFieldOptions | RadioFieldOptions | SortFieldOptions | TextFieldOptions | VirtualFieldOptions | ArrayFieldOptions | SetFieldOptions | TimeFieldOptions | DateFieldOptions | UidFieldOptions | UUIDFieldOptions | NanoidFieldOptions | PasswordFieldOptions | ContextFieldOptions | BelongsToFieldOptions | HasOneFieldOptions | HasManyFieldOptions | BelongsToManyFieldOptions;
@@ -36,6 +36,7 @@ __reExport(fields_exports, require("./time-field"), module.exports);
36
36
  __reExport(fields_exports, require("./uid-field"), module.exports);
37
37
  __reExport(fields_exports, require("./uuid-field"), module.exports);
38
38
  __reExport(fields_exports, require("./virtual-field"), module.exports);
39
+ __reExport(fields_exports, require("./nanoid-field"), module.exports);
39
40
  // Annotate the CommonJS export names for ESM import in node:
40
41
  0 && (module.exports = {
41
42
  ...require("./array-field"),
@@ -59,5 +60,6 @@ __reExport(fields_exports, require("./virtual-field"), module.exports);
59
60
  ...require("./time-field"),
60
61
  ...require("./uid-field"),
61
62
  ...require("./uuid-field"),
62
- ...require("./virtual-field")
63
+ ...require("./virtual-field"),
64
+ ...require("./nanoid-field")
63
65
  });
@@ -0,0 +1,14 @@
1
+ import { DataTypes } from 'sequelize';
2
+ import { BaseColumnFieldOptions, Field } from './field';
3
+ export declare class NanoidField extends Field {
4
+ get dataType(): DataTypes.StringDataTypeConstructor;
5
+ init(): void;
6
+ bind(): void;
7
+ unbind(): void;
8
+ }
9
+ export interface NanoidFieldOptions extends BaseColumnFieldOptions {
10
+ type: 'nanoid';
11
+ size?: number;
12
+ customAlphabet?: string;
13
+ autoFill?: boolean;
14
+ }
@@ -0,0 +1,58 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var nanoid_field_exports = {};
20
+ __export(nanoid_field_exports, {
21
+ NanoidField: () => NanoidField
22
+ });
23
+ module.exports = __toCommonJS(nanoid_field_exports);
24
+ var import_sequelize = require("sequelize");
25
+ var import_field = require("./field");
26
+ var import_nanoid = require("nanoid");
27
+ const DEFAULT_SIZE = 12;
28
+ const _NanoidField = class _NanoidField extends import_field.Field {
29
+ get dataType() {
30
+ return import_sequelize.DataTypes.STRING;
31
+ }
32
+ init() {
33
+ const { name, size, customAlphabet: customAlphabetOptions, autoFill } = this.options;
34
+ this.listener = async (instance) => {
35
+ const value = instance.get(name);
36
+ if (!value && autoFill !== false) {
37
+ const nanoIdFunc = customAlphabetOptions ? (0, import_nanoid.customAlphabet)(customAlphabetOptions) : import_nanoid.nanoid;
38
+ instance.set(name, nanoIdFunc(size || DEFAULT_SIZE));
39
+ }
40
+ };
41
+ }
42
+ bind() {
43
+ super.bind();
44
+ this.on("beforeCreate", this.listener);
45
+ this.on("beforeUpdate", this.listener);
46
+ }
47
+ unbind() {
48
+ super.unbind();
49
+ this.off("beforeCreate", this.listener);
50
+ this.off("beforeUpdate", this.listener);
51
+ }
52
+ };
53
+ __name(_NanoidField, "NanoidField");
54
+ let NanoidField = _NanoidField;
55
+ // Annotate the CommonJS export names for ESM import in node:
56
+ 0 && (module.exports = {
57
+ NanoidField
58
+ });
@@ -1,9 +1,12 @@
1
1
  import { DataTypes } from 'sequelize';
2
- import { BaseColumnFieldOptions, Field, FieldContext } from './field';
2
+ import { BaseColumnFieldOptions, Field } from './field';
3
3
  export declare class UuidField extends Field {
4
- constructor(options?: any, context?: FieldContext);
5
4
  get dataType(): DataTypes.AbstractDataTypeConstructor;
5
+ init(): void;
6
+ bind(): void;
7
+ unbind(): void;
6
8
  }
7
9
  export interface UUIDFieldOptions extends BaseColumnFieldOptions {
8
10
  type: 'uuid';
11
+ autoFill?: boolean;
9
12
  }
@@ -23,19 +23,30 @@ __export(uuid_field_exports, {
23
23
  module.exports = __toCommonJS(uuid_field_exports);
24
24
  var import_sequelize = require("sequelize");
25
25
  var import_field = require("./field");
26
+ var import_uuid = require("uuid");
26
27
  const _UuidField = class _UuidField extends import_field.Field {
27
- constructor(options, context) {
28
- super(
29
- {
30
- defaultValue: import_sequelize.DataTypes.UUIDV4,
31
- ...options
32
- },
33
- context
34
- );
35
- }
36
28
  get dataType() {
37
29
  return import_sequelize.DataTypes.UUID;
38
30
  }
31
+ init() {
32
+ const { name, autoFill } = this.options;
33
+ this.listener = async (instance) => {
34
+ const value = instance.get(name);
35
+ if (!value && autoFill !== false) {
36
+ instance.set(name, (0, import_uuid.v4)());
37
+ }
38
+ };
39
+ }
40
+ bind() {
41
+ super.bind();
42
+ this.on("beforeCreate", this.listener);
43
+ this.on("beforeUpdate", this.listener);
44
+ }
45
+ unbind() {
46
+ super.unbind();
47
+ this.off("beforeCreate", this.listener);
48
+ this.off("beforeUpdate", this.listener);
49
+ }
39
50
  };
40
51
  __name(_UuidField, "UuidField");
41
52
  let UuidField = _UuidField;
package/lib/repository.js CHANGED
@@ -44,6 +44,7 @@ module.exports = __toCommonJS(repository_exports);
44
44
  var import_flat = require("flat");
45
45
  var import_lodash = __toESM(require("lodash"));
46
46
  var import_sequelize = require("sequelize");
47
+ var import_utils = require("@nocobase/utils");
47
48
  var import_must_have_filter_decorator = __toESM(require("./decorators/must-have-filter-decorator"));
48
49
  var import_target_collection_decorator = __toESM(require("./decorators/target-collection-decorator"));
49
50
  var import_transaction_decorator = require("./decorators/transaction-decorator");
@@ -469,7 +470,7 @@ const _Repository = class _Repository {
469
470
  transaction: transaction2
470
471
  });
471
472
  }
472
- if (options.filter) {
473
+ if (options.filter && (0, import_utils.isValidFilter)(options.filter)) {
473
474
  if (this.collection.model.primaryKeyAttributes.length !== 1 && !import_lodash.default.get(this.collection.options, "filterTargetKey")) {
474
475
  const queryOptions = {
475
476
  ...this.buildQueryOptions(options)
@@ -5,6 +5,7 @@ export declare class SyncRunner {
5
5
  private readonly collection;
6
6
  private readonly database;
7
7
  private tableDescMap;
8
+ private uniqueAttributes;
8
9
  constructor(model: typeof Model);
9
10
  get tableName(): string | {
10
11
  tableName: string;
@@ -17,6 +18,8 @@ export declare class SyncRunner {
17
18
  [attribute: string]: import("sequelize").ModelAttributeColumnOptions<SequelizeModel<any, any>>;
18
19
  };
19
20
  runSync(options: any): Promise<any>;
21
+ handleUniqueFieldBeforeSync(beforeColumns: any, options: any): Promise<void>;
22
+ handlePrimaryKeyBeforeSync(columns: any, options: any): Promise<void>;
20
23
  handlePrimaryKey(columns: any, options: any): Promise<void>;
21
24
  handleDefaultValues(columns: any, options: any): Promise<void>;
22
25
  handleUniqueIndex(options: any): Promise<void>;
@@ -34,6 +34,7 @@ const _SyncRunner = class _SyncRunner {
34
34
  collection;
35
35
  database;
36
36
  tableDescMap = {};
37
+ uniqueAttributes = [];
37
38
  get tableName() {
38
39
  return this.model.getTableName();
39
40
  }
@@ -68,6 +69,15 @@ const _SyncRunner = class _SyncRunner {
68
69
  }
69
70
  throw e;
70
71
  }
72
+ try {
73
+ const beforeColumns = await this.queryInterface.describeTable(this.tableName, options);
74
+ await this.handlePrimaryKeyBeforeSync(beforeColumns, options);
75
+ await this.handleUniqueFieldBeforeSync(beforeColumns, options);
76
+ } catch (e) {
77
+ if (!e.message.includes("No description found")) {
78
+ throw e;
79
+ }
80
+ }
71
81
  const syncResult = await this.performSync(options);
72
82
  const columns = await this.queryInterface.describeTable(this.tableName, options);
73
83
  await this.handlePrimaryKey(columns, options);
@@ -75,10 +85,34 @@ const _SyncRunner = class _SyncRunner {
75
85
  await this.handleUniqueIndex(options);
76
86
  return syncResult;
77
87
  }
78
- async handlePrimaryKey(columns, options) {
79
- if (!this.database.inDialect("postgres")) {
88
+ async handleUniqueFieldBeforeSync(beforeColumns, options) {
89
+ if (!this.database.inDialect("sqlite")) {
80
90
  return;
81
91
  }
92
+ const newAttributes = Object.keys(this.rawAttributes).filter((key) => {
93
+ return !Object.keys(beforeColumns).includes(this.rawAttributes[key].field) && this.rawAttributes[key].unique;
94
+ });
95
+ this.uniqueAttributes = newAttributes;
96
+ for (const newAttribute of newAttributes) {
97
+ this.rawAttributes[newAttribute].unique = false;
98
+ }
99
+ }
100
+ async handlePrimaryKeyBeforeSync(columns, options) {
101
+ const columnsBePrimaryKey = Object.keys(columns).filter((key) => {
102
+ return columns[key].primaryKey == true;
103
+ }).sort();
104
+ const columnsWillBePrimaryKey = Object.keys(this.rawAttributes).filter((key) => {
105
+ return this.rawAttributes[key].primaryKey == true;
106
+ }).map((key) => {
107
+ return this.rawAttributes[key].field;
108
+ }).sort();
109
+ if (columnsBePrimaryKey.length == 1 && !columnsWillBePrimaryKey.includes(columnsBePrimaryKey[0])) {
110
+ if (this.database.inDialect("mariadb", "mysql")) {
111
+ await this.sequelize.query(`ALTER TABLE ${this.collection.quotedTableName()} DROP PRIMARY KEY;`, options);
112
+ }
113
+ }
114
+ }
115
+ async handlePrimaryKey(columns, options) {
82
116
  try {
83
117
  const columnsBePrimaryKey = Object.keys(columns).filter((key) => {
84
118
  return columns[key].primaryKey == true;
@@ -91,18 +125,26 @@ const _SyncRunner = class _SyncRunner {
91
125
  if (columnsWillBePrimaryKey.length == 0) {
92
126
  return;
93
127
  }
94
- if (JSON.stringify(columnsBePrimaryKey) != JSON.stringify(columnsWillBePrimaryKey)) {
95
- await this.queryInterface.addConstraint(this.tableName, {
96
- type: "primary key",
97
- fields: columnsWillBePrimaryKey,
98
- name: `${this.collection.tableName()}_${columnsWillBePrimaryKey.join("_")}_pk`,
99
- transaction: options == null ? void 0 : options.transaction
100
- });
128
+ if (columnsWillBePrimaryKey.length == 1 && JSON.stringify(columnsBePrimaryKey) != JSON.stringify(columnsWillBePrimaryKey)) {
129
+ if (this.database.inDialect("mariadb", "mysql")) {
130
+ await this.sequelize.query(
131
+ `ALTER TABLE ${this.collection.quotedTableName()} ADD PRIMARY KEY (${columnsWillBePrimaryKey[0]});`,
132
+ options
133
+ );
134
+ } else {
135
+ await this.queryInterface.addConstraint(this.tableName, {
136
+ type: "primary key",
137
+ fields: columnsWillBePrimaryKey,
138
+ name: `${this.collection.tableName()}_${columnsWillBePrimaryKey.join("_")}_pk`,
139
+ transaction: options == null ? void 0 : options.transaction
140
+ });
141
+ }
101
142
  }
102
143
  } catch (e) {
103
144
  if (e.message.includes("No description found")) {
104
145
  return;
105
146
  }
147
+ throw e;
106
148
  }
107
149
  }
108
150
  async handleDefaultValues(columns, options) {
@@ -154,6 +196,9 @@ const _SyncRunner = class _SyncRunner {
154
196
  }
155
197
  }
156
198
  async handleUniqueIndex(options) {
199
+ for (const uniqueAttribute of this.uniqueAttributes) {
200
+ this.rawAttributes[uniqueAttribute].unique = true;
201
+ }
157
202
  const existsIndexes = await this.queryInterface.showIndex(this.collection.getTableNameWithSchema(), options);
158
203
  const existsUniqueIndexes = existsIndexes.filter((index) => index.unique);
159
204
  const uniqueAttributes = Object.keys(this.rawAttributes).filter((key) => {
@@ -190,7 +235,8 @@ const _SyncRunner = class _SyncRunner {
190
235
  if (!indexExists) {
191
236
  await this.queryInterface.addIndex(this.tableName, [this.rawAttributes[uniqueAttribute].field], {
192
237
  unique: true,
193
- transaction: options == null ? void 0 : options.transaction
238
+ transaction: options == null ? void 0 : options.transaction,
239
+ name: `${this.collection.tableName()}_${this.rawAttributes[uniqueAttribute].field}_uk`
194
240
  });
195
241
  }
196
242
  }
@@ -1,10 +1,10 @@
1
1
  declare const _default: {
2
2
  postgres: {
3
- 'character varying': string;
4
- varchar: string;
3
+ 'character varying': string[];
4
+ varchar: string[];
5
+ char: string[];
5
6
  character: string;
6
7
  text: string;
7
- char: string;
8
8
  oid: string;
9
9
  name: string;
10
10
  smallint: string[];
@@ -34,10 +34,10 @@ declare const _default: {
34
34
  'smallint unsigned': string[];
35
35
  'tinyint unsigned': string[];
36
36
  'mediumint unsigned': string[];
37
- char: string;
37
+ char: string[];
38
+ varchar: string[];
38
39
  date: string;
39
40
  time: string;
40
- varchar: string;
41
41
  text: string;
42
42
  longtext: string;
43
43
  int: string[];
@@ -52,10 +52,11 @@ declare const _default: {
52
52
  datetime: string;
53
53
  timestamp: string;
54
54
  json: string[];
55
+ enum: string;
55
56
  };
56
57
  sqlite: {
57
58
  text: string;
58
- varchar: string;
59
+ varchar: string[];
59
60
  integer: string;
60
61
  real: string;
61
62
  datetime: string;
@@ -72,10 +73,10 @@ declare const _default: {
72
73
  'smallint unsigned': string[];
73
74
  'tinyint unsigned': string[];
74
75
  'mediumint unsigned': string[];
75
- char: string;
76
+ char: string[];
77
+ varchar: string[];
76
78
  date: string;
77
79
  time: string;
78
- varchar: string;
79
80
  text: string;
80
81
  longtext: string;
81
82
  int: string[];
@@ -90,6 +91,7 @@ declare const _default: {
90
91
  datetime: string;
91
92
  timestamp: string;
92
93
  json: string[];
94
+ enum: string;
93
95
  };
94
96
  };
95
97
  export default _default;
@@ -21,11 +21,11 @@ __export(field_type_map_exports, {
21
21
  });
22
22
  module.exports = __toCommonJS(field_type_map_exports);
23
23
  const postgres = {
24
- "character varying": "string",
25
- varchar: "string",
24
+ "character varying": ["string", "uuid", "nanoid"],
25
+ varchar: ["string", "uuid", "nanoid"],
26
+ char: ["string", "uuid", "nanoid"],
26
27
  character: "string",
27
28
  text: "text",
28
- char: "string",
29
29
  oid: "string",
30
30
  name: "string",
31
31
  smallint: ["integer", "sort"],
@@ -46,7 +46,7 @@ const postgres = {
46
46
  path: "json",
47
47
  polygon: "json",
48
48
  circle: "json",
49
- uuid: "string"
49
+ uuid: "uuid"
50
50
  };
51
51
  const mysql = {
52
52
  smallint: ["integer", "boolean", "sort"],
@@ -55,10 +55,10 @@ const mysql = {
55
55
  "smallint unsigned": ["integer", "boolean", "sort"],
56
56
  "tinyint unsigned": ["integer", "boolean", "sort"],
57
57
  "mediumint unsigned": ["integer", "boolean", "sort"],
58
- char: "string",
58
+ char: ["string", "uuid", "nanoid"],
59
+ varchar: ["string", "uuid", "nanoid"],
59
60
  date: "date",
60
61
  time: "time",
61
- varchar: "string",
62
62
  text: "text",
63
63
  longtext: "text",
64
64
  int: ["integer", "sort"],
@@ -72,11 +72,12 @@ const mysql = {
72
72
  decimal: "decimal",
73
73
  datetime: "date",
74
74
  timestamp: "date",
75
- json: ["json", "array"]
75
+ json: ["json", "array"],
76
+ enum: "string"
76
77
  };
77
78
  const sqlite = {
78
79
  text: "text",
79
- varchar: "string",
80
+ varchar: ["string", "uuid", "nanoid"],
80
81
  integer: "integer",
81
82
  real: "real",
82
83
  datetime: "date",
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@nocobase/database",
3
- "version": "0.20.0-alpha.9",
3
+ "version": "0.21.0-alpha.2",
4
4
  "description": "",
5
5
  "main": "./lib/index.js",
6
6
  "types": "./lib/index.d.ts",
7
7
  "license": "Apache-2.0",
8
8
  "dependencies": {
9
- "@nocobase/logger": "0.20.0-alpha.9",
10
- "@nocobase/utils": "0.20.0-alpha.9",
9
+ "@nocobase/logger": "0.21.0-alpha.2",
10
+ "@nocobase/utils": "0.21.0-alpha.2",
11
11
  "async-mutex": "^0.3.2",
12
12
  "chalk": "^4.1.1",
13
13
  "cron-parser": "4.4.0",
@@ -25,7 +25,8 @@
25
25
  "qs": "^6.11.2",
26
26
  "semver": "^7.3.7",
27
27
  "sequelize": "^6.26.0",
28
- "umzug": "^3.1.1"
28
+ "umzug": "^3.1.1",
29
+ "uuid": "^9.0.1"
29
30
  },
30
31
  "devDependencies": {
31
32
  "@types/glob": "^7.2.0"
@@ -35,5 +36,5 @@
35
36
  "url": "git+https://github.com/nocobase/nocobase.git",
36
37
  "directory": "packages/database"
37
38
  },
38
- "gitHead": "5473d9039cfdb649a8c8c625edefc9a3ac464be5"
39
+ "gitHead": "90628f2e2da846208fb2d7966ddb4e467d187ffb"
39
40
  }