Skip to content

Instantly share code, notes, and snippets.

@adrianolsk
Forked from kingsidharth/knex.column.deleted.js
Created November 29, 2017 01:36
Show Gist options
  • Save adrianolsk/b83f2a7a7c168c98f9a989b826f1dfe9 to your computer and use it in GitHub Desktop.
Save adrianolsk/b83f2a7a7c168c98f9a989b826f1dfe9 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