c2bfbbc3e803da604969d47bdd0479216aba45a9
[cinaest] / src / plugins / catalog-sqlite.vala
1 /* This file is part of Cinaest.
2  *
3  * Copyright (C) 2009 Philipp Zabel
4  *
5  * Cinaest is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * Cinaest is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with Cinaest. If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 using Sqlite;
20
21 class CatalogSqlite : Object {
22         Database db;
23         SList<Movie> result;
24         int results_waiting;
25
26         public delegate void ReceiveMovieFunction (string title, int year, int rating, int genres);
27
28         public CatalogSqlite (string filename) {
29                 int rc;
30
31                 rc = Database.open (filename, out db);
32                 if (rc != Sqlite.OK) {
33                         stderr.printf ("Can't open database: %d, %s\n", rc, db.errmsg ());
34                         return;
35                 }
36
37                 rc = db.exec ("PRAGMA locking_mode = EXCLUSIVE;", callback, null);
38                 if (rc != Sqlite.OK) {
39                         stderr.printf ("Can't get exclusive lock: %d, %s\n", rc, db.errmsg ());
40                         return;
41                 }
42
43                 rc = db.exec ("PRAGMA synchronous = OFF;", callback, null);
44                 if (rc != Sqlite.OK)
45                         stderr.printf ("Can't turn off synchronous access: %d, %s\n", rc, db.errmsg ());
46
47                 prepare ();
48         }
49
50         public static int callback (int n_columns, string[] values,
51                                     string[] column_names) {
52                 for (int i = 0; i < n_columns; i++) {
53                         stdout.printf ("%s = %s\n", column_names[i], values[i]);
54                 }
55                 stdout.printf ("\n");
56
57                 return 0;
58         }
59
60         public int add_movie (string table, Movie movie) {
61                 string sql = "INSERT INTO %s(Title, Year, Rating, Genres) VALUES (\"%s\", %d, %d, %d);".printf (table, movie.title, movie.year, movie.rating, movie.genres.field);
62                 int rc;
63
64                 rc = db.exec (sql, callback, null);
65                 if (rc != Sqlite.OK) {
66                         stderr.printf ("Failed to insert movie \"%s\" (%d): %d, %s\n", movie.title, movie.year, rc, db.errmsg ());
67                         return 1;
68                 }
69
70                 return 0;
71         }
72
73         public int delete_movie (string table, Movie movie) {
74                 string sql = "DELETE FROM %s WHERE Title=\"%s\" AND Year=%d".printf (table, movie.title, movie.year);
75                 int rc;
76
77                 rc = db.exec (sql, callback, null);
78                 if (rc != Sqlite.OK) {
79                         stderr.printf ("Failed to delete movie \"%s\" (%d): %d, %s\n", movie.title, movie.year, rc, db.errmsg ());
80                         return 1;
81                 }
82
83                 return 0;
84         }
85
86         public int count (string table) {
87                 string sql = "SELECT count(*) FROM %s".printf (table);
88                 Statement stmt;
89                 int rc;
90                 int count = 0;
91
92                 rc = db.prepare_v2 (sql, -1, out stmt);
93                 if (rc != Sqlite.OK) {
94                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
95                         db.progress_handler (0, null);
96                         return 0;
97                 }
98
99                 do {
100                         rc = stmt.step ();
101                         if (rc == Sqlite.ROW) {
102                                 count = stmt.column_int (0);
103                         }
104                 } while (rc == Sqlite.ROW);
105
106                 return count;
107         }
108
109         public bool contains (string table, Movie movie) {
110                 string sql = "SELECT count(*) FROM %s WHERE Title=\"%s\" AND Year=%d".printf (table, movie.title, movie.year);
111                 Statement stmt;
112                 int rc;
113                 int count = 0;
114
115                 rc = db.prepare_v2 (sql, -1, out stmt);
116                 if (rc != Sqlite.OK) {
117                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
118                         db.progress_handler (0, null);
119                         return false;
120                 }
121
122                 do {
123                         rc = stmt.step ();
124                         if (rc == Sqlite.ROW) {
125                                 count = stmt.column_int (0);
126                         }
127                 } while (rc == Sqlite.ROW);
128
129                 return (count > 0);
130         }
131
132         private int prepare () {
133                 Statement stmt;
134                 int rc;
135
136                 rc = db.exec ("CREATE TABLE IF NOT EXISTS Collection (Title TEXT NOT NULL, Year INTEGER, Rating INTEGER, Genres INTEGER NOT NULL DEFAULT 0); " +
137                               "CREATE TABLE IF NOT EXISTS Loaned (Title TEXT NOT NULL, Year INTEGER, Rating INTEGER, Genres INTEGER NOT NULL DEFAULT 0); " +
138                               "CREATE TABLE IF NOT EXISTS Watched (Title TEXT NOT NULL, Year INTEGER, Rating INTEGER, Genres INTEGER NOT NULL DEFAULT 0, Date INTEGER); " +
139                               "CREATE TABLE IF NOT EXISTS Watchlist (Title TEXT NOT NULL, Year INTEGER, Rating INTEGER, Genres INTEGER NOT NULL DEFAULT 0);",
140                               callback, null);
141                 if (rc != Sqlite.OK) {
142                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
143                         return 1;
144                 }
145
146                 // Add a date column to the Watched table
147                 rc = db.prepare_v2 ("SELECT sql FROM sqlite_master WHERE (type = 'table' AND name = 'Watched');",
148                                     -1, out stmt);
149                 if (rc != Sqlite.OK) {
150                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
151                         return 1;
152                 }
153                 do {
154                         rc = stmt.step ();
155                         if (rc == Sqlite.ROW) {
156                                 var sql = stmt.column_text (0);
157                                 if (sql == "CREATE TABLE Watched (Title TEXT NOT NULL, Year INTEGER, Rating INTEGER, Genres INTEGER NOT NULL DEFAULT 0)") {
158                                         rc = db.exec ("ALTER TABLE Watched ADD COLUMN Date INTEGER;",
159                                                       callback, null);
160                                         if (rc != Sqlite.OK) {
161                                                 stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
162                                                 return 1;
163                                         }
164                                 }
165                                 break;
166                         }
167                 } while (rc == Sqlite.ROW);
168
169                 return 0;
170         }
171
172         public int clear () {
173                 int rc;
174
175                 rc = db.exec ("DROP TABLE IF EXISTS Collection; CREATE TABLE Collection (Title TEXT NOT NULL, Year INTEGER, Rating INTEGER, Genres INTEGER NOT NULL DEFAULT 0); DROP TABLE IF EXISTS Loaned; CREATE TABLE Loaned (Title TEXT NOT NULL, Year INTEGER, Rating INTEGER, Genres INTEGER NOT NULL DEFAULT 0); DROP TABLE IF EXISTS Watchlist; CREATE TABLE Watchlist (Title TEXT NOT NULL, Year INTEGER, Rating INTEGER, Genres INTEGER NOT NULL DEFAULT 0);", callback, null);
176                 if (rc != Sqlite.OK) {
177                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
178                         return 1;
179                 }
180
181                 return 0;
182         }
183
184         private Cancellable? _cancellable;
185         public async int query (string table, MovieFilter filter, MovieSource.ReceiveMovieFunction callback, int limit, Cancellable? cancellable) {
186                 var sql = new StringBuilder ();
187                 sql.append ("SELECT Title, Year, Rating, Genres");
188                 if (table == "Watched")
189                         sql.append (", Date");
190                 sql.append (" FROM ");
191                 sql.append (table);
192                 var sep = " WHERE ";
193                 Statement stmt;
194                 int rc;
195
196                 // FIXME - how many opcodes until main loop iteration for best responsivity?
197                 _cancellable = cancellable;
198                 db.progress_handler (1000, progress_handler);
199
200                 if (filter.title != null && filter.title != "") {
201                         if ("*" in filter.title) {
202                                 sql.append (sep);
203                                 sql.append_printf ("Title GLOB \"%s\"", filter.title);
204                         } else {
205                                 sql.append (sep);
206                                 sql.append_printf ("Title LIKE \"%s%%\"", filter.title);
207                         }
208                         sep = " AND ";
209                 }
210                 if (filter.year_min > 0) {
211                         sql.append (sep);
212                         sql.append_printf ("Year >= %d", filter.year_min);
213                         sep = " AND ";
214                 }
215                 if (filter.year_max > 0) {
216                         sql.append (sep);
217                         sql.append_printf ("Year <= %d", filter.year_max);
218                         sep = " AND ";
219                 }
220                 if (filter.rating_min > 0) {
221                         sql.append (sep);
222                         sql.append_printf ("Rating >= %d", filter.rating_min);
223                         sep = " AND ";
224                 }
225                 if (filter.genres.field != 0) {
226                         sql.append (sep);
227                         sql.append_printf ("Genres&%d = %d", filter.genres.field, filter.genres.field);
228                 }
229                 sql.append_printf (" LIMIT %d;", limit);
230
231                 stdout.printf("SQL: \"%s\"\n", sql.str);
232
233                 rc = db.prepare_v2 (sql.str, -1, out stmt);
234                 if (rc != Sqlite.OK) {
235                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
236                         db.progress_handler (0, null);
237                         return 1;
238                 }
239
240                 result = new SList<Movie> ();
241                 results_waiting = 0;
242
243                 do {
244                         Idle.add (query.callback);
245                         yield;
246                         rc = stmt.step ();
247                         if (rc == Sqlite.ROW) {
248                                 var movie = new Movie ();
249                                 movie.year = stmt.column_int (1);
250                                 movie.title = stmt.column_text (0);
251                                 movie.rating = stmt.column_int (2);
252                                 movie.genres.field = stmt.column_int (3);
253                                 // TODO - depending on settings, this could be something else, like director info or runtime
254                                 movie.secondary = movie.genres.to_string ();
255                                 result.append (movie);
256                                 if (++results_waiting >= 10) {
257                                         callback (result);
258                                         result = new SList<Movie> ();
259                                         results_waiting = 0;
260                                 }
261                         }
262                 } while (rc == Sqlite.ROW);
263
264                 if (results_waiting > 0)
265                         callback (result);
266                 result = new SList<Movie> ();
267
268                 db.progress_handler (0, null);
269                 return 0;
270         }
271
272         private int progress_handler () {
273                 ((MainContext) null).iteration (false);
274                 return (int) _cancellable.is_cancelled ();
275         }
276 }