Skip to content

Instantly share code, notes, and snippets.

@kbanman
Created October 28, 2013 07:01
Show Gist options
  • Save kbanman/7192432 to your computer and use it in GitHub Desktop.
Save kbanman/7192432 to your computer and use it in GitHub Desktop.
Demo of strange behaviour in KnexJS when inserting into a table whose primary key is a string
// Knex 0.4.11
var Knex = require('knex');
var Q = require('q');
var DB = Knex.initialize({
client: 'mysql',
connection: {
adapter: 'mysql',
database: 'temp',
user: 'root',
password : ''
},
});
var createVanilla = function() {
return DB.schema.hasTable('vanilla').then(function(exists) {
if (exists) return Q();
console.log('govanilla');
return DB.schema.createTable('vanilla', function(t) {
t.increments('id').primary();
//t.dateTime('created_at').defaultTo(DB.raw('CURRENT_TIMESTAMP'));
t.string('name');
}).then(function(result) {
console.log('created vanilla table');
return result;
});
});
};
var createStringy = function() {
return DB.schema.hasTable('stringy').then(function(exists) {
if (exists) return Q();
console.log('gostringy');
return DB.schema.createTable('stringy', function(t) {
t.string('id').primary().notNullable();
//t.dateTime('created_at').defaultTo(DB.raw('CURRENT_TIMESTAMP'));
t.string('name');
}).then(function(result) {
console.log('created stringy table');
return result;
});
});
};
var createTables = function() {
return Q.all([
createVanilla(),
createStringy(),
]);
};
var insertObj = function() {
var obj = {
//created_at: new Date,
name: 'test',
};
console.log('insertObj', obj);
return DB('vanilla').insert(obj, 'id').then(function(ids) {
console.log('Inserted', obj, ids);
return ids;
});
}
var insertStringy = function() {
var obj = {
id: 'string-'+parseInt(Math.random()*1000),
//created_at: new Date,
name: 'test'
};
console.log('insertStringy', obj);
return DB('stringy').insert(obj, 'id').then(function(ids) {
console.log('Inserted', obj, ids);
return ids;
});
};
createTables()
.then(function(result) {
return Q.all([
insertObj(),
insertStringy(),
]).fail(function(err) {
console.log('Error inserting rows', err);
});
}, function(err) {
console.log('Error creating tables', err);
})
.then(function(results) {
console.log('inserts', results);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment