Node.js + OracleDb - 多次插入最后一个日期

时间:2017-03-21 13:46:04

标签: javascript node.js oracledb oracledb-npm

我收到了这个JSON:

{
  "TOTAL_RECORDS": 1029,
  "REGISTROS": [
    {
      "CODIGO": "1",
      "ATENDIMENTO": "1",
      "PAGAMENTO": "1",
      "VENCIMENTO": "2016-12-17 00:00:00",
      "PROCESSAMENTO": "2016-12-10 00:00:00",
      "VALOR": "1800.00000",
      "NOSSO_NUMERO": "xxxxxxx",
      "NUMERO_DOCUMENTO": "xxxxx",
      "CODIGO_BANCO": "123",
      "LINHA_DIGITAVEL": "XXX70110000180000",
      "CODIGO_BARRAS": "XXX90940"
    },
    {
      "CODIGO": "2",
      "ATENDIMENTO": "2",
      "PAGAMENTO": "2",
      "VENCIMENTO": "2016-12-17 00:00:00",
      "PROCESSAMENTO": "2016-12-10 00:00:00",
      "VALOR": "2700.00000",
      "NOSSO_NUMERO": "xxxxxxx",
      "NUMERO_DOCUMENTO": "xxxxx",
      "CODIGO_BANCO": "123",
      "LINHA_DIGITAVEL": "XXX70110000180000",
      "CODIGO_BARRAS": "XXX90940"
    },...

然后我需要捕获这些信息并保存在DB Oracle中,所以我这样做:

module.exports = function (object, callback) {

     var oracledb = require('oracledb');    
     for(const prop in object['REGISTROS']){                    

        codigo = object['REGISTROS'][prop]['CODIGO'];               

        atendimento = object['REGISTROS'][prop]['ATENDIMENTO'];

        pagamento = object['REGISTROS'][prop]['PAGAMENTO'];

        vencimento = object['REGISTROS'][prop]['VENCIMENTO'];

        processamento = object['REGISTROS'][prop]['PROCESSAMENTO'];

        valor = parseInt(object['REGISTROS'][prop]['VALOR']);

        nossoNumero = object['REGISTROS'][prop]['NOSSO_NUMERO'];

        numeroDocumento = object['REGISTROS'][prop]['NUMERO_DOCUMENTO'];

        codigoBanco = object['REGISTROS'][prop]['CODIGO_BANCO'];

        linhaDigitavel = object['REGISTROS'][prop]['LINHA_DIGITAVEL'];              

        codigoBarras = object['REGISTROS'][prop]['CODIGO_BARRAS'];

        oracledb.getConnection({            
            user: "x",
            password:"xxx",
            connectString: "mycon/string"  
        },
        function(err, connection){  
            if (err){  
                console.error(err.message);  
                return;  
            }

            connection.execute(
                "INSERT INTO USU_TBOLETO VALUES (:USU_CODIGO, :USU_ATEND, :USU_PAGAMENTO, " +
                ":USU_VENCIMENTO, :USU_PROCESSA, :USU_VALOR, :USU_NOSSONUM, :NUMERODOC, :USU_CODBANCO, " +
                ":USU_LINHADIG , :USU_CODBARRAS)",

            [codigo, atendimento, pagamento, vencimento, processamento, valor, nossoNumero, 
            numeroDocumento, codigoBanco, linhaDigitavel, codigoBarras], 
            { autoCommit: true},            
            function(err, result){

                if (err){  
                    console.error(err.message);            
                    doRelease(connection);  
                    return;  
                }
                console.log(codigo + ' - ' + atendimento + ' - ' + pagamento + ' - ' + vencimento);
                ///console.log(result.metaData);  
                ///console.log(result.rows);  
                doRelease(connection);  
            });                  
        }); 
    }   


    function doRelease(connection) {        
        connection.release(  
            function(err){  
                if (err) { console.error(err.message); }  
            }  
        );  
    }
}

问题是它在我的数据库中插入了最后一条记录,1029次,就像总记录一样。 为什么? 我不明白为什么。 INSERT代码进入FOR条件。

正确的是插入1029次,从1号开始直到1029。

ATT。 迪奥戈

2 个答案:

答案 0 :(得分:1)

当您运行代码时,如果您目前已经构建了代码,它将向libuv的工作队列发送许多异步操作,并且您的JavaScript代码将失去控制权。我建议使用async module's eachSeries method来维护控制或承诺链(或Node.js 7.6 +中的async / await)。

此外,为循环的每次迭代获取新连接会减慢很多事情!此操作只需要一个连接。您应该获得连接,处理数据,关闭连接。

重新考虑的另一件事是使用autoCommit:true。如果对每一行执行此操作,则将每个插入视为自己的事务。如果失败发生在中途,找出问题并修复它(插入剩余的行)将是困难和手动的。我建议在插入所有内容后对连接对象使用commit方法(或者在循环的最后一次迭代时使用autoCommit:true)。

以下是一个例子:

const oracledb = require('oracledb');
const config = require('./dbConfig.js');

module.exports = function(object, callback) {
    let conn;

    function insertRegistro(registro, commit) {
        if (commit) {
            console.log('Last iteration of the loop, committing with this one');
        }

        return conn.execute(
            `insert into usu_tboleto (
               usu_codigo, usu_atend, usu_pagamento, usu_vencimento, usu_processa, usu_valor, 
               usu_nossonum, numerodoc, usu_codbanco, usu_linhadig, usu_codbarras
             ) values (
               :usu_codigo, :usu_atend, :usu_pagamento, :usu_vencimento, :usu_processa, :usu_valor, 
               :usu_nossonum, :numerodoc, :usu_codbanco, :usu_linhadig , :usu_codbarras
            )`,
            {
                usu_codigo: registro.CODIGO,
                usu_atend: registro.ATENDIMENTO,
                usu_pagamento: registro.PAGAMENTO,
                usu_vencimento: registro.VENCIMENTO,
                usu_processa: registro.PROCESSAMENTO,
                usu_valor: registro.VALOR,
                usu_nossonum: registro.NOSSO_NUMERO,
                numerodoc: registro.NUMERO_DOCUMENTO,
                usu_codbanco: registro.CODIGO_BANCO,
                usu_linhadig: registro.LINHA_DIGITAVEL,
                usu_codbarras: registro.CODIGO_BARRAS
            },
            {
                autoCommit: commit
            }
        );
    }

    oracledb.getConnection(config)
        .then(function(c) {
            conn = c;

            console.log('Got connection, starting loop');

            let promiseChain = Promise.resolve();

            object['REGISTROS'].forEach(function(registro, index) {
                promiseChain = promiseChain
                    .then(function() {
                        return insertRegistro(registro, object['REGISTROS'].length === index + 1);
                    });
            });

            return promiseChain;
        })
        .catch(function(err) {
            console.log(err);
            console.log('Encountered error, rolling back transaction');

            return conn.rollback()
                .then(function() {
                    console.log('Transaction rolled back');
                })
                .catch(function(err) {
                    console.log('Error rolling back', err);
                });
        })
        .then(function() {
            return conn.close();
        })
        .then(function() {
            console.log('Connection closed');
        })
        .catch(function(err) {
            console.log(err);
        });
} 

您可以通过将往返次数从1029减少到1(通过一次性完成)或3次(如果您一次设置500次)来进一步优化。这将大大提高性能。这是一个以500个为一组进行批量插入的示例。

const oracledb = require('oracledb');
const config = require('./dbConfig.js');

module.exports = function(object, callback) {
  let conn;

  function insertRegistros(opts) {
    if (opts.commit) {
        console.log('Last iteration of the loop, committing with this one');
    }

    return conn.execute(
     `declare
        type varchar2_aat is table of varchar2(50)
          index by pls_integer;

        l_usu_codigo_vals varchar2_aat;

      begin

        l_usu_codigo_vals := :usu_codigo_vals;

        forall x in 1 .. l_usu_codigo_vals.count
        insert into usu_tboleto (
          usu_codigo, usu_atend, usu_pagamento, usu_vencimento, usu_processa, usu_valor, 
          usu_nossonum, numerodoc, usu_codbanco, usu_linhadig, usu_codbarras
        ) values (
          :usu_codigo_vals(x), :usu_atend_vals(x), :usu_pagamento_vals(x), :usu_vencimento_vals(x), :usu_processa_vals(x), :usu_valor_vals(x), 
          :usu_nossonum_vals(x), :numerodoc_vals(x), :usu_codbanco_vals(x), :usu_linhadig_vals(x) , :usu_codbarras_vals(x)
        );

      end;`,
      {
        usu_codigo_vals: {type: oracledb.STRING, dir: oracledb.BIND_IN, val: opts.usu_codigo_vals},
        usu_atend_vals: {type: oracledb.STRING, dir: oracledb.BIND_IN, val: opts.usu_atend_vals},
        usu_pagamento_vals: {type: oracledb.STRING, dir: oracledb.BIND_IN, val: opts.usu_pagamento_vals},
        usu_vencimento_vals: {type: oracledb.STRING, dir: oracledb.BIND_IN, val: opts.usu_vencimento_vals},
        usu_processa_vals: {type: oracledb.STRING, dir: oracledb.BIND_IN, val: opts.usu_processa_vals},
        usu_valor_vals: {type: oracledb.STRING, dir: oracledb.BIND_IN, val: opts.usu_valor_vals},
        usu_nossonum_vals: {type: oracledb.STRING, dir: oracledb.BIND_IN, val: opts.usu_nossonum_vals},
        numerodoc_vals: {type: oracledb.STRING, dir: oracledb.BIND_IN, val: opts.numerodoc_vals},
        usu_codbanco_vals: {type: oracledb.STRING, dir: oracledb.BIND_IN, val: opts.usu_codbanco_vals},
        usu_linhadig_vals: {type: oracledb.STRING, dir: oracledb.BIND_IN, val: opts.usu_linhadig_vals},
        usu_codbarras_vals: {type: oracledb.STRING, dir: oracledb.BIND_IN, val: opts.usu_codbarras_vals}
      },
      {
        autoCommit: opts.commit
      }
    );
  }

  oracledb.getConnection(config)
    .then(function(c) {
      conn = c;

      console.log('Got connection, starting loop');

      const batchRowCount = 500;
      const loops = Math.ceil(object['REGISTROS'].length / batchRowCount);

      let promiseChain = Promise.resolve();
      let registrosIdx = 0;

      for (let outerIndex = 0; outerIndex < loops; outerIndex += 1) {
        (function() {
          const usu_codigo_vals = [];
          const usu_atend_vals = [];
          const usu_pagamento_vals = [];
          const usu_vencimento_vals = [];
          const usu_processa_vals = [];
          const usu_valor_vals = [];
          const usu_nossonum_vals = [];
          const numerodoc_vals = [];
          const usu_codbanco_vals = [];
          const usu_linhadig_vals = [];
          const usu_codbarras_vals = [];

          for (let idx = 0; idx < batchRowCount; idx += 1) {
            if (registrosIdx === object['REGISTROS'].length) {
              break;
            }

            usu_codigo_vals.push(object['REGISTROS'][registrosIdx].CODIGO);
            usu_atend_vals.push(object['REGISTROS'][registrosIdx].ATENDIMENTO);
            usu_pagamento_vals.push(object['REGISTROS'][registrosIdx].PAGAMENTO);
            usu_vencimento_vals.push(object['REGISTROS'][registrosIdx].VENCIMENTO);
            usu_processa_vals.push(object['REGISTROS'][registrosIdx].PROCESSAMENTO);
            usu_valor_vals.push(object['REGISTROS'][registrosIdx].VALOR);
            usu_nossonum_vals.push(object['REGISTROS'][registrosIdx].NOSSO_NUMERO);
            numerodoc_vals.push(object['REGISTROS'][registrosIdx].NUMERO_DOCUMENTO);
            usu_codbanco_vals.push(object['REGISTROS'][registrosIdx].CODIGO_BANCO);
            usu_linhadig_vals.push(object['REGISTROS'][registrosIdx].LINHA_DIGITAVEL);
            usu_codbarras_vals.push(object['REGISTROS'][registrosIdx].CODIGO_BARRAS);

            registrosIdx += 1;
          }

          promiseChain = promiseChain
            .then(function() {
              return insertRegistros({
                usu_codigo_vals: usu_codigo_vals, 
                usu_atend_vals: usu_atend_vals,
                usu_pagamento_vals: usu_pagamento_vals,
                usu_vencimento_vals: usu_vencimento_vals,
                usu_processa_vals: usu_processa_vals,
                usu_valor_vals: usu_valor_vals,
                usu_nossonum_vals: usu_nossonum_vals,
                numerodoc_vals: numerodoc_vals,
                usu_codbanco_vals: usu_codbanco_vals,
                usu_linhadig_vals: usu_linhadig_vals,
                usu_codbarras_vals: usu_codbarras_vals,
                commit: outerIndex + 1 === loops
              });
            });
        })();
      }

      return promiseChain;
    })
    .catch(function(err) {
      console.log(err);
      console.log('Encountered error, rolling back transaction');

      return conn.rollback()
        .then(function() {
          console.log('Transaction rolled back');
        })
        .catch(function(err) {
          console.log('Error rolling back', err);
        });
    })
    .then(function() {
        return conn.close();
    })
    .then(function() {
        console.log('Connection closed');
    })
    .catch(function(err) {
        console.log(err);
    });
} 

正如您所看到的,代码变得有点棘手。但是,当驱动程序添加对绑定记录数组的支持而不仅仅是字符串或数字时,这将变得更加简单。

您可以在我的博客上阅读更多相关信息以及我的工作: https://jsao.io/2017/01/plsql-record-types-and-the-node-js-driver/

答案 1 :(得分:0)

for循环几乎立即执行,而数据库操作是异步且缓慢的。 {!1}}循环必须在执行异步操作的回调时完成,因此它只会在循环的最后一次迭代中看到值。

为避免这种情况,您可以使用ES6 for声明变量,这将创建块范围变量。将您的代码更改为此代码,它应该有效:

const

有关循环和闭包的更多信息:

Javascript infamous Loop issue?

JavaScript closure inside loops – simple practical example

Asynchronous Process inside a javascript for loop