Skip to content

Commit

Permalink
add addPrimaryKeyConstraint for AlterTableBuilder
Browse files Browse the repository at this point in the history
  • Loading branch information
n7olkachev committed Aug 7, 2023
1 parent a657787 commit a7fca74
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/schema/alter-table-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import {
import { AlterTableExecutor } from './alter-table-executor.js'
import { AlterTableAddForeignKeyConstraintBuilder } from './alter-table-add-foreign-key-constraint-builder.js'
import { AlterTableDropConstraintBuilder } from './alter-table-drop-constraint-builder.js'
import { PrimaryConstraintNode } from '../operation-node/primary-constraint-node.js'

/**
* This builder can be used to create a `alter table` query.
Expand Down Expand Up @@ -212,6 +213,23 @@ export class AlterTableBuilder implements ColumnAlteringInterface {
})
}

/**
* See {@link CreateTableBuilder.addPrimaryKeyConstraint}
*/
addPrimaryKeyConstraint(
constraintName: string,
columns: string[]
): AlterTableExecutor {
return new AlterTableExecutor({
...this.#props,
node: AlterTableNode.cloneWithTableProps(this.#props.node, {
addConstraint: AddConstraintNode.create(
PrimaryConstraintNode.create(columns, constraintName)
),
}),
})
}

dropConstraint(constraintName: string): AlterTableDropConstraintBuilder {
return new AlterTableDropConstraintBuilder({
...this.#props,
Expand Down
22 changes: 22 additions & 0 deletions test/node/src/schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2427,6 +2427,28 @@ for (const dialect of DIALECTS) {
})
})

describe('add primary key constraint', async () => {
it('should add a primary key constraint', async () => {
const builder = ctx.db.schema
.alterTable('test')
.addPrimaryKeyConstraint('test_pkey', ['integer_col'])

testSql(builder, dialect, {
postgres: {
sql: 'alter table "test" add constraint "test_pkey" primary key ("integer_col")',
parameters: [],
},
mysql: {
sql: 'alter table `test` add constraint `test_pkey` primary key (`integer_col`)',
parameters: [],
},
sqlite: NOT_SUPPORTED,
})

await builder.execute()
})
})

describe('drop constraint', () => {
it('should drop a foreign key constraint', async () => {
await ctx.db.schema.dropTable('test').execute()
Expand Down

0 comments on commit a7fca74

Please sign in to comment.