Skip to content

Instantly share code, notes, and snippets.

@iPotaje
Created April 19, 2016 13:19
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save iPotaje/89f48328c682b8a4f6f0b6e3874a6902 to your computer and use it in GitHub Desktop.
Save iPotaje/89f48328c682b8a4f6f0b6e3874a6902 to your computer and use it in GitHub Desktop.
Example of Sequelize with sql.js
var lib = require('./patch.js');
var Sequelize = require('sequelize');
var sequelize = new Sequelize('sqlite://dbname', {dialectModulePath: 'sql.js'});
var User = sequelize.define('user', {
username: Sequelize.STRING,
birthday: Sequelize.DATE
});
sequelize.sync().then(function() {
return User.create({
username: 'janedoe',
birthday: new Date(1980, 6, 20)
});
}).then(function(jane) {
console.log(jane.get({
plain: true
}));
});
"use strict";
var lib = require('sql.js');
lib.verbose = function() {
return lib;
}
lib._Database = lib.Database;
lib.Database = class Db extends lib._Database {
constructor(filename, mode, cb) {
super();
process.nextTick(cb, null);
}
//I'm not 100% sure what this was supposed to do on node-sqlite3, heh.
serialize(cb) {
process.nextTick(cb);
}
run(sql, params, cb) {
super.run(sql, params);
var ctx = {};
if (sql.toLowerCase().indexOf('insert') !== -1) {
var rez = this.exec("select last_insert_rowid();");
ctx.lastID = rez[0].values[0][0];
}
if (cb) {
process.nextTick(cb.bind(ctx), null);
}
return this;
}
all(sql, params, cb) {
var result = [];
this.each(sql, params,
function(r) {
result.push(r);
},
function() {
cb(null, result);
});
return this;
}
close () {
}
}
module.export = lib;
@iPotaje
Copy link
Author

iPotaje commented Apr 19, 2016

@oney
Copy link

oney commented Jun 4, 2020

@aniketbiprojit
Copy link

Thanks for copying. That issue is now missing. xD

@websemantics
Copy link

Thanks for the post. This helped with getting lastID

@catamphetamine
Copy link

catamphetamine commented Jun 26, 2023

Hi. I've made an npm package that could be used to make sql.js work with Sequelize without any patching (based on the gist code). In case anyone's interested:
https://www.npmjs.com/package/sql.js-as-sqlite3

Usage:

import Sequelize from 'sequelize'
import sqlJsAsSqlite3 from 'sql.js-as-sqlite3'

const sequelize = new Sequelize('sqlite://:memory:', {
  dialectModule: sqlJsAsSqlite3
})

@aniketbiprojit
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment