Skip to content

Commit

Permalink
fix(mongo): skip useless unique definition for primary keys (#121)
Browse files Browse the repository at this point in the history
  • Loading branch information
Hieuzest authored Nov 6, 2024
1 parent e91dc93 commit 5d08c90
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
10 changes: 6 additions & 4 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,9 +163,10 @@ 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
fields.updateOne(meta, { $set: { virtual: useVirtualKey } }, { upsert: true })
}
if (!doc || virtual === useVirtualKey) {
// Empty table or already configured
await 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 5d08c90

Please sign in to comment.