Skip to content

Commit

Permalink
🐛 Use field path when creating index names instead of field names
Browse files Browse the repository at this point in the history
  • Loading branch information
skerit committed Feb 19, 2024
1 parent 6611763 commit 8b38843
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 15 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
## 1.4.0-alpha.2 (WIP)

* Drop the correct already-existing index when trying to create a similar one
* Use field path when creating index names instead of field names

## 1.4.0-alpha.1 (2024-02-15)

Expand Down
47 changes: 32 additions & 15 deletions lib/class/schema_client.js
Original file line number Diff line number Diff line change
Expand Up @@ -1041,7 +1041,7 @@ Schema.setMethod(function getFieldNames() {
*
* @author Jelle De Loecker <[email protected]>
* @since 0.2.0
* @version 1.3.17
* @version 1.4.0
*
* @param {string|FieldType} _field
* @param {Object} options
Expand Down Expand Up @@ -1073,13 +1073,33 @@ Schema.setMethod(function addIndex(_field, _options) {
// Set the default options
options = Object.assign({}, this.indexOptions, options);

if (options.name == null) {
options.name = field.name;
const setIndexName = () => {

if (options.unique) {
options.name += '_uq';
if (options.name) {
return;
}

if (!this.model_name) {
return;
}

if (options.name == null) {
options.name = field.path;

if (options.unique) {
options.name += '_uq';
}
}
}

if (this.indexes[options.name] == null) {
// Create the index group if it doesn't exist yet.
// The first time it's called will define the group options.
this.indexes[options.name] = {
fields: {},
options: options
};
}
};

if (typeof options.order == 'number') {
if (options.order == 'asc') {
Expand All @@ -1089,22 +1109,16 @@ Schema.setMethod(function addIndex(_field, _options) {
}
}

if (this.indexes[options.name] == null) {
// Create the index group if it doesn't exist yet.
// The first time it's called will define the group options.
this.indexes[options.name] = {
fields: {},
options: options
};
}

// Even if an index is unique,
// it needs the 'alternate' property in order to be used
// as an alternate method of updating without _id
if (options.alternate) {
this.has_alternates++;
}

// Try to set the index name now, if possible
setIndexName();

const that = this;

that.getDatasource().done(function gotDs(err, datasource) {
Expand All @@ -1123,6 +1137,9 @@ Schema.setMethod(function addIndex(_field, _options) {
return alchemy.printLog('error', ['Unable to ensure index on this datasource', options.name], {err: new Error()});
}

// Try to set the index name again, if it hasn't been done yet
setIndexName();

let path = field.path;

if (options.db_property) {
Expand Down

0 comments on commit 8b38843

Please sign in to comment.