nodeJS将数据插入PostgreSQL错误

2023-11-29

我在使用 NodeJS 和 PostgreSQL 时遇到了一个奇怪的错误,我希望你能帮助我。

我有大量的数据集,大约有 200 万个条目,我想将它们插入到数据库中。

一份数据由 4 列组成:

id: string,
points: float[][]
mid: float[]
occurences: json[]

我像这样插入数据:

let pgp = require('pg-promise')(options);
let connectionString = 'postgres://archiv:archiv@localhost:5432/fotoarchivDB';
let db = pgp(connectionString);

cityNet.forEach((arr) => {
    db
    .none(
        "INSERT INTO currentcitynet(id,points,mid,occurences) VALUES $1",
        Inserts("${id},${points}::double precision[],${mid}::double precision[],${occurences}::json[]",arr))
    .then(data => {
        //success
    })
    .catch(error => {
        console.log(error);
        //error
    });
})

function Inserts(template, data) {
    if (!(this instanceof Inserts)) {
        return new Inserts(template, data);
    }
    this._rawDBType = true;
    this.formatDBType = function() {
    return data.map(d => "(" + pgp.as.format(template, d) + ")").join(",");
};

这对于前 309248 个数据块来说是正确的,然后突然间它会在尝试插入的每个下一个数据(看起来像这样)中出现错误:

{ error: syntax error at end of input
at Connection.parseE (/home/christian/Masterarbeit_reworked/projekt/server/node_modules/pg-promise/node_modules/pg/lib/connection.js:539:11)
at Connection.parseMessage (/home/christian/Masterarbeit_reworked/projekt/server/node_modules/pg-promise/node_modules/pg/lib/connection.js:366:17)
at Socket.<anonymous> (/home/christian/Masterarbeit_reworked/projekt/server/node_modules/pg-promise/node_modules/pg/lib/connection.js:105:22)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at Socket.Readable.push (_stream_readable.js:134:10)
at TCP.onread (net.js:548:20)
name: 'error',
length: 88,
severity: 'ERROR',
code: '42601',
detail: undefined,
hint: undefined,
position: '326824',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'scan.l',
line: '1074',
routine: 'scanner_yyerror' }

每个迭代错误消息的“位置”条目都会发生变化。

我可以重做,但在 309248 个条目之后它总是会出错。 当我尝试插入更少的条目(例如 1000 个条目)时,不会发生错误。

这真的让我很困惑。我认为 PostgreSQL 没有最大行数。此外,错误消息对我根本没有帮助。

SOLVED发现错误了。在我的数据中,存在“空”条目。过滤掉空数据已成功。 我将尝试其他插入数据的建议,因为当前的方式有效,但性能非常糟糕。


我是作者pg-承诺。您的整个方法应该更改为以下方法。

通过以下方式进行大量插入的正确方法pg-承诺:

const pgp = require('pg-promise')({
    capSQL: true
});

const db = pgp(/*connection details*/);

var cs = new pgp.helpers.ColumnSet([
    'id',
    {name: 'points', cast: 'double precision[]'},
    {name: 'mid', cast: 'double precision[]'},
    {name: 'occurences', cast: 'json[]'}
], {table: 'currentcitynet'});

function getNextInsertBatch(index) {
    // retrieves the next data batch, according to the index, and returns it
    // as an array of objects. A normal batch size: 1000 - 10,000 objects,
    // depending on the size of the objects.
    //
    // returns null when there is no more data left.
}

db.tx('massive-insert', t => {
    return t.sequence(index => {
        const data = getNextInsertBatch(index);
        if (data) {
            const inserts = pgp.helpers.insert(data, cs);
            return t.none(inserts);
        }
    });
})
    .then(data => {
        console.log('Total batches:', data.total, ', Duration:', data.duration);
    })
    .catch(error => {
        console.log(error);
    });

UPDATE

And if getNextInsertBatch只能异步获取数据,然后从中返回一个promise,并更新sequence->source相应回调:

return t.sequence(index => {
    return getNextInsertBatch(index)
        .then(data => {
            if (data) {
                const inserts = pgp.helpers.insert(data, cs);
                return t.none(inserts);
            }
        });
});

相关链接:

  • tx
  • sequence / spex序列
  • 列集
  • 使用 pg-promise 进行多行插入
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

nodeJS将数据插入PostgreSQL错误 的相关文章

  • pg_dump 没有对象注释?

    有没有办法执行 pg dump 并排除表 视图和列的 COMMENT ON 我广泛使用 COMMENT ON 命令来描述所有对象 并且经常在其中包含换行符以获得更清晰的描述 例如 COMMENT ON TABLE mytable1 IS M
  • 如何防止 gulp-notify 破坏 Windows 中的 gulp-watch?

    我正在使用吞咽通知 https www npmjs org package gulp notify插入 这是我如何在 gulpfile js 中实现它的示例 您可以看到我也在使用 gutil 和 livereload 我不知道它们是否发挥任
  • 嵌套异步/等待 Nodejs

    似乎无法弄清楚为什么这对我不起作用 我有一个父函数 它对子加载进程执行 AWAIT LOAD 进程又调用另一个名为 LOADDATA 的 AWAIT 所以基本上是这样的 module exports async function try a
  • 一次更新猫鼬中的多个文档

    我有一个用户文档数组 每个用户都有关注者属性 它是一个数字 我只想将此属性增加 1 然后立即更新数据库中的所有这些用户文档 更多细节 在请求中 我有一组用户 id 我使用这些 id 进行查询以获取一组用户文档 const users awa
  • pg_dump 与 pg_dumpall?使用哪一个来进行数据库备份?

    I tried pg dump然后在另一台机器上我尝试导入 sql 并填充数据库 我看到 CREATE TABLE ERROR role prod does not exist CREATE TABLE ERROR role prod do
  • Node.js 未处理的“错误”事件

    我编写了一个简单的代码并将其保存在文件 try js 中 var http require http var makeRequest function message var options host localhost port 8080
  • Node.js - 重载函数

    有没有一种方法可以重载node js中的函数 类似于 noSuchMethod https developer mozilla org en JavaScript Reference Global Objects Object noSuch
  • 如何执行“sudo nvm”?

    在我的 Mac 上 我想将一些需要 su 权限的包迁移到另一个节点版本 我使用 homebrew 安装 nvm 现在我需要执行 sudo nvm 或 reinstall packages将失败 me MacBook sudo nvm sud
  • 部分唯一索引不适用于冲突子句 PostgreSQL

    表结构 create table example a id integer b id integer c id integer flag integer 部分索引 create unique index u idx on example a
  • 错误关系不存在

    我得到了 error relation causes does not exist 我的节点应用程序出现错误 这种关系确实存在 我不确定问题出在哪里 我创建了该表 CREATE TABLE causes cause id bigint NO
  • 如何阻止 Node.js 服务器崩溃

    我是节点js新手 我试图创建一个简单的 HTTP 服务器 我按照著名的例子创建了一个 Hello World 服务器如下 var handleRequest function req res res writeHead 200 res1 e
  • web3.eth.sendSignedTransaction() 总是返回“返回错误:nonce 太低”

    I used 电子邮件受保护 cdn cgi l email protection在 Node js 中与私有区块链交互 我是按照官方文档写的代码 电子邮件受保护 cdn cgi l email protection var Web3 re
  • axios 请求中未发送正文数据

    我试图通过 axios 请求将数据发送到我的后端脚本 但正文看起来是空的 这是前端发送的请求 axios request method GET url http localhost 4444 next api headers Authori
  • 下载 csv 文件 node.js

    我正在使用 node js 构建一个应用程序并尝试将数据下载为 csv 文件 我正在使用 json2csv https www npmjs com package json2csv https www npmjs com package j
  • 使用连接池后如何处理过多的并发连接?

    Scenario 假设您有一个拥有大量流量的网站或应用程序 即使使用数据库连接池 性能也会受到真正的打击 站点 应用程序甚至可能崩溃 因为并发连接太多 Question 人们有什么选择来处理这个问题 我的想法 我在想有这个问题的人可以创建多
  • 在Python中检索PostgreSQL数据库的新记录

    在数据库表中 第二列和第三列有数字 将会不断添加新行 每次 每当数据库表中添加新行时 python 都需要不断检查它们 当 sql 表中收到的新行数低于 105 时 python 应打印一条通知消息 警告 数量已降至 105 以下 另一方面
  • 如何获取nodejs程序中的nodejs版本?

    In a Node js 的调试器 https github com rocky trepanjs 有一个命令显示V8版本和调试器包版本 如何获取nodejs版本 我想我基本上可以运行命令node version or nodejs ver
  • 如何为我的整个 Node.js 应用程序使用相同的 MySQL 连接?

    我有一个app js 我从那里运行我的整个应用程序 在 app js 内部 我require许多文件中都有代码 对于每个文件 我都这样做 var mysql require mysql var mclient mysql createCon
  • Django 模型:默认日期时间未转换为 SQL CURRENT_TIMESTAMP

    我正在使用 Django 模型创建 PostgreSQL DB 我有一个 DateTimeField 我想将当前时间戳设置为默认值 我知道有多个消息来源建议如何做到这一点 但是 当我在 Django 之外检查数据库时 默认时间戳不会显示 我
  • Jwt 签名和前端登录身份验证

    我有这个特殊的 jwt sign 函数 Backend const token jwt sign id user id process env TOKEN SECRET expiresIn 1m res header auth token

随机推荐