使用 Knex 查询动态更改数据库

Dynamically change database with Knex queries

我在尝试动态设置 Knex 数据库时遇到问题。我有多个数据库,每小时递增一次。 (例如 db-1-hour、db-2-hour)。当我们切换到新的时间时,我想使用下一个数据库。我创建了一个示例函数,其中 returns 一个基于新数据库的新 Knex 函数,但我收到了已弃用的警告。

我的配置

import knex from 'knex';

const knexConfig = {
  client: 'pg',
  connection: {
    host: host,
    port: port,
    user: user,
    database: '',
    password: password,
  },
  pool: {
    min: 2,
    max: 10,
  },
  timezone: 'UTC',
};

exports const getCurrentDb = async () => {
 const hourDb = await getLatestDbName()
 cons knexConfig.connection.database = hourDb; // I update the database name
 return knex(knexConfig);
}
 

用法

import { getCurrentDb } from "./config"

const getSomething = async () => {
 const db = await getCurrentDb()
 return db.select().from("something")
}

代码有效,但我总是收到警告消息:

calling knex without a tableName is deprecated. Use knex.queryBuilder() instead.

如何动态连接到数据库?提前致谢!

警告信息与数据库切换机制无关。

尝试将您的 select 语句更改为:

import { getCurrentDb } from "./config"

const getSomething = async () => {
 const db = await getCurrentDb()
 return db("something").columns('*')
}