Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: on update current timestamp in MySQL #1174

Open
wants to merge 2 commits into
base: v0.28
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/schema/column-definition-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { GeneratedNode } from '../operation-node/generated-node.js'
import { DefaultValueNode } from '../operation-node/default-value-node.js'
import { parseOnModifyForeignAction } from '../parser/on-modify-action-parser.js'
import { Expression } from '../expression/expression.js'
import { RawNode } from '../operation-node/raw-node.js'

export class ColumnDefinitionBuilder implements OperationNodeSource {
readonly #node: ColumnDefinitionNode
Expand Down Expand Up @@ -239,6 +240,28 @@ export class ColumnDefinitionBuilder implements OperationNodeSource {
)
}

/**
* Adds an `ON UPDATE CURRENT_TIMESTAMP` clause to a column
*
* This clause is only supported in MySQL
*
* ### Examples
*
* ```ts
* ctx.db.schema.createTable('test')
* .addColumn('updated_at', 'datetime', (col) =>
* col.defaultTo(sql`current_timestamp`).onUpdateCurrentTimestamp(),
* )
* ```
*/
onUpdateCurrentTimestamp(): ColumnDefinitionBuilder {
return new ColumnDefinitionBuilder(
ColumnDefinitionNode.cloneWith(this.#node, {
endModifiers: [RawNode.createWithSql(`ON UPDATE CURRENT_TIMESTAMP`)],
}),
)
}

/**
* Adds a unique constraint for the column.
*
Expand Down
6 changes: 5 additions & 1 deletion test/node/src/schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,9 @@ for (const dialect of DIALECTS) {
.addColumn('u', 'char')
.addColumn('v', 'binary(16)')
.addColumn('w', 'varbinary(16)')
.addColumn('updated_at', 'datetime', (col) =>
col.defaultTo(sql`current_timestamp`).onUpdateCurrentTimestamp(),
)

testSql(builder, dialect, {
mysql: {
Expand Down Expand Up @@ -260,7 +263,8 @@ for (const dialect of DIALECTS) {
'`t` char(4),',
'`u` char,',
'`v` binary(16),',
'`w` varbinary(16))',
'`w` varbinary(16),',
'`updated_at` datetime default current_timestamp ON UPDATE CURRENT_TIMESTAMP)',
],
parameters: [],
},
Expand Down
Loading