Catalog plugin: store and retrieve the date field for watched movies
[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                 var sql = new StringBuilder ();
62                 int rc;
63                 sql.append_printf ("INSERT INTO %s(Title, Year, Rating, Genres", table);
64                 if (table == "Watched")
65                         sql.append_printf (", Date) VALUES (\"%s\", %d, %d, %d, %u);",
66                                            movie.title, movie.year, movie.rating, movie.genres.field, movie.julian_date);
67                 else
68                         sql.append_printf (") VALUES (\"%s\", %d, %d, %d);",
69                                            movie.title, movie.year, movie.rating, movie.genres.field);
70
71                 rc = db.exec (sql.str, callback, null);
72                 if (rc != Sqlite.OK) {
73                         stderr.printf ("Failed to insert movie \"%s\" (%d): %d, %s\n", movie.title, movie.year, rc, db.errmsg ());
74                         return 1;
75                 }
76
77                 return 0;
78         }
79
80         public int delete_movie (string table, Movie movie) {
81                 string sql = "DELETE FROM %s WHERE Title=\"%s\" AND Year=%d".printf (table, movie.title, movie.year);
82                 int rc;
83
84                 rc = db.exec (sql, callback, null);
85                 if (rc != Sqlite.OK) {
86                         stderr.printf ("Failed to delete movie \"%s\" (%d): %d, %s\n", movie.title, movie.year, rc, db.errmsg ());
87                         return 1;
88                 }
89
90                 return 0;
91         }
92
93         public int count (string table) {
94                 string sql = "SELECT count(*) FROM %s".printf (table);
95                 Statement stmt;
96                 int rc;
97                 int count = 0;
98
99                 rc = db.prepare_v2 (sql, -1, out stmt);
100                 if (rc != Sqlite.OK) {
101                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
102                         db.progress_handler (0, null);
103                         return 0;
104                 }
105
106                 do {
107                         rc = stmt.step ();
108                         if (rc == Sqlite.ROW) {
109                                 count = stmt.column_int (0);
110                         }
111                 } while (rc == Sqlite.ROW);
112
113                 return count;
114         }
115
116         public bool contains (string table, Movie movie) {
117                 string sql = "SELECT count(*) FROM %s WHERE Title=\"%s\" AND Year=%d".printf (table, movie.title, movie.year);
118                 Statement stmt;
119                 int rc;
120                 int count = 0;
121
122                 rc = db.prepare_v2 (sql, -1, out stmt);
123                 if (rc != Sqlite.OK) {
124                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
125                         db.progress_handler (0, null);
126                         return false;
127                 }
128
129                 do {
130                         rc = stmt.step ();
131                         if (rc == Sqlite.ROW) {
132                                 count = stmt.column_int (0);
133                         }
134                 } while (rc == Sqlite.ROW);
135
136                 return (count > 0);
137         }
138
139         private int prepare () {
140                 Statement stmt;
141                 int rc;
142
143                 rc = db.exec ("CREATE TABLE IF NOT EXISTS Collection (Title TEXT NOT NULL, Year INTEGER, Rating INTEGER, Genres INTEGER NOT NULL DEFAULT 0); " +
144                               "CREATE TABLE IF NOT EXISTS Loaned (Title TEXT NOT NULL, Year INTEGER, Rating INTEGER, Genres INTEGER NOT NULL DEFAULT 0); " +
145                               "CREATE TABLE IF NOT EXISTS Watched (Title TEXT NOT NULL, Year INTEGER, Rating INTEGER, Genres INTEGER NOT NULL DEFAULT 0, Date INTEGER); " +
146                               "CREATE TABLE IF NOT EXISTS Watchlist (Title TEXT NOT NULL, Year INTEGER, Rating INTEGER, Genres INTEGER NOT NULL DEFAULT 0);",
147                               callback, null);
148                 if (rc != Sqlite.OK) {
149                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
150                         return 1;
151                 }
152
153                 // Add a date column to the Watched table
154                 rc = db.prepare_v2 ("SELECT sql FROM sqlite_master WHERE (type = 'table' AND name = 'Watched');",
155                                     -1, out stmt);
156                 if (rc != Sqlite.OK) {
157                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
158                         return 1;
159                 }
160                 do {
161                         rc = stmt.step ();
162                         if (rc == Sqlite.ROW) {
163                                 var sql = stmt.column_text (0);
164                                 if (sql == "CREATE TABLE Watched (Title TEXT NOT NULL, Year INTEGER, Rating INTEGER, Genres INTEGER NOT NULL DEFAULT 0)") {
165                                         rc = db.exec ("ALTER TABLE Watched ADD COLUMN Date INTEGER;",
166                                                       callback, null);
167                                         if (rc != Sqlite.OK) {
168                                                 stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
169                                                 return 1;
170                                         }
171                                 }
172                                 break;
173                         }
174                 } while (rc == Sqlite.ROW);
175
176                 return 0;
177         }
178
179         public int clear () {
180                 int rc;
181
182                 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);
183                 if (rc != Sqlite.OK) {
184                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
185                         return 1;
186                 }
187
188                 return 0;
189         }
190
191         private Cancellable? _cancellable;
192         public async int query (string table, MovieFilter filter, MovieSource.ReceiveMovieFunction callback, int limit, Cancellable? cancellable) {
193                 var sql = new StringBuilder ();
194                 sql.append ("SELECT Title, Year, Rating, Genres");
195                 if (table == "Watched")
196                         sql.append (", Date");
197                 sql.append (" FROM ");
198                 sql.append (table);
199                 var sep = " WHERE ";
200                 Statement stmt;
201                 int rc;
202
203                 // FIXME - how many opcodes until main loop iteration for best responsivity?
204                 _cancellable = cancellable;
205                 db.progress_handler (1000, progress_handler);
206
207                 if (filter.title != null && filter.title != "") {
208                         if ("*" in filter.title) {
209                                 sql.append (sep);
210                                 sql.append_printf ("Title GLOB \"%s\"", filter.title);
211                         } else {
212                                 sql.append (sep);
213                                 sql.append_printf ("Title LIKE \"%s%%\"", filter.title);
214                         }
215                         sep = " AND ";
216                 }
217                 if (filter.year_min > 0) {
218                         sql.append (sep);
219                         sql.append_printf ("Year >= %d", filter.year_min);
220                         sep = " AND ";
221                 }
222                 if (filter.year_max > 0) {
223                         sql.append (sep);
224                         sql.append_printf ("Year <= %d", filter.year_max);
225                         sep = " AND ";
226                 }
227                 if (filter.rating_min > 0) {
228                         sql.append (sep);
229                         sql.append_printf ("Rating >= %d", filter.rating_min);
230                         sep = " AND ";
231                 }
232                 if (filter.genres.field != 0) {
233                         sql.append (sep);
234                         sql.append_printf ("Genres&%d = %d", filter.genres.field, filter.genres.field);
235                 }
236                 sql.append_printf (" LIMIT %d;", limit);
237
238                 stdout.printf("SQL: \"%s\"\n", sql.str);
239
240                 rc = db.prepare_v2 (sql.str, -1, out stmt);
241                 if (rc != Sqlite.OK) {
242                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
243                         db.progress_handler (0, null);
244                         return 1;
245                 }
246
247                 result = new SList<Movie> ();
248                 results_waiting = 0;
249
250                 do {
251                         Idle.add (query.callback);
252                         yield;
253                         rc = stmt.step ();
254                         if (rc == Sqlite.ROW) {
255                                 var movie = new Movie ();
256                                 movie.year = stmt.column_int (1);
257                                 movie.title = stmt.column_text (0);
258                                 movie.rating = stmt.column_int (2);
259                                 movie.genres.field = stmt.column_int (3);
260                                 if (table == "Watched")
261                                         movie.julian_date = stmt.column_int (4);
262                                 // TODO - depending on settings, this could be something else, like director info or runtime
263                                 movie.secondary = movie.genres.to_string ();
264                                 result.append (movie);
265                                 if (++results_waiting >= 10) {
266                                         callback (result);
267                                         result = new SList<Movie> ();
268                                         results_waiting = 0;
269                                 }
270                         }
271                 } while (rc == Sqlite.ROW);
272
273                 if (results_waiting > 0)
274                         callback (result);
275                 result = new SList<Movie> ();
276
277                 db.progress_handler (0, null);
278                 return 0;
279         }
280
281         private int progress_handler () {
282                 ((MainContext) null).iteration (false);
283                 return (int) _cancellable.is_cancelled ();
284         }
285 }