Skip to content

Instantly share code, notes, and snippets.

@zew13
Created September 16, 2019 03:59
Show Gist options
  • Select an option

  • Save zew13/38ff3b877ffc85b7339d8d477220c972 to your computer and use it in GitHub Desktop.

Select an option

Save zew13/38ff3b877ffc85b7339d8d477220c972 to your computer and use it in GitHub Desktop.
Knex = require('knex')
{isSet} = require 'lodash'
QueryBuilder = require('knex/lib/query/builder')
_transaction = Knex.Client.prototype.transaction
Knex.Client.prototype.transaction = (container, config)->
_transaction.call(
@
(trx)->
Object.assign(trx,extend)
container.apply @,arguments
config
)
Object.assign(
QueryBuilder.prototype
{
total:(where)->>
if where
q = @where(where)
else
q = @
return Object.values((await q.count())[0])[0]
get: (dict, column)->>
if parseInt(dict)
dict = {id:dict}
return (await @where(dict).select(column).limit(1))[0]
upsert:(dict, conflict)->>
table = @_single.table
kli = Object.keys(dict)
vli = Object.values(dict)
ks = kli.join(',')
if conflict
skli = []
svli = []
for i in conflict.split(",")
skli.push i
svli.push dict[i]
else
conflict = ks
skli = kli
svli = vli
if skli.length < kli.length
to_update = []
for i in kli
if not (skli.indexOf(i)+1)
to_update.push "#{i}=?"
vli.push dict[i]
DO = "UPDATE SET "+to_update.join(",")
else
DO = "NOTHING"
await @client.raw(
"INSERT INTO #{table} (#{ks}) VALUES (#{Array(kli.length).fill("?").join(',')}) ON CONFLICT(#{conflict}) DO #{DO}"
vli
)
query_li = ["#i=?" for i in skli]
return (await @client.raw(
"""SELECT id FROM #{table} WHERE #{query_li.join(' AND ')} LIMIT 1""", svli
)).rows[0].id
}
)
extend = {
one: ->>
return (await (@exec.apply(@,arguments)))[0]
_raw:->
args = []
for i in arguments
args.push i
sql = args.shift()
return @raw.call(
@
sql
args
)
li1:->>
r = []
for i in await @li.apply(@,arguments)
r.push i[0]
return r
li: ->>
{rows} = await @_raw.apply(@, arguments).options({rowMode:'array'})
return rows
exec : ->>
{rows} = await @_raw.apply(@, arguments)
return rows
}
module.exports = ->
pg = Knex.apply @,arguments
Object.assign(pg, extend)
pg.on(
'query-error'
(error, obj)->
console.error obj.sql
console.error obj.bindings
console.error error.toString()
)
return pg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment