electron sequelize.js关闭后如何重新连接

gev0vcfq  于 2023-10-14  发布在  Electron
关注(0)|答案(1)|浏览(148)

我使用sequelize.js连接sqlite,但我必须关闭连接,因为我想修改sqlite的文件。Windows无法在文件打开时修改它。
我这样创建对象:

const sequelize = new Sequelize('database', null, null, {
    dialect: 'sqlite',
    storage: 'db.sql',
    define: {
      timestamps: false,
      freezeTableName: true
    },
    dialectModule: sqlite3
  })

当我关闭连接时,我无法通过原始对象重新连接sqlite。我尝试使用ConnectionManager初始化,但它不工作。

sequelize.close()
// do something ...
sequelize.connectionManager.initPools()
sequelize.authenticate() // raise the error by disconnect
z31licg0

z31licg01#

很抱歉我做了尸检。
我想,我找到了一个变通办法。
1.将数据库处理程序 Package 在类中
`// DBHandler.ts

class DBHandler {

  public dbInstance: Sequelize | undefined = undefined;

  constructor(
    readonly dbConf: Options,
  ) {}

  async connect() {
    // Check if the Sequelize instance already exist
    if (this.dbInstance)
      throw new ApplicationError('Database connection is already initialized');

    // Connection is created here
    this.dbInstance = new Sequelize(
      DATABASE_URL,
      this.dbConf
    );
    
    // Private method listed below
    await this.initModels();
  }

  async initModels() {
    
    // Init each model via functions - see the next code block
    await initFooModel(this.dbInstance);
    // ... other models

    // Init associations and hooks if you have any -
    // make sure to do it after all the models init
    await initAssociations();
    await initHooks();
  }

  async close() {
    // Check if sequelize instance exists
    if (!this.dbInstance)
      throw new ApplicationError('Database connection is not initialized');

    await this.dbInstance.close();
  }

}

1.模型定义文件,假设使用Model.init()(也将与.define()一起使用):在Promise中 Package Model.init(... args),然后将其 Package 在一个Projec函数中

// Foo.ts

export const initFooModel = async (dbInstance: Sequelize) => {
  return new Promise<void>((resolve, reject) => {
    try {

      // Your actual Model.init()
      Foo.init({
        id: {
          type: DataTypes.INTEGER,
          primaryKey: true,
          autoIncrement: true
        },
        bar: {
          type: DataTypes.STRING(5000),
          allowNull: false
        },
        baz: {
          type: DataTypes.STRING(9001),
          allowNull: true
        },
      }, {
        // Sequelize property in options === Sequelize instance
        sequelize: dbInstance,
        ... // other options
      });

      resolve();
    } catch(e) {
      reject(e)
    }
  });
};

1.对关联执行相同的操作:

// initModelAssociations.ts

export const initModelAssociations = async () => {
  return new Promise<void>((resolve, reject) => {
    try {

      // Your actual associations declaration here
      Foo.belongsTo(Bar);
      ...

      resolve();
    } catch(e) {
      reject(e);
    }
  });
};

1.用钩子做同样的包裹。 我已经用PostgreSQL测试过了,但我认为它也应该能用SQLite。没有必要使这些函数异步,如果你喜欢同步init,只需删除这些Promises。 在你的代码中:

const dbHandler = new DBHandler(
  // Your Sequelize config here
)

await dbHandler.connect();
...
await dbHandler.close();
...
await dbHandler.connect();

`
应该可以!
//对不起,无法正确格式化(1.)

相关问题