typeorm: TypeORM Attempts to create tables that already exist

Issue type:

[ ] question [x ] bug report [ ] feature request [ ] documentation issue

Database system/driver:

[ ] cordova [ ] mongodb [x ] mssql [ ] mysql / mariadb [ ] oracle [ ] postgres [ ] sqlite [ ] sqljs [ ] react-native [ ] expo

TypeORM version:

[ x] latest [ ] @next [ ] 0.x.x (or put your version here)

Steps to reproduce or a small repository showing the problem:

If I delete all the tables in my database and run my app, all tables are created successfully. If I then stop the app and restart it, typeorm attempts to create tables that already exist and then fails.

Here is the output from TypeOrm for the second run: image

Here is the beginning of the definition for the EmployeeAvailabilities table (there are more columns than this):

@Entity('EmployeeAvailabilities', {schema: 'dbo'})
@Index('IX_EmployeeId', ['employee'])
export class EmployeeAvailability {

    @PrimaryGeneratedColumn({

        name: 'EmployeeAvailabilityId',
    })
    public employeeAvailabilityId: number;

    @ManyToOne(() => Employee, (employee: Employee) => employee.employeeAvailabilitiess, {  nullable: false, onDelete: 'CASCADE' })
    @JoinColumn({ name: 'EmployeeId'})
    public employee: Employee | null;
}

At first I thought the issue was because the class name and table name do not match. But if I make the class name and table name match, the issue still occurs.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 8
  • Comments: 41 (2 by maintainers)

Most upvoted comments

As mentioned in #4420, using lowercase only in table names fixed this for me.

edit: Oh and I only had this issue on Windows, not mac!

Check if you have synchronize connection option set to true. I think it shouldn’t be set to true for the second time

数据库的表 不能大写,大写就出现如上报错,改成小写就可以了,亲测有效,折腾了一天,午觉都睡不着。

@mosilver Yep with NestJS TypeORM module its doing the same for me

I had the same problem but using Nativescript-sqlite with a simplem connection:

console.log('Creating Connection')

const connection = await createConnection({
    name: 'default',
    database: 'synchrony.db',
    type: 'nativescript',
    driver,
    entities: [
        PushNotification,
        Slide,
        SlideImage,
        UserProgressInfo,
        UserSynchronizationChartData,
        UserPodcastHistory,
        UserRecent,
        Session,
        User,
        Country,
        CountryName,
        Podcast,
        Practice,
        Audio,
        Mentor,
        ProgramType,
        Program,
        ProgramsGroup,
        MentorsGroup,
        Category,
        FAQ,
        Tag,
        Membership,
    ],
    // logging: this.config.debug,
    // synchronize: this.config.debug
})

console.log("Connection Created!")

// setting true will drop tables and recreate
await connection.synchronize(false)

The first time the app runs everything goes fine, but the second time this code runs it throws:

JS: QueryFailedError: android.database.sqlite.SQLiteException: table "push_notification" already exists (code 1): , while compiling: CREATE TABLE "push_notification" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar NOT NULL, "body" varchar NOT NULL, "timestamp" datetime NOT NULL, "type" varchar NOT NULL, "action" varchar)
JS:     android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
JS:     android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
JS:     android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
JS:     android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
JS:     android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
JS:     android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
JS:     android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
JS:     android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1318)
JS:     android.database.sqlite.SQL...

But the database and the app runs without any problem, is like the driver is not running some query check for know if the tables already exists before running a create query.

I don’t know if this is sufficient for creating a new issue like @pleerock points.

I had this problem, it appears TypeOrm doesn’t like table name with any capitalization

solution: USE LOWERCASE name for your table name. worked for me

My issue was related to this setting in ormconfig:

  • synchronize: true
  • migrationsRun: true

You should only set it to true on one of them, but not on both

I have the same problem as op (same driver), I noticed that typeorm fails to check if the table exists only when ‘schema’ is defined in the entity. In my case using lowercase only did not fix it.

I am also experiencing this issue. My “synchronize” is set to true. It seems like too much work to have to set this one setting to false if the app has already run once before.

migrationsRun: true this works for me on windows

{
//...
database: 'viewModal',
}

to

{
//...
database: 'view_modal', //not 'viewModal',
}

it works in my project

Setting lower_case_table_names to 1 in my.cnf doens’t help at all. Only fails on mac, by the way, but I cannot name my tables with only lowercase either. Any solution so far?

For me lowercase works uppercase dousn’t work

Guys please provide simple schema on which this bug occurs. I will look into it but need complete schema definition. If possible make it as a PR with failing test or paste schema here.

Example of how to make such test easily in #3257 - just need to change entities and description.

错误的写法(wrong spelling),注意database,这里我使用了大写(大驼峰命名法)。这时候就会出现数据表重复创建的情况。

 TypeOrmModule.forRoot({
      type:'mysql',          
      host:'localhost',      
      port:3306,   
      database:'HongLangMan',           
     //.......  
    }),

正确的写法(correct spelling):database项全部使用了小写

 TypeOrmModule.forRoot({
      type:'mysql',          
      host:'localhost',      
      port:3306,   
      database:'honglangman',           
     //.......  
    }),
```,

In my case I have removed node_modules directory, dist directory, and package.json file from my project. Then I run npm install and run using ts-node -p <path_to_your_project> && ts-node dist/<path_to_main_file(like index.js/server.js)> i.e. ts-node -p . && ts-node dist/server.js. After that everything goes fine!

I am having same issue

@Entity("User") <-- this does not work

but

@Entity("user") <-- this works

with capital case and synchronize on it throws error table already exists

I had both package @nestjs/typeorm and typeorm installed in my project.

I removed typeorm from it and now is working without a problem