You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sequelize.query() Promise始终无法resolve的问题排查

Sequelize查询PostgreSQL无输出且卡住的问题排查

问题现象

执行Sequelize查询时,仅输出running query...,之后既无错误信息,也不输出query complete.,但通过psql能成功执行相同查询。

相关代码

查询函数

async getRowFromWorkerTable(contact_uri){    
    console.log(`running query...`);    
    let result;    
    try{
        result = await sequelize.query("select * from worker where contact_uri='"+contact_uri+"'",
        { type: sequelize.QueryTypes.SELECT});
    }    
    catch(err){
        console.err(err);
    }    
    finally{
        console.log(`query complete.`);
    }    
    return result;
}

Sequelize初始化代码

const sequelize=new Sequelize(process.env.database,process.env.username,process.env.password,{
    dialect:'postgres',
});

Sequelize对象输出

{
  sequelize: <ref *1> Sequelize {
    options: {
      dialect: 'postgres',
      dialectModule: null,
      dialectModulePath: null,
      host: 'localhost',
      protocol: 'tcp',
      define: {},
      query: {},
      sync: {},
      timezone: '+00:00',
      clientMinMessages: 'warning',
      standardConformingStrings: true,
      logging: [Function: log],
      omitNull: false,
      native: false,
      replication: false,
      ssl: undefined,
      pool: {},
      quoteIdentifiers: true,
      hooks: {},
      retry: [Object],
      transactionType: 'DEFERRED',
      isolationLevel: null,
      databaseVersion: 0,
      typeValidation: false,
      benchmark: false,
      minifyAliases: false,
      logQueryParameters: false,
      dialectOptions: [Object]
    },
    config: {
      database: 'dbname',
      username: 'username',
      password: 'password',
      host: 'localhost',
      port: 5432,
      pool: {},
      protocol: 'tcp',
      native: false,
      ssl: undefined,
      replication: false,
      dialectModule: null,
      dialectModulePath: null,
      keepDefaultTimezone: undefined,
      dialectOptions: [Object]
    },
    dialect: PostgresDialect {
      sequelize: [Circular *1],
      connectionManager: [ConnectionManager],
      QueryGenerator: [PostgresQueryGenerator]
    },
    queryInterface: QueryInterface {
      sequelize: [Circular *1],
      QueryGenerator: [PostgresQueryGenerator]
    },
    models: {},
    modelManager: ModelManager { models: [], sequelize: [Circular *1] },
    connectionManager: ConnectionManager {
      sequelize: [Circular *1],
      config: [Object],
      dialect: [PostgresDialect],
      versionPromise: [Promise [Object]],
      dialectName: 'postgres',
      pool: [Pool],
      lib: [PG],
      nameOidMap: {},
      enumOids: [Object],
      oidParserMap: Map(0) {}
    },
    importCache: {}
  }
}

问题原因及解决方案

1. 错误输出语句写错

catch块中使用了console.err(err),正确写法是console.error(err),导致错误发生时无法打印错误信息,误以为没有错误。

修复代码:

catch(err){
    console.error(err);
}

2. 字符串拼接导致SQL语法错误或注入风险

直接拼接contact_uri到SQL语句中,如果contact_uri包含单引号等特殊字符,会导致SQL语法错误,查询卡住。同时存在SQL注入风险。

改用参数化查询:

result = await sequelize.query(
  "select * from worker where contact_uri = :contact_uri",
  { 
    type: sequelize.QueryTypes.SELECT,
    replacements: { contact_uri: contact_uri }
  }
);

3. 未验证数据库连接

Sequelize对象初始化成功不代表数据库连接正常,需要主动验证连接状态。

添加连接验证:

// 初始化后添加
async function initDB() {
  try {
    await sequelize.authenticate();
    console.log('数据库连接成功');
  } catch (error) {
    console.error('数据库连接失败:', error);
  }
}
initDB();

4. 连接池配置问题

默认连接池配置可能导致无法获取可用连接,查询一直等待。

调整连接池配置:

const sequelize=new Sequelize(process.env.database,process.env.username,process.env.password,{
    dialect:'postgres',
    pool: {
      max: 5, // 最大连接数
      min: 0, // 最小空闲连接数
      acquire: 30000, // 获取连接超时时间(毫秒)
      idle: 10000 // 连接空闲超时时间(毫秒)
    }
});

5. 开启SQL日志排查实际执行语句

开启Sequelize的日志功能,查看实际发送到数据库的SQL语句,确认是否和psql执行的一致。

开启日志:

const sequelize=new Sequelize(process.env.database,process.env.username,process.env.password,{
    dialect:'postgres',
    logging: console.log // 打印所有执行的SQL语句
});

内容的提问来源于stack exchange,提问作者sigil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 18:50:25