【问题标题】:Knex cannot find table in Cloud SQL Postgres from Cloud FunctionsKnex 在 Cloud Functions 的 Cloud SQL Postgres 中找不到表
【发布时间】: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


    【解决方案1】:

    看起来您正在创建表 tableName 而不使用引号,这使得它实际上是小写的(不区分大小写)。因此,在创建架构时,请执行以下操作:

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

    或仅使用小写的表/列名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      • 2021-09-02
      • 2019-08-17
      • 2021-06-05
      • 2019-04-18
      • 2017-08-18
      • 2019-08-12
      相关资源
      最近更新 更多