保存实体 PrimaryGenelatedColumn 值时未生成,给出 NOT NULL 约束错误

Wim*_*ets 2 angularjs typescript ionic-framework typeorm

类型0.2.8

我正在构建一个适用于移动使用和浏览器 (PWA) 使用的 Ionic 应用程序。下面是我的项目中的一些简短代码。我使用 a 创建一个简单的实体PrimaryGeneratedColumn并尝试插入一个实例。这会生成有关主列为 的错误NULL。“生成”这个词不是意味着生成列值吗?

这是一个错误吗?司机有什么具体的事情sqljs吗?或者我错过了一些明显而简单的事情?

实体

@Entity()
export class MyEntity {

    @PrimaryGeneratedColumn()
    id:number;

    @Column()
    name:string;

    @CreateDateColumn()
    createdAt:string;
}
Run Code Online (Sandbox Code Playgroud)

移民

export class Migration20181022133900 implements MigrationInterface {

    async up(queryRunner: QueryRunner): Promise<any> {
        await queryRunner.createTable(new Table({
            name: 'my_entity',
            columns: [
                {
                    name: 'id',
                    type: 'int',
                    isPrimary: true,
                    isGenerated: true
                },
                {
                    name: 'name',
                    type: 'varchar'
                },
                {
                    name: 'createdAt',
                    type: 'timestamp',
                    'default': 'now()'
                }
            ]
        }), true);
    }

    async down(queryRunner: QueryRunner): Promise<any> {
        await queryRunner.dropTable('my_entity');
    }
}
Run Code Online (Sandbox Code Playgroud)

数据库提供商

const DATABASE_SHARED_OPTIONS:Partial<ConnectionOptions> = {
    entities: [
        MyEntity
    ],
    logging: 'all',
    logger: new DatabaseLogger(),
    migrationsRun: true,
    migrations: [
        Migration20181022133900
    ]
};
@Injectable()
export class Database {

    constructor(public platform:Platform) {}

    setup(): Promise<Connection> {
        let options: CordovaConnectionOptions | SqljsConnectionOptions;

        // Mobile app
        if (this.platform.is('cordova')) {
            options = {
                type: 'cordova',
                database: 'my_project.db',
                location: 'default',
            };
            options = Object.assign(options, DATABASE_SHARED_OPTIONS);
        }

        // Browser PWA app
        else {
            options = {
                type: 'sqljs',
                autoSave: true,
                location: 'my_project',
            };
            options = Object.assign(options, DATABASE_SHARED_OPTIONS);
        }

        return createConnection(options);
    }
}
Run Code Online (Sandbox Code Playgroud)

应用程序组件

export class MyApp {

    constructor(
        platform: Platform,
        database: Database
    ) {
      platform.ready().then(() => {
        database.setup()
            .then((connection) => {
                  this.insertTest();
            });
      });
    }

    insertTest() {
        const myEntity= new MyEntity();
        myEntity.name = 'foo';
        getRepository(MyEntity).save(myEntity)
            .then((data) => {
                  console.log(data); // never reached due to error
            });
    }
}
Run Code Online (Sandbox Code Playgroud)

数据库日志显示以下查询(带参数["foo"]):

INSERT INTO "my_entity"("name", "createdAt") VALUES (?, datetime('now'))
Run Code Online (Sandbox Code Playgroud)

我的控制台中显示以下错误:

ERROR Error: Uncaught (in promise): QueryFailedError: NOT NULL constraint failed: my_entity.id
Run Code Online (Sandbox Code Playgroud)

更新1

它似乎只在使用迁移时给出错误。删除迁移并使用synchronize: true数据库设置可以工作并id为实体生成一个。那么我的迁移代码中的列定义有问题吗?

{
    name: 'id',
    type: 'int',
    isPrimary: true,
    isGenerated: true
}
Run Code Online (Sandbox Code Playgroud)

更新2

好的,我修好了。a 的迁移配置@PrimaryGeneratedColumn似乎非常具体。对于其他面临此问题的人来说,这为我解决了这个问题:

{
    name: 'id',
    type: 'integer', // instead of 'int', required for the increment strategy
    isPrimary: true,
    isGenerated: true,
    generationStrategy: 'increment' // thought this was the default
}
Run Code Online (Sandbox Code Playgroud)

Wim*_*ets 7

好的,我修好了。a 的迁移配置@PrimaryGeneratedColumn似乎非常具体。对于其他面临此问题的人来说,这为我解决了这个问题:

{
    name: 'id',
    type: 'integer', // instead of 'int', required for the increment strategy
    isPrimary: true,
    isGenerated: true,
    generationStrategy: 'increment' // thought this was the default
}
Run Code Online (Sandbox Code Playgroud)