Knex 在 Cloud SQL Postgres 中找不到 table 来自 Cloud Functions

Knex cannot find table in Cloud SQL Postgres from Cloud Functions

我正在尝试从用 TypeScript 编写的 Cloud Function 连接到 Cloud 运行ning 中的 Postgres 12 数据库 SQL。

我使用以下内容创建数据库:

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  - 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 中使用以下命令创建了 table(然后填充了来自 CSV 的数据):

\connect ingredients;
CREATE TABLE tableName (name VARCHAR(255), otherField VARCHAR(255), ... );

在该控制台中,如果我 运行 查询 SELECT * FROM tableName;,我会看到列出的正确数据。

为什么 Knex 看不到 table:tableName,但 GCP Cloud Shell 可以?

顺便说一句,我肯定连接到正确的数据库,因为我在云 SQL 日志记录界面中看到相同的错误日志。

看起来您在创建 table tableName 时没有引用,这实际上是小写(不区分大小写)。所以在创建模式时做:

CREATE TABLE "tableName" ("name" VARCHAR(255), "otherField" VARCHAR(255), ... );

或仅使用小写 table / 列名称。