From 9f2ef4e32af7be8d8b6b897b4c7d9adf43ad41d1 Mon Sep 17 00:00:00 2001 From: adamcikado Date: Sat, 27 Jan 2024 10:29:40 +0100 Subject: [PATCH] fix: compare DateTime in newUpIfMissing --- src/orm/base_model/index.ts | 15 +++++++-- test/orm/base_model.spec.ts | 65 +++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 3 deletions(-) diff --git a/src/orm/base_model/index.ts b/src/orm/base_model/index.ts index 1efbce2d..7b722afb 100644 --- a/src/orm/base_model/index.ts +++ b/src/orm/base_model/index.ts @@ -207,9 +207,18 @@ class BaseModelImpl implements LucidRow { * array */ return rowObjects.map((rowObject: any) => { - const existingRow = existingRows.find((one: any) => { - /* eslint-disable-next-line eqeqeq */ - return keys.every((key) => one[key] == rowObject[key]) + const existingRow = existingRows.find((row: any) => { + return keys.every((key) => { + const objectValue = rowObject[key] + const rowValue = row[key] + + if (DateTime.isDateTime(rowValue) && DateTime.isDateTime(objectValue)) { + return rowValue.equals(objectValue) + } + + /* eslint-disable-next-line eqeqeq */ + return rowValue == objectValue + }) }) /** diff --git a/test/orm/base_model.spec.ts b/test/orm/base_model.spec.ts index 205c4b1b..18f71718 100644 --- a/test/orm/base_model.spec.ts +++ b/test/orm/base_model.spec.ts @@ -4888,6 +4888,71 @@ test.group('Base Model | fetch', (group) => { assert.lengthOf(usersList, 1) assert.equal(usersList[0].points, 2) }) + + test('updateOrCreateMany should work with DateTime', async ({ fs, assert }) => { + const app = new AppFactory().create(fs.baseUrl, () => {}) + await app.init() + const db = getDb() + const adapter = ormAdapter(db) + + const BaseModel = getBaseModel(adapter) + + class User extends BaseModel { + @column({ isPrimary: true }) + declare id: number + + @column() + declare username: string + + @column() + declare email: string + + @column.dateTime() + declare createdAt: DateTime + } + + const createdAt1 = DateTime.now().minus({ days: 2 }) + const createdAt2 = DateTime.now().minus({ days: 1 }) + + await db + .insertQuery() + .table('users') + .multiInsert([ + { + username: 'virk1', + email: 'virk+1@adonisjs.com', + created_at: createdAt1, + }, + { + username: 'virk2', + email: 'virk+2@adonisjs.com', + created_at: createdAt2, + }, + ]) + + const users = await User.updateOrCreateMany('createdAt', [ + { + username: 'virk3', + email: 'virk+3@adonisjs.com', + createdAt: createdAt1, + }, + { + username: 'nikk', + email: 'nikk@adonisjs.com', + createdAt: DateTime.now(), + }, + ]) + + assert.lengthOf(users, 2) + assert.isTrue(users[0].$isPersisted) + assert.isFalse(users[0].$isLocal) + + assert.isTrue(users[1].$isPersisted) + assert.isTrue(users[1].$isLocal) + + const usersList = await db.query().from('users') + assert.lengthOf(usersList, 3) + }) }) test.group('Base Model | hooks', (group) => {