首页 > 解决方案 > 使用 Knex 查询动态更改数据库

问题描述

我在尝试动态设置 Knex 数据库时遇到问题。我有多个数据库,每小时递增。(例如 db-1-hour、db-2-hour)。当我们切换到新的时间时,我想使用下一个数据库。我创建了一个示例函数,它基于新数据库返回一个新的 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.

如何动态连接到数据库?先感谢您!

标签: javascriptnode.jsknex.js

解决方案


警告消息与 DB 切换机制无关。

尝试将您的select陈述更改为:

import { getCurrentDb } from "./config"

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

推荐阅读