Created
November 21, 2016 12:25
-
-
Save bennadel/2510dc96a4f596e22d635a2242e37f8c to your computer and use it in GitHub Desktop.
Casting Bit Fields To Booleans Using The Node.js MySQL Driver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Import the core node modules. | |
var mysql = require( "mysql" ); | |
// Create the connection to your database. This time, we're going to use our own custom | |
// type casting function to manually coerce some of the columns. | |
var db = mysql.createConnection({ | |
host: "localhost", | |
user: "root", | |
password: "", | |
database: "testing", | |
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() ); | |
} | |
}); | |
// Gather records that we know contain a BIT column. | |
db.query( | |
` | |
SELECT | |
id, | |
name, | |
isBFF -- This is a BIT field. | |
FROM | |
friend | |
`, | |
function handleResults( error, rows ) { | |
console.log( "Results:" ); | |
console.log( rows ); | |
} | |
); | |
// Gracefully close the connection to the database (queued queries will still run). | |
db.end(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Import the core node modules. | |
var mysql = require( "mysql" ); | |
// Create the connection to your database. We're going to use the default | |
// type casting algorithms. | |
var db = mysql.createConnection({ | |
host: "localhost", | |
user: "root", | |
password: "", | |
database: "testing" | |
}); | |
// Gather records that we know contain a BIT column. | |
db.query( | |
` | |
SELECT | |
id, | |
name, | |
isBFF -- This is a BIT field. | |
FROM | |
friend | |
`, | |
function handleResults( error, rows ) { | |
console.log( "Results:" ); | |
console.log( rows ); | |
} | |
); | |
// Gracefully close the connection to the database (queued queries will still run). | |
db.end(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment