· 7 years ago · Oct 02, 2018, 05:48 PM
1class MiniOrm
2 constructor: (name, size)->
3 size ?= 500000
4 @db = Sql.openDatabaseSync(name, "1.0", "QMLStorage_"+name, size)
5 @ensure_db()
6
7
8
9 ensure_db: ->
10 schema = "CREATE TABLE IF NOT EXISTS elems(type TEXT NOT NULL, key TEXT NOT NULL, value TEXT)"
11 @sql schema, []
12
13 reset_db: ->
14 @sql "DROP TABLE elems", []
15 @ensure_db()
16
17
18 get: (typ, key) ->
19 sel = 'SELECT type,key,value FROM elems WHERE type = ? and KEY = ?'
20 res = @sql sel, [typ, key]
21 rows = res.rows
22 if rows.length > 1
23 lg "Abuse of MiniOrm, expected only 1 entry, got several"
24
25 else if rows.length == 0
26 return null
27
28 first = rows.item(0).value
29 #dump(first)
30 return JSON.parse(first)
31
32
33 dump: ->
34 sel = 'SELECT * FROM elems'
35 res = @sql sel, []
36 rows = res.rows
37 all = (rows.item(i) for i in [0..rows.length-1])
38
39 for r in all
40 dump(r)
41
42
43 add: (typ, key, value) ->
44 sel = "INSERT INTO elems(type, key, value) VALUES (?,?,?)"
45 #tval = JSON.stringify(value)
46 @db.transaction (tx) =>
47 tx.executeSql(sel, [typ, key, value])
48
49 update: (typ, key, newvalue) ->
50 sel = "UPDATE elems SET value = ? WHERE type=? AND key=?"
51 #tval = JSON.stringify(newvalue)
52 @db.transaction (tx) =>
53 tx.executeSql(sel, [newvalue, typ, key])
54
55
56 put: (typ, key, value) ->
57 tval = JSON.stringify(value)
58
59 r = @get typ, key
60
61 if r
62 @update(typ,key,tval)
63 else
64 @add(typ, key, tval)
65
66 sql: (stmt, args) ->
67 lg stmt + ", " + JSON.stringify(args)
68 rs = {}
69 @db.transaction (tx) =>
70 rs = tx.executeSql(stmt, args)
71 lg("Result: " + JSON.stringify(rs))
72 lg rs.rows.length
73 return rs
74
75
76
77
78
79class RedditController
80 constructor: ->
81 @views = {}
82 #@lcount = 0
83 @currentlink = {}
84 @loginAttempt = ""
85 @lcache = {}
86 @linkSelection = "hot"
87 @db = new MiniOrm("qmlreddit")
88 @db.reset_db()
89 #@db.add("_config", "local_subreddits","[ 'bestof', 'skyrim']" )
90 @db.put("_config", "local_subreddits", ["more", "good", "stuff (value overwritten)"])
91 @db.put("_config", "local_subreddits", ["last", "update"])
92 @db.dump()
93 rs = @db.get "_config", "local_subreddits"
94 lg "Got config value"
95 dump(rs)
96 @localcategories = []