balena-supervisor/src/db.coffee
Pablo Carranza Velez c8d79c3b7d Remove any leftover knex migrations locks before running migrations
Closes #598
Change-Type: patch
Signed-off-by: Pablo Carranza Velez <pablo@resin.io>
2018-03-21 18:20:15 -03:00

34 lines
851 B
CoffeeScript

Knex = require 'knex'
path = require 'path'
constants = require './lib/constants'
module.exports = class DB
constructor: ({ @databasePath } = {}) ->
@databasePath ?= constants.databasePath
@knex = Knex(
client: 'sqlite3'
connection:
filename: @databasePath
useNullAsDefault: true
)
init: =>
@knex('knex_migrations_lock').update({ is_locked: 0 })
.catch(->) # Knex doesn't return a bluebird promise here so we can't catchReturn :(
.then =>
@knex.migrate.latest(directory: path.join(__dirname, 'migrations'))
# Returns a knex object for one of the models (tables)
models: (modelName) =>
@knex(modelName)
upsertModel: (modelName, obj, id, trx) =>
knex = trx ? @knex
knex(modelName).update(obj).where(id)
.then (n) ->
if n == 0
knex(modelName).insert(obj)
transaction: (cb) =>
@knex.transaction(cb)