mirror of
https://github.com/balena-os/balena-supervisor.git
synced 2025-01-13 08:19:57 +00:00
c8d79c3b7d
Closes #598 Change-Type: patch Signed-off-by: Pablo Carranza Velez <pablo@resin.io>
34 lines
851 B
CoffeeScript
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)
|