javascript - 使用 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.
如何动态连接到数据库?先感谢您!
解决方案
警告消息与 DB 切换机制无关。
尝试将您的select
陈述更改为:
import { getCurrentDb } from "./config"
const getSomething = async () => {
const db = await getCurrentDb()
return db("something").columns('*')
}
推荐阅读
- c# - 通过 HTTP 请求使用 C# 读取 Json
- typeorm - TypeORM 索引创建
- spring - 在 Kubernetes 中进行 Spring Boot 集成测试的 Testcontainers 的选项或替代方案?
- sql - 如何将多行转换为一行
- javascript - 为什么桌面上的 chrome 中有“navigator.maxTouchPoints = 10”?
- javascript - 仅使用键 JavaScript 在对象中查找值
- ios - 命令 PhaseScriptExecution 失败,退出代码非零 - 无法在物理设备上安装应用程序
- javascript - Angular 12 将外部脚本加载为类型模块
- android - 确保 RoomDatabase.Callback 中的协程完成
- php - Laravel(如何将数据添加到数据库)