Skip to content

Instantly share code, notes, and snippets.

@kingsidharth
Last active November 29, 2017 01:36
Show Gist options
  • Save kingsidharth/634ec33983f35aa05dc404b4fe918029 to your computer and use it in GitHub Desktop.
Save kingsidharth/634ec33983f35aa05dc404b4fe918029 to your computer and use it in GitHub Desktop.
Knex.js Gotchas!
/* SINPPET FOR DELETED & DELETED AT SUPPORT IN KNEX.JS
inspired from Sequlize.js 'paranoid' schema option,
don't delete rows from database, ever.
*/
/* In Table Definition */
knex.schema.createTable('TABLE_NAME', function(table) {
table.boolean('deleted').defaultsTo(false).notNullable();
table.dateTime('deleted_at');
});
/* To Emulate Delete */
delete(id) {
return db.table('accounts').where({ id: id})
.returning('deleted')
.update({
deleted: true,
deleted_at: new Date()
});
}
/* Then When Handling Read or Search */
findAll() {
return db.select().from('TABLE_NAME').where({ deleted: false });
}
/* CORRECT HANDLING OF TIMESTAMPS IN KNEX.JS */
knex.schema.createTable('TABLE_NAME', function(table) {
table.timestamps(true, true); // Adds 'created_at' & 'updated_at' with both not nullable & default-ing to Date.now();
table.timestamps(); // Just adds 'created_at' & 'updated_at' with default null
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment