Skip to content

Commit

Permalink
fix: compare DateTime in newUpIfMissing
Browse files Browse the repository at this point in the history
  • Loading branch information
adamcikado committed Jan 27, 2024
1 parent 42b46f3 commit 9f2ef4e
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/orm/base_model/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
})
})

/**
Expand Down
65 changes: 65 additions & 0 deletions test/orm/base_model.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: '[email protected]',
created_at: createdAt1,
},
{
username: 'virk2',
email: '[email protected]',
created_at: createdAt2,
},
])

const users = await User.updateOrCreateMany('createdAt', [
{
username: 'virk3',
email: '[email protected]',
createdAt: createdAt1,
},
{
username: 'nikk',
email: '[email protected]',
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) => {
Expand Down

0 comments on commit 9f2ef4e

Please sign in to comment.