Skip to content

Commit

Permalink
fix: don't use temporary table name to create foreign key, unique, ch…
Browse files Browse the repository at this point in the history
…eck constraint with SQLite (#9185)

* fix: don't use temporary table name to create foreign key, unique, check constraint with SQLite

In migration steps, finally temporary table name is renamed to original table name. these constraints name should be created from original table name not temporary table name.

Closes: #9176

* style: remove unnecessary comment
  • Loading branch information
fossamagna committed Aug 24, 2022
1 parent 77866d8 commit e519910
Show file tree
Hide file tree
Showing 13 changed files with 416 additions and 6 deletions.
22 changes: 17 additions & 5 deletions src/driver/sqlite-abstract/AbstractSqliteQueryRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1688,7 +1688,11 @@ export abstract class AbstractSqliteQueryRunner
/**
* Builds create table sql.
*/
protected createTableSql(table: Table, createForeignKeys?: boolean): Query {
protected createTableSql(
table: Table,
createForeignKeys?: boolean,
temporaryTable?: boolean,
): Query {
const primaryColumns = table.columns.filter(
(column) => column.isPrimary,
)
Expand All @@ -1710,6 +1714,14 @@ export abstract class AbstractSqliteQueryRunner
table.name,
)} (${columnDefinitions}`

let [databaseNew, tableName] = this.splitTablePath(table.name)
const newTableName = temporaryTable
? `${databaseNew ? `${databaseNew}.` : ""}${tableName.replace(
/^temporary_/,
"",
)}`
: table.name

// need for `addColumn()` method, because it recreates table.
table.columns
.filter((column) => column.isUnique)
Expand Down Expand Up @@ -1737,7 +1749,7 @@ export abstract class AbstractSqliteQueryRunner
const uniqueName = unique.name
? unique.name
: this.connection.namingStrategy.uniqueConstraintName(
table,
newTableName,
unique.columnNames,
)
const columnNames = unique.columnNames
Expand All @@ -1756,7 +1768,7 @@ export abstract class AbstractSqliteQueryRunner
const checkName = check.name
? check.name
: this.connection.namingStrategy.checkConstraintName(
table,
newTableName,
check.expression!,
)
return `CONSTRAINT "${checkName}" CHECK (${check.expression})`
Expand Down Expand Up @@ -1786,7 +1798,7 @@ export abstract class AbstractSqliteQueryRunner
.join(", ")
if (!fk.name)
fk.name = this.connection.namingStrategy.foreignKeyName(
table,
newTableName,
fk.columnNames,
this.getTablePath(fk),
fk.referencedColumnNames,
Expand Down Expand Up @@ -1981,7 +1993,7 @@ export abstract class AbstractSqliteQueryRunner
}temporary_${tableNameNew}`

// create new table
upQueries.push(this.createTableSql(newTable, true))
upQueries.push(this.createTableSql(newTable, true, true))
downQueries.push(this.dropTableSql(newTable))

// migrate all data from the old table into new table
Expand Down
10 changes: 10 additions & 0 deletions test/github-issues/9176/entity/Author.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Column, Entity, PrimaryGeneratedColumn } from "../../../../src"

@Entity()
export class Author {
@PrimaryGeneratedColumn()
id: number

@Column()
name: string
}
22 changes: 22 additions & 0 deletions test/github-issues/9176/entity/Post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import {
Column,
Entity,
ManyToOne,
PrimaryGeneratedColumn,
} from "../../../../src"
import { Author } from "./Author"

@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number

@Column()
title: string

@Column()
text: string

@ManyToOne((type) => Author, { cascade: true, nullable: false })
author: Author
}
33 changes: 33 additions & 0 deletions test/github-issues/9176/entity/User.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import {
Check,
Column,
Entity,
PrimaryGeneratedColumn,
Unique,
} from "../../../../src"

@Entity()
@Unique(["firstName", "lastName", "middleName"])
export class User {
@PrimaryGeneratedColumn()
id: number

@Column()
firstName: string

@Column()
lastName: string

@Column()
middleName: string
}

@Entity()
@Check(`"age" > 18`)
export class CheckedUser {
@PrimaryGeneratedColumn()
id: number

@Column()
age: number
}
113 changes: 113 additions & 0 deletions test/github-issues/9176/issue-9176.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import "reflect-metadata"
import {
createTestingConnections,
closeTestingConnections,
} from "../../utils/test-utils"
import { DataSource } from "../../../src/data-source/DataSource"
import { Author } from "./entity/Author"
import { Post } from "./entity/Post"
import { CheckedUser, User } from "./entity/User"
import { CreatePostTable1656926770819 } from "./migration/1656926770819-CreatePostTable"
import { CreateAuthorTable1656939116999 } from "./migration/1656939116999-CreateAuthorTable"
import { AddAuthorIdColumn1656939646470 } from "./migration/1656939646470-AddAuthorIdColumn"
import { CreateUserTable1657066872930 } from "./migration/1657066872930-CreateUserTable"
import { CreateUniqueConstraintToUser1657067039714 } from "./migration/1657067039714-CreateUniqueConstraintToUser"
import { CreateCheckedUserTable1657067039715 } from "./migration/1657067039715-CreateCheckedUserTable"
import { CreateCheckConstraintToUser1657067039716 } from "./migration/1657067039716-CreateCheckConstraintToUser"
import { expect } from "chai"

describe("github issues > #9176 The names of foreign keys created by queryRunner.createForeignKey and schema:sync are different with SQLite", () => {
describe("github issues > #9176 foreign keys", () => {
let dataSources: DataSource[]
before(
async () =>
(dataSources = await createTestingConnections({
entities: [Author, Post],
enabledDrivers: ["sqlite"],
migrations: [
CreatePostTable1656926770819,
CreateAuthorTable1656939116999,
AddAuthorIdColumn1656939646470,
],
schemaCreate: false,
dropSchema: true,
})),
)
after(() => closeTestingConnections(dataSources))

it("should not generate queries when created foreign key with queryRunnner.createForeignKey", () =>
Promise.all(
dataSources.map(async (dataSource) => {
await dataSource.runMigrations()
const sqlInMemory = await dataSource.driver
.createSchemaBuilder()
.log()

expect(sqlInMemory.upQueries).to.empty
expect(sqlInMemory.downQueries).to.empty
}),
))
})

describe("github issues > #9176 unique constraint", () => {
let dataSources: DataSource[]
before(
async () =>
(dataSources = await createTestingConnections({
entities: [User],
enabledDrivers: ["sqlite"],
migrations: [
CreateUserTable1657066872930,
CreateUniqueConstraintToUser1657067039714,
],
schemaCreate: false,
dropSchema: true,
})),
)
after(() => closeTestingConnections(dataSources))

it("should not generate queries when created unique constraint with queryRunnner.createUniqueConstraint", () =>
Promise.all(
dataSources.map(async (dataSource) => {
await dataSource.runMigrations()
const sqlInMemory = await dataSource.driver
.createSchemaBuilder()
.log()

expect(sqlInMemory.upQueries).to.empty
expect(sqlInMemory.downQueries).to.empty
}),
))
})

describe("github issues > #9176 check constraint", () => {
let dataSources: DataSource[]
before(
async () =>
(dataSources = await createTestingConnections({
entities: [CheckedUser],
enabledDrivers: ["sqlite"],
migrations: [
CreateCheckedUserTable1657067039715,
CreateCheckConstraintToUser1657067039716,
],
schemaCreate: false,
dropSchema: true,
})),
)
after(() => closeTestingConnections(dataSources))

it("should not generate queries when created check constraint with queryRunnner.createCheckConstraint", () =>
Promise.all(
dataSources.map(async (dataSource) => {
await dataSource.runMigrations()
const sqlInMemory = await dataSource.driver
.createSchemaBuilder()
.log()

expect(sqlInMemory.upQueries).to.empty
expect(sqlInMemory.downQueries).to.empty
}),
))
})
})
35 changes: 35 additions & 0 deletions test/github-issues/9176/migration/1656926770819-CreatePostTable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { MigrationInterface, QueryRunner, Table } from "../../../../src"

export class CreatePostTable1656926770819 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: "post",
columns: [
{
name: "id",
type: "integer",
isPrimary: true,
isGenerated: true,
generationStrategy: "increment",
},
{
name: "title",
type: "varchar",
},
{
name: "text",
type: "varchar",
},
],
}),
true,
true,
true,
)
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable("post")
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { MigrationInterface, QueryRunner, Table } from "../../../../src"

export class CreateAuthorTable1656939116999 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: "author",
columns: [
{
name: "id",
type: "integer",
isPrimary: true,
isGenerated: true,
generationStrategy: "increment",
},
{
name: "name",
type: "varchar",
},
],
}),
true,
true,
true,
)
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable("author")
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import {
MigrationInterface,
QueryRunner,
TableColumn,
TableForeignKey,
} from "../../../../src"

export class AddAuthorIdColumn1656939646470 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.addColumn(
"post",
new TableColumn({
name: "authorId",
type: "integer",
}),
)
await queryRunner.createForeignKey(
"post",
new TableForeignKey({
columnNames: ["authorId"],
referencedTableName: "author",
referencedColumnNames: ["id"],
}),
)
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropForeignKey(
"post",
new TableForeignKey({
columnNames: ["authorId"],
referencedTableName: "author",
referencedColumnNames: ["id"],
}),
)
await queryRunner.dropColumn("post", "authorId")
}
}
39 changes: 39 additions & 0 deletions test/github-issues/9176/migration/1657066872930-CreateUserTable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { MigrationInterface, QueryRunner, Table } from "../../../../src"

export class CreateUserTable1657066872930 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: "user",
columns: [
{
name: "id",
type: "integer",
isPrimary: true,
isGenerated: true,
generationStrategy: "increment",
},
{
name: "firstName",
type: "varchar",
},
{
name: "lastName",
type: "varchar",
},
{
name: "middleName",
type: "varchar",
},
],
}),
true,
true,
true,
)
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable("user")
}
}

0 comments on commit e519910

Please sign in to comment.