Skip to content

Commit

Permalink
fix(mongo): skip useless unique definition for primary keys
Browse files Browse the repository at this point in the history
  • Loading branch information
Hieuzest committed Nov 6, 2024
1 parent e91dc93 commit 741697f
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 3 deletions.
8 changes: 5 additions & 3 deletions packages/mongo/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { BSONType, ClientSession, Collection, Db, IndexDescription, Long, MongoClient, MongoClientOptions, MongoError, ObjectId } from 'mongodb'
import { Binary, Dict, isNullable, makeArray, mapValues, noop, omit, pick } from 'cosmokit'
import { Binary, deepEqual, Dict, isNullable, makeArray, mapValues, noop, omit, pick } from 'cosmokit'
import { Driver, Eval, executeUpdate, Field, hasSubquery, Query, RuntimeError, Selection, z } from 'minato'
import { URLSearchParams } from 'url'
import { Builder } from './builder'
Expand Down Expand Up @@ -99,6 +99,7 @@ export class MongoDriver extends Driver<MongoDriver.Config> {

// if the index is already created, skip it
keys = makeArray(keys)
if (index && deepEqual(keys, makeArray(primary))) return
const name = (index ? 'unique:' : 'primary:') + keys.join('+')
if (oldSpecs.find(spec => spec.name === name)) return

Expand Down Expand Up @@ -162,8 +163,9 @@ export class MongoDriver extends Driver<MongoDriver.Config> {
const doc = await this.db.collection(table).findOne()
if (doc) {
virtual = typeof doc._id !== 'object' || (typeof primary === 'string' && modelFields[primary]?.deftype === 'primary')
} else {
// Empty collection, just set meta and return
}
if (!doc || virtual === useVirtualKey) {
// Empty table or already configured
fields.updateOne(meta, { $set: { virtual: useVirtualKey } }, { upsert: true })
this.logger.info('Successfully reconfigured table %s', table)
return
Expand Down
1 change: 1 addition & 0 deletions packages/mongo/tests/migration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ describe('@minatojs/driver-mongo/migrate-virtualKey', () => {
regex: 'string',
}, {
autoInc: true,
unique: ['id'],
})

const table: Foo[] = []
Expand Down

0 comments on commit 741697f

Please sign in to comment.