Typeorm 列类型依赖于数据库

svo*_*l13 6 mysql sqlite node.js typescript typeorm

我有简单的实体

@Entity()
export class File {
    @PrimaryGeneratedColumn()
    id: number;
    @Column({type: "mediumblob"})
    data: Buffer;
}
Run Code Online (Sandbox Code Playgroud)

我想在 Mysql 的生产中使用它(“mediumblob”,因为我想存储 10MB 文件)。

我也想运行集成测试,sqlite但它只支持“blob”。

然后我想要这样的测试:

describe("CR on File and blobs", () => {
    it("should store arbitrary binary file", async (done) => {
        const conn = await createConnection({
            type: "sqlite",
            database: ":memory:",
            entities: ["src/models/file.ts"],
            synchronize: true
        });
        const fileRepo = await conn.getRepository(File);
        fileRepo.createQueryBuilder("file")
            .where("file.id == :id", {id: 1})
            .select([
                "file.data"
            ])
            .stream();
        done();
    });
});
Run Code Online (Sandbox Code Playgroud)

当我运行这样的代码时,我得到这样的错误 DataTypeNotSupportedError: Data type "mediumblob" in "File.data" is not supported by "sqlite" database.

如果我将列类型更改为blobthenmysql上传116kb文件 时出现以下错误QueryFailedError: ER_DATA_TOO_LONG: Data too long for column 'data' at row 1

是否有可能以某种方式生成某种逻辑/映射来解决mysql/ sqliteso "blob"is used for sqlitewhile "mediumblob"is used for 的不兼容性mysql

Hun*_*ran 10

我们可以在@Column 之上创建一个简单的装饰器@DbAwareColumn。新装饰器根据环境更正列类型。我希望您在测试环境中使用 sqlite

import { Column, ColumnOptions, ColumnType } from 'typeorm';

const mysqlSqliteTypeMapping: { [key: string]: ColumnType } = {
  'mediumtext': 'text',
  'timestamp': 'datetime',
  'mediumblob': 'blob'
};

export function resolveDbType(mySqlType: ColumnType): ColumnType {
  const isTestEnv = process.env.NODE_ENV === 'test';
  if (isTestEnv && mySqlType in mysqlSqliteTypeMapping) {
    return mysqlSqliteTypeMapping[mySqlType.toString()];
  }
  return mySqlType;
}

export function DbAwareColumn(columnOptions: ColumnOptions) {
  if (columnOptions.type) {
    columnOptions.type = resolveDbType(columnOptions.type);
  }
  return Column(columnOptions);
}
Run Code Online (Sandbox Code Playgroud)

在实体中,我们可以将其用作

@Entity({name: 'document'})
export class Document {

  @DbAwareColumn({ name: 'body', type: 'mediumtext'})
  body: string;

  @DbAwareColumn({type: "mediumblob"})
  data: Buffer;

  @DbAwareColumn({type: "timestamp"})
  createdAt: Date;
}

Run Code Online (Sandbox Code Playgroud)