nodejs の mysql で Error: Cannot enqueue Query after invoking quit.エラー

今日もエラーと戦い続けるIT戦士のこばちです。

今日はnodejsでmysqlに接続していたら、次のようなエラーにぶち当たりました。


/Users/kobachi/Documents/dev/my-test/tests/db/item/add_items.js:25
      if (error) {connection.rollback(function() {throw error;})}
                                                  ^

Error: Cannot enqueue Query after invoking quit.
    at Protocol._validateEnqueue (/Users/kobachi/Documents/dev/my-test/node_modules/mysql/lib/protocol/Protocol.js:202:16)
    at Protocol._enqueue (/Users/kobachi/Documents/dev/my-test/node_modules/mysql/lib/protocol/Protocol.js:135:13)
    at Connection.query (/Users/kobachi/Documents/dev/my-test/node_modules/mysql/lib/Connection.js:214:25)
    at /Users/kobachi/Documents/dev/my-test/tests/db/item/add_items.js:24:16
    at Query._callback (/Users/kobachi/Documents/dev/my-test/tests/db/item/add_items.js:23:17)
    at Query.Sequence.end (/Users/kobachi/Documents/dev/my-test/node_modules/mysql/lib/protocol/sequences/Sequence.js:86:24)
    at Query._handleFinalResultPacket (/Users/kobachi/Documents/dev/my-test/node_modules/mysql/lib/protocol/sequences/Query.js:144:8)
    at Query.OkPacket (/Users/kobachi/Documents/dev/my-test/node_modules/mysql/lib/protocol/sequences/Query.js:78:10)
    at Protocol._parsePacket (/Users/kobachi/Documents/dev/my-test/node_modules/mysql/lib/protocol/Protocol.js:280:23)
    at Parser.write (/Users/kobachi/Documents/dev/my-test/node_modules/mysql/lib/protocol/Parser.js:74:12)
~/Documents/dev/my-test $ node tests/db/item/add_items.js

ソースは次のような内容。

const connection = require('../mysql.js')

const items = [{},{},{}]; // 略

connection.connect();

// 商品が存在しない場合登録する
connection.beginTransaction(function(error) {
  if (error) { throw error; }
  let promise = new Promise(function(resolve, reject) {
    connection.query(`SELECT code FROM mst_items`, (error, results) => {
      if (error) {connection.rollback(function() {throw error;})}
      resolve(results);
    });
  });

  promise.then(function(results) {
    const exist_item_codes = results.map((result) => { return result.code });
    const not_exist_item = items.filter((item) => { return (!exist_item_codes.includes(item.code)) });

    not_exist_item.forEach((item) => {
      connection.query(`INSERT INTO mst_items (code, name, price) VALUES ('${item.code}', '${item.name}', ${item.price}, 1)`, function (error, results) {
        if (error) { connection.rollback(function() { throw error; }); }
        connection.commit(function(error) {
          if (error) {
            connection.rollback(function() {
              throw error;
            });
          }
          console.log(`${item.name}を追加!`);
        });
      });
    })
  }).catch((err) => setImmediate(() => { throw err; }));
});

connection.end();

解決策は、connection.connect()connection.end()を削除することです★

参考:https://github.com/mysqljs/mysql/issues/1296

スポンサーリンク

シェアする

  • このエントリーをはてなブックマークに追加

フォローする

スポンサーリンク