Skip to content

Instantly share code, notes, and snippets.

@vivainio
Created April 22, 2012 09:11
Show Gist options
  • Save vivainio/2462851 to your computer and use it in GitHub Desktop.
Save vivainio/2462851 to your computer and use it in GitHub Desktop.
class MiniOrm
constructor: (name, size)->
size ?= 500000
@db = Sql.openDatabaseSync(name, "1.0", "QMLStorage_"+name, size)
@ensure_db()
ensure_db: ->
schema = "CREATE TABLE IF NOT EXISTS elems(type TEXT NOT NULL, key TEXT NOT NULL, value TEXT)"
@sql schema, []
reset_db: ->
@sql "DROP TABLE elems", []
@ensure_db()
get: (typ, key) ->
sel = 'SELECT type,key,value FROM elems WHERE type = ? and KEY = ?'
res = @sql sel, [typ, key]
rows = res.rows
if rows.length > 1
lg "Abuse of MiniOrm, expected only 1 entry, got several"
else if rows.length == 0
return null
first = rows.item(0).value
#dump(first)
return JSON.parse(first)
dump: ->
sel = 'SELECT * FROM elems'
res = @sql sel, []
rows = res.rows
all = (rows.item(i) for i in [0..rows.length-1])
for r in all
dump(r)
add: (typ, key, value) ->
sel = "INSERT INTO elems(type, key, value) VALUES (?,?,?)"
#tval = JSON.stringify(value)
@db.transaction (tx) =>
tx.executeSql(sel, [typ, key, value])
update: (typ, key, newvalue) ->
sel = "UPDATE elems SET value = ? WHERE type=? AND key=?"
#tval = JSON.stringify(newvalue)
@db.transaction (tx) =>
tx.executeSql(sel, [newvalue, typ, key])
put: (typ, key, value) ->
tval = JSON.stringify(value)
r = @get typ, key
if r
@update(typ,key,tval)
else
@add(typ, key, tval)
sql: (stmt, args) ->
lg stmt + ", " + JSON.stringify(args)
rs = {}
@db.transaction (tx) =>
rs = tx.executeSql(stmt, args)
lg("Result: " + JSON.stringify(rs))
lg rs.rows.length
return rs
class RedditController
constructor: ->
@views = {}
#@lcount = 0
@currentlink = {}
@loginAttempt = ""
@lcache = {}
@linkSelection = "hot"
@db = new MiniOrm("qmlreddit")
@db.reset_db()
#@db.add("_config", "local_subreddits","[ 'bestof', 'skyrim']" )
@db.put("_config", "local_subreddits", ["more", "good", "stuff (value overwritten)"])
@db.put("_config", "local_subreddits", ["last", "update"])
@db.dump()
rs = @db.get "_config", "local_subreddits"
lg "Got config value"
dump(rs)
@localcategories = []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment