drizzle-team / drizzle-team/drizzle-orm

[BUG]: Prepared statements always send the same default value

Open
#1,588 5 comments 1 reaction 0 assignees View on GitHub
bug
Dominant language
TypeScript
Stars
35.8k
Forks
1.6k
Avg merge
2d 7h
Merged PRs (30d)
4

Description

### What version of `drizzle-orm` are you using?

0.29.0

### What version of `drizzle-kit` are you using?

0.20.4

### Describe the Bug

I'm not 100% if this is a bug or if it's by design, but for me it was quite unexpected:

If I have a prepared statement with some placeholders, and one column has a `$default` fn, Drizzle runs the `fn` only once when creating the SQL binary, instead of creating a placeholder for the column and executing the function every time `run`, `get`, `all` etc are called.

It seems to me that `$default` / `$defaultFn` should behave like placeholders, otherwise I can't really use prepared statements for eg creating new ids, unless I manually use a placeholder and pass the value.

1. Create a schema with `$default`, eg:
```ts
import { createId } from '@paralleldrive/cuid2'
import { sqliteTable, text } from 'drizzle-orm/sqlite-core'

export const user = sqliteTable('user', {
id: text('id').notNull().$default(createId).primaryKey(),
email: text('email').notNull().unique(),
name: text('name').notNull(),
createdAt: text('created_at').notNull().$default(() => new Date().toISOString()),
updatedAt: text('updated_at').notNull().$default(() => new Date().toISOString()),
})
```
2. Create a prepared statement for inserting a row, eg:
```ts
const upsertUserStatement = db
.insert(user)
.values({
email: sql.placeholder('email'),
name: sql.placeholder('name'),
})
.prepare()
```
3. Call this statement with different values, eg:
```ts
upsertUserStatement.run({ email: 'john.doe@email.com', name: 'John Doe' })
upsertUserStatement.run({ email: 'jane.doe@email.com', name: 'Jane Doe' })
```

### Expected behavior

My expected behavior: two users should be created with different ids and different dates.
What actually happened: first user is created and second one gives a UNIQUE CONSTRAINT error, `user.id`.

### Environment & setup

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.