【发布时间】:2021-02-25 20:44:06
【问题描述】:
我正在尝试从用 TypeScript 编写的云函数连接到在 Cloud SQL 中运行的 Postgres 12 数据库。
我使用以下内容创建数据库:
import * as Knex from "knex"
const { username, password, instance } = ... // username, password, connection name (<app-name>:<region>:<database>)
const config = {
client: 'pg',
connection: {
user: username,
password: password,
database: 'ingredients',
host: `/cloudsql/${instance}`,
pool: { min: 1, max: 1}
}
}
const knex = Knex(config as Knex.Config)
然后我使用以下方法查询数据库:
const query = ... // passed in as param
const result = await knex('tableName').where('name', 'ilike', query).select('*')
当我运行此代码时,我在 Cloud Functions 日志中收到以下错误:
Unhandled error { error: select * from "tableName" where "name" ilike $1 - relation "tableName" does not exist
at Parser.parseErrorMessage (/workspace/node_modules/pg-protocol/dist/parser.js:278:15)
at Parser.handlePacket (/workspace/node_modules/pg-protocol/dist/parser.js:126:29)
at Parser.parse (/workspace/node_modules/pg-protocol/dist/parser.js:39:38)
at Socket.stream.on (/workspace/node_modules/pg-protocol/dist/index.js:10:42)
at Socket.emit (events.js:198:13)
at Socket.EventEmitter.emit (domain.js:448:20)
at addChunk (_stream_readable.js:288:12)
at readableAddChunk (_stream_readable.js:269:11)
at Socket.Readable.push (_stream_readable.js:224:10)
at Pipe.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
我在 GCP Cloud Shell 中使用以下命令创建了表(然后使用 CSV 中的数据填充):
\connect ingredients;
CREATE TABLE tableName (name VARCHAR(255), otherField VARCHAR(255), ... );
在该控制台中,如果我运行查询 SELECT * FROM tableName;,我会看到列出的正确数据。
为什么 Knex 看不到表格:tableName,但 GCP Cloud Shell 可以?
顺便说一句,我肯定连接到正确的数据库,因为我在 Cloud SQL 日志记录界面中看到了相同的错误日志。
【问题讨论】:
标签: postgresql google-cloud-platform google-cloud-functions google-cloud-sql knex.js