2 class Readings.Catalogue
4 version = Readings.config.get 'db_version'
5 console.log "opening db ver #{version}"
6 @db = openDatabase 'catalogue', version, 'Catalogue', 65535, @init
10 unneded_stmts = (stmt, idx) ->
11 stmt.indexOf("PRAGMA")==0 or
12 stmt.indexOf("BEGIN TRANSACTION")==0 or
13 stmt.indexOf("COMMIT")==0 or
18 console.log "initializing DB"
19 db.changeVersion "", Readings.config.get 'db_version'
20 $.ajax Readings.config.get('initdburl'),
25 sql = $.grep sql, unneded_stmts, true
29 tx.executeSql stmt, [],
32 console.error("error for #{stmt}")
37 console.error "can't get initial sql"
39 wrap_error: (error_cb) ->
41 window.last_error = error
42 alert "SQL ERROR: #{error.message}"
48 map_rs: (rs, mapper) ->
50 for i in [0...rs.rows.length]
51 objs.push(mapper(rs.rows.item(i)))
55 withCategory: (category, callback, error) ->
56 rs_to_tags = (tx, data) ->
58 for i in [0...data.rows.length]
59 tags.push new Readings.Tag(data.rows.item(i))
62 @db.readTransaction (tx)=>
63 tx.executeSql "SELECT * FROM tag WHERE category=? ORDER BY sort_key",
64 [category], rs_to_tags, @wrap_error(error)
66 withTag: (tag_id, cb) ->
67 @db.readTransaction (tx) =>
68 tx.executeSql "SELECT * FROM tag WHERE id=?", [tag_id],
71 tag = new Readings.Tag rs.rows.item(0)
74 alert "No tag id #{tag_id}"
78 withBooks: (tag, cb) ->
79 @db.readTransaction (tx) =>
80 console.log "books in tag: #{tag.books}"
81 tx.executeSql "SELECT * FROM book WHERE id IN (#{tag.books}) ORDER BY sort_key",
82 [], ((tx, rs) => cb(@map_rs(rs, (rec)->new Readings.Book(rec)))), @wrap_error()
84 fetchBook: (book_id, fetch_contents, cb) ->
85 unless typeof book_id == "number" or /^[0-9]+$/.exec book_id
86 throw Error "book_id = '#{book_id}' is not a number"
88 @db.readTransaction (tx) =>
89 tx.executeSql "SELECT * FROM book WHERE id=?", [book_id],
92 book = new Readings.Book rs.rows.item(0)
93 if fetch_contents and not book.is_local()