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

时间:2018-10-23 11:57:14

标签: angularjs typescript ionic-framework typeorm

Typeorm 0.2.8

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

这是一个错误吗? sqljs驱动程序特有的内容?还是我错过了一些明显而简单的事情?

实体

@Entity()
export class MyEntity {

    @PrimaryGeneratedColumn()
    id:number;

    @Column()
    name:string;

    @CreateDateColumn()
    createdAt:string;
}

迁移

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');
    }
}

数据库提供程序

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);
    }
}

应用程序组件

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
            });
    }
}

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

INSERT INTO "my_entity"("name", "createdAt") VALUES (?, datetime('now'))

控制台中显示以下错误:

ERROR Error: Uncaught (in promise): QueryFailedError: NOT NULL constraint failed: my_entity.id

更新1

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

{
    name: 'id',
    type: 'int',
    isPrimary: true,
    isGenerated: true
}

更新2

好的,我修复了它。 @PrimaryGeneratedColumn的迁移配置似乎非常具体。对于其他遇到此问题的人,这已为我解决:

{
    name: 'id',
    type: 'integer', // instead of 'int', required for the increment strategy
    isPrimary: true,
    isGenerated: true,
    generationStrategy: 'increment' // thought this was the default
}

1 个答案:

答案 0 :(得分:1)

好的,我修复了它。 @PrimaryGeneratedColumn的迁移配置似乎非常具体。对于其他遇到此问题的人,这已为我解决:

{
    name: 'id',
    type: 'integer', // instead of 'int', required for the increment strategy
    isPrimary: true,
    isGenerated: true,
    generationStrategy: 'increment' // thought this was the default
}