MySQL,MariaDB,Nodejsでboolean型を扱う時にはまったこと

IT, 開発

MySQL,MariaDBにはboolean型が無いみたいで、
以下の記事でbooleanを使うならbit(1)を使うといいと解説してあります。


しかし…
いざejsなどで値を参照すると、まじもんのbit(1)が入っているので表示できなかったり、分岐などで利用する場合、
毎回 true or false に成形しなおす必要があります。
当たり前なんですが、面倒です。

先人のいい記事がありました。
MySQLにつなぎに行くときにtypeCastにbitだった場合、true or false変換するfunctionを定義しておくことでbit(1)であることを気にせず取得した値をboolean型のように扱えます。
https://www.bennadel.com/blog/3188-casting-bit-fields-to-booleans-using-the-node-js-mysql-driver.htm
解決しました。
bit(1)ではなく、true or falseで取り出すことができます。

const mysql = require('mysql');
const config = require('config');

let conf = config.db
// https://www.bennadel.com/blog/3188-casting-bit-fields-to-booleans-using-the-node-js-mysql-driver.htm
conf.typeCast = function castField(field, useDefaultTypeCasting) {
  // We only want to cast bit fields that have a single-bit in them. If the field
  // has more than one bit, then we cannot assume it is supposed to be a Boolean.
  if ((field.type === "BIT") && (field.length === 1)) {
    var bytes = field.buffer();
    // A Buffer in Node represents a collection of 8-bit unsigned integers.
    // Therefore, our single "bit field" comes back as the bits '0000 0001',
    // which is equivalent to the number 1.
    return (bytes[0] === 1);
  }
  return (useDefaultTypeCasting());
}

let connection = mysql.createPool(config.db);

module.exports = connection;

呼び出し側はこんな感じ

const moment = require('moment');
const path = require('path');
const config = require('config');
const connection = require(path.resolve(__dirname, '../modules/mysql-connection.js'));
const logger = require(path.resolve(__dirname, '../modules/logger.js')).dao;
const squel = require("squel");
const PRE = '[dao/good] '
const TABLE = "good"
const util = require('util')

const good = {
  isExists(userId, postId) {
    return new Promise(function (resolve, reject) {
      let query= squel.select({
          separator: "\n"
        }).field("userId").from(TABLE).where("userId=?", userId).where("postId=?", postId)
        .toString();
      logger.debug(PRE + `query: ${query}`);
      connection.query(query, function (err, rows) {
        if (err)
          reject(err);
        if (rows.length > 0) {
          resolve(true);
        } else {
          resolve(false);
        }
      });
    });
  }
}
module.exports = good;

 

IT, 開発