sqlite 迁移未在使用Capacitor的Ionic和Vue上的TypeORM上注册

ghhaqwfi  于 2023-08-06  发布在  SQLite
关注(0)|答案(2)|浏览(98)

我正在使用capacitor-sqlite plugin创建一个Ionic5应用程序(使用Vue3)。我也在尝试使用TypeORM在所有这些之上。
我可以使用capacitor连接到sqlite数据库,但由于某种原因,迁移似乎根本没有注册,并且总是以空数组的形式出现,代码如下:

// App.vue

import {createConnection} from "typeorm";
import {CapacitorSQLite, SQLiteConnection} from "@capacitor-community/sqlite";

onBeforeMount(async () => {
    const sqlite = new SQLiteConnection(CapacitorSQLite);
    createConnection({
        type: 'capacitor',
        driver: sqlite,
        database: 'mydrivetime',
        synchronize: false,
        migrationsRun: false,
        logging: true,
        entities: [
            "User"
        ],
        migrations: [
            "1626771964722-UserCreate"
        ],
    }).then(async connection => {

        console.log('migrations', connection.migrations);
        console.log('isConnected', connection.isConnected);

        connection.runMigrations()
          .then(() => {
            console.log("migrations successful");
          }).catch(error => console.log(JSON.stringify(error)));

    });
});

字符串
即使我在同一路径上进行了迁移设置,也会得到以下输出:

⚡️  [log] - migrations []
⚡️  [log] - isConnected true
⚡️  [log] - migrations successful


这是我在与App.vue相同的路径中的迁移文件。我也试着把它放在一个单独的文件夹,并试图glob它,但没有运气。

import {MigrationInterface, QueryRunner} from "typeorm";

export class UserCreate1626771964722 implements MigrationInterface {

    public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(`
            CREATE TABLE "user" (
                "id" integer PRIMARY KEY AUTOINCREMENT NOT NULL,
                "firstName" varchar NOT NULL,
                "age" integer NOT NULL
            )
        `);
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(`
            DROP TABLE "user"
        `);
    }

}


我没有任何其他地方的其他设置,我不知道为什么迁移(或实体)没有得到注册。下面是connection对象的完整console.log

{
    "migrations": [],
    "subscribers": [],
    "entityMetadatas": [],
    "name": "default",
    "options": {
        "type": "capacitor",
        "driver": {
            "sqlite": {},
            "_connectionDict": {}
        },
        "database": "mydrivetime",
        "synchronize": false,
        "migrationsRun": false,
        "logging": true,
        "entities": [
            "User"
        ],
        "migrations": [
            "1626771964722-UserCreate"
        ]
    },
    "logger": {
        "options": true
    },
    "driver": {
        "isReplicated": false,
        "treeSupport": true,
        "supportedDataTypes": [
            "int",
            "integer",
            "tinyint",
            "smallint",
            "mediumint",
            "bigint",
            "unsigned big int",
            "int2",
            "int8",
            "integer",
            "character",
            "varchar",
            "varying character",
            "nchar",
            "native character",
            "nvarchar",
            "text",
            "clob",
            "text",
            "blob",
            "real",
            "double",
            "double precision",
            "float",
            "real",
            "numeric",
            "decimal",
            "boolean",
            "date",
            "time",
            "datetime"
        ],
        "withLengthColumnTypes": [
            "character",
            "varchar",
            "varying character",
            "nchar",
            "native character",
            "nvarchar",
            "text",
            "blob",
            "clob"
        ],
        "spatialTypes": [],
        "withPrecisionColumnTypes": [
            "real",
            "double",
            "double precision",
            "float",
            "real",
            "numeric",
            "decimal",
            "date",
            "time",
            "datetime"
        ],
        "withScaleColumnTypes": [
            "real",
            "double",
            "double precision",
            "float",
            "real",
            "numeric",
            "decimal"
        ],
        "mappedDataTypes": {
            "createDate": "datetime",
            "createDateDefault": "datetime('now')",
            "updateDate": "datetime",
            "updateDateDefault": "datetime('now')",
            "deleteDate": "datetime",
            "deleteDateNullable": true,
            "version": "integer",
            "treeLevel": "integer",
            "migrationId": "integer",
            "migrationName": "varchar",
            "migrationTimestamp": "bigint",
            "cacheId": "int",
            "cacheIdentifier": "varchar",
            "cacheTime": "bigint",
            "cacheDuration": "int",
            "cacheQuery": "text",
            "cacheResult": "text",
            "metadataType": "varchar",
            "metadataDatabase": "varchar",
            "metadataSchema": "varchar",
            "metadataTable": "varchar",
            "metadataName": "varchar",
            "metadataValue": "text"
        },
        "connection": "...",
        "options": "...",
        "database": "mydrivetime",
        "driver": "...",
        "sqlite": "...",
        "databaseConnection": {}
    },
    "manager": {
        "repositories": [],
        "plainObjectToEntityTransformer": {},
        "connection": "..."
    },
    "namingStrategy": {
        "nestedSetColumnNames": {
            "left": "nsleft",
            "right": "nsright"
        },
        "materializedPathColumnName": "mpath"
    },
    "relationLoader": {
        "connection": "..."
    },
    "relationIdLoader": {
        "connection": "..."
    },
    "isConnected": true
}

ubbxdtey

ubbxdtey1#

这个问题原来是一个众所周知的问题,TypeORM实体/迁移在缩小时不工作。修复方法是添加vue config以防止类名被缩小,如下所示:

//vue.config.js (in the root folder)
module.exports = {
  chainWebpack: config => {
    if (process.env.NODE_ENV === 'production') {
      config.optimization.minimizer('terser').tap((args) => {
        // see https://cli.vuejs.org/guide/webpack.html#chaining-advanced
        // https://cli.vuejs.org/migrating-from-v3/#vue-cli-service
        //   => chainWebpack for a chain override example
        // https://github.com/terser/terser#minify-options for terser options
        const terserOptions = args[0].terserOptions
        // Avoid to mangle entities (leads to query errors)
        terserOptions["keep_classnames"] = true
        terserOptions["keep_fnames"] = true
        // console.log(JSON.stringify(args[0], null, 2))
        return args
      })
    }
  },
  // ...rest of your vue.config.js...
}

字符串
有关详细信息,请查看this github issue

628mspwn

628mspwn2#

经过一番挣扎,我找到了迁移的工作方式和添加迁移时要避免的事情。

1.使用class作为迁移数组输入,而不是classname或文件夹路径。

如果你使用classname或path,它将在生产模式下改变,因为classname被缩小了,你将开始面对下面的错误。

Error during Data Source initialization i: Te migration name is wrong. Migration class name should have a JavaScript timestamp appended.

字符串

2.将MigrationInterface的name属性定义为类名。

MigrationInterface已经定义了name属性,所有你需要做的就是将这个name属性设置为name of class(with timestamp),这样在你的代码被缩小后,或者即使你将你的类重命名为without timestamp,它也会保留下来。参见下面的示例。

import {MigrationInterface, QueryRunner, Table} from "typeorm"

export class CreateGradeDownloadStatusTable implements MigrationInterface {

    name = 'CreateGradeDownloadStatusTable1691033085995'

    public async up(queryRunner: QueryRunner): Promise<void> {}

    public async down(queryRunner: QueryRunner): Promise<void> {}

}

相关问题