3 Readings.Catalogue = (function() {
5 function Catalogue() {}
7 Catalogue.prototype.open = function() {
9 version = Readings.config.get('db_version');
10 console.log("opening db ver " + version);
11 this.db = openDatabase('catalogue', version, 'Catalogue', 65535, this.init);
15 Catalogue.prototype.init = function(db) {
18 unneded_stmts = function(stmt, idx) {
19 return stmt.indexOf("PRAGMA") === 0 || stmt.indexOf("BEGIN TRANSACTION") === 0 || stmt.indexOf("COMMIT") === 0 || /^\s*$/.exec(stmt);
21 if (!(db != null)) db = this.db;
22 console.log("initializing DB");
23 db.changeVersion("", Readings.config.get('db_version'));
24 return $.ajax(Readings.config.get('initdburl'), {
27 success: function(sql) {
29 sql = sql.split(/;\n/);
30 sql = $.grep(sql, unneded_stmts, true);
31 create = function(tx) {
32 var stmt, _i, _len, _results;
34 for (_i = 0, _len = sql.length; _i < _len; _i++) {
36 _results.push(tx.executeSql(stmt, [], function(tx, rs) {
38 }, function(tx, err) {
39 console.error("error for " + stmt);
40 return console.error(err);
45 return db.transaction(create);
48 return console.error("can't get initial sql");
53 Catalogue.prototype.wrap_error = function(error_cb) {
54 return function(tx, error) {
55 window.last_error = error;
56 alert("SQL ERROR: " + error.message);
58 return error_cb(error);
65 Catalogue.prototype.map_rs = function(rs, mapper) {
68 for (i = 0, _ref = rs.rows.length; 0 <= _ref ? i < _ref : i > _ref; 0 <= _ref ? i++ : i--) {
69 objs.push(mapper(rs.rows.item(i)));
74 Catalogue.prototype.withCategory = function(category, callback, error) {
77 rs_to_tags = function(tx, data) {
80 for (i = 0, _ref = data.rows.length; 0 <= _ref ? i < _ref : i > _ref; 0 <= _ref ? i++ : i--) {
81 tags.push(new Readings.Tag(data.rows.item(i)));
83 return callback(tags);
85 return this.db.readTransaction(function(tx) {
86 return tx.executeSql("SELECT * FROM tag WHERE category=? ORDER BY sort_key", [category], rs_to_tags, _this.wrap_error(error));
90 Catalogue.prototype.withTag = function(tag_id, cb) {
92 return this.db.readTransaction(function(tx) {
93 return tx.executeSql("SELECT * FROM tag WHERE id=?", [tag_id], function(tx, rs) {
95 if (rs.rows.length > 0) {
96 tag = new Readings.Tag(rs.rows.item(0));
99 return alert("No tag id " + tag_id);
101 }, _this.wrap_error());
105 Catalogue.prototype.withBooks = function(tag, cb) {
107 return this.db.readTransaction(function(tx) {
108 console.log("books in tag: " + tag.books);
109 return tx.executeSql("SELECT * FROM book WHERE id IN (" + tag.books + ") ORDER BY sort_key", [], (function(tx, rs) {
110 return cb(_this.map_rs(rs, function(rec) {
111 return new Readings.Book(rec);
113 }), _this.wrap_error());