10065c06048a652ce1ce844f93b1857739d0349f
[cinaest] / src / imdb / imdb-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 IMDbSqlite : Object {
22         Database db;
23         List<string> genres;
24
25         public delegate void ReceiveMovieFunction (string title, string? aka, int year, int rating, int genres);
26
27         public IMDbSqlite (string filename) {
28                 int rc;
29
30                 genres = new List<string> ();
31
32                 rc = Database.open (filename, out db);
33                 if (rc != Sqlite.OK) {
34                         stderr.printf ("Can't open database: %d, %s\n", rc, db.errmsg ());
35                         return;
36                 }
37
38                 rc = db.exec ("PRAGMA journal_mode = OFF;", callback, null);
39                 if (rc != Sqlite.OK) {
40                         stderr.printf ("Can't turn off journal mode: %d, %s\n", rc, db.errmsg ());
41                         return;
42                 }
43
44                 rc = db.exec ("PRAGMA locking_mode = EXCLUSIVE;", callback, null);
45                 if (rc != Sqlite.OK) {
46                         stderr.printf ("Can't get exclusive lock: %d, %s\n", rc, db.errmsg ());
47                         return;
48                 }
49
50                 rc = db.exec ("PRAGMA synchronous = OFF;", callback, null);
51                 if (rc != Sqlite.OK)
52                         stderr.printf ("Can't turn off synchronous access: %d, %s\n", rc, db.errmsg ());
53
54         }
55
56         public static int callback (int n_columns, string[] values,
57                                     string[] column_names) {
58                 for (int i = 0; i < n_columns; i++) {
59                         stdout.printf ("%s = %s\n", column_names[i], values[i]);
60                 }
61                 stdout.printf ("\n");
62
63                 return 0;
64         }
65
66         public int add_movie (string title, int year) {
67                 string sql = "INSERT INTO Movies(Title, Year) VALUES (\"%s\", %d);".printf (title, year);
68                 int rc;
69
70                 rc = db.exec (sql, callback, null);
71                 if (rc != Sqlite.OK) {
72                         stderr.printf ("Failed to insert movie \"%s\" (%d): %d, %s\n", title, year, rc, db.errmsg ());
73                         return 1;
74                 }
75
76                 return 0;
77         }
78
79         public int movie_set_rating (string title, int rating, int votes) {
80                 var sql = "UPDATE Movies SET Rating=%d, Votes=%d WHERE Title=\"%s\";".printf (rating, votes, title);
81                 int rc;
82
83                 rc = db.exec (sql, callback, null);
84                 if (rc != Sqlite.OK) {
85                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
86                         return 1;
87                 }
88
89                 return 0;
90         }
91
92         public int movie_add_genre (string title, string genre) {
93                 string sql;
94                 int bit;
95                 int rc;
96
97                 bit = genre_bit (genre);
98                 if (bit == 0) {
99                         genres.append (genre);
100                         bit = genre_bit (genre);
101
102                         sql = "INSERT INTO Genres(Bit, Genre) VALUES (%d, \"%s\");".printf (bit, genre);
103
104                         rc = db.exec (sql, callback, null);
105                         if (rc != Sqlite.OK) {
106                                 stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
107                                 return 1;
108                         }
109                 }
110
111                 sql = "UPDATE Movies SET Genres=Genres|%d WHERE Title=\"%s\";".printf (bit, title);
112                 rc = db.exec (sql, callback, null);
113                 if (rc != Sqlite.OK) {
114                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
115                         return 1;
116                 }
117
118                 return 0;
119         }
120
121         int genre_bit (string genre) {
122                 for (int i = 0; i < genres.length (); i++) {
123                         if (genres.nth_data (i) == genre)
124                                 return 1 << i;
125                 }
126                 return 0;
127         }
128
129         public int add_aka (string title, string aka) {
130                 int rowid;
131
132                 if (!movie_exists (title, out rowid))
133                         return 1;
134
135                 string sql = "INSERT INTO Akas(Aka, TitleID) VALUES (\"%s\", %d);".printf (aka, rowid);
136                 int rc;
137                 rc = db.exec (sql, callback, null);
138                 if (rc != Sqlite.OK) {
139                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
140                         return 1;
141                 }
142
143                 return 0;
144         }
145
146         public int add_plot (string title, string plot, string? author) {
147                 int rowid;
148
149                 if (!movie_exists (title, out rowid))
150                         return 1;
151
152                 string sql;
153                 if (author != null) {
154                         sql = "INSERT INTO Plots(rowid, Plot, Author) VALUES (%d, \"%s\", \"%s\");".printf (rowid, plot.replace ("\"", "&quot;"), author.replace ("\"", "&quot;"));
155                 } else {
156                         sql = "INSERT INTO Plots(rowid, Plot) VALUES (%d, \"%s\");".printf (rowid, plot.replace ("\"", "&quot;"));
157                 }
158                 int rc;
159                 rc = db.exec (sql, callback, null);
160                 if (rc != Sqlite.OK) {
161                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
162                         stderr.printf ("offending SQL: %s\n", sql);
163                         return 1;
164                 }
165
166                 return 0;
167         }
168
169         public bool movie_exists (string title, out int rowid = null) {
170                 string sql = "SELECT rowid FROM Movies WHERE Title=\"%s\"".printf (title);
171                 Statement stmt;
172                 int rc;
173
174                 rc = db.prepare_v2 (sql, -1, out stmt);
175                 if (rc != Sqlite.OK) {
176                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
177                         return false;
178                 }
179
180                 do {
181                         rc = stmt.step ();
182                         if (rc == Sqlite.ROW) {
183                                 if (&rowid != null) {
184                                         rowid = stmt.column_int (0);
185                                 }
186                                 return true;
187                         }
188                 } while (rc == Sqlite.ROW);
189
190                 return false;
191         }
192
193         public int count (string table) {
194                 string sql = "SELECT count(*) FROM %s".printf (table);
195                 Statement stmt;
196                 int rc;
197                 int count = 0;
198
199                 rc = db.prepare_v2 (sql, -1, out stmt);
200                 if (rc != Sqlite.OK) {
201                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
202                         db.progress_handler (0, null);
203                         return 0;
204                 }
205
206                 do {
207                         rc = stmt.step ();
208                         if (rc == Sqlite.ROW) {
209                                 count = stmt.column_int (0);
210                         }
211                 } while (rc == Sqlite.ROW);
212
213                 return count;
214         }
215
216         public bool has_plots () {
217                 return (count ("Plots") > 0);
218         }
219
220         public string get_plot (string title) {
221                 string sql = "SELECT Plot FROM Plots WHERE rowid in (SELECT rowid FROM Movies WHERE Title=\"%s\")".printf (title);
222                 Statement stmt;
223                 int rc;
224                 int count = 0;
225
226                 rc = db.prepare_v2 (sql, -1, out stmt);
227                 if (rc != Sqlite.OK) {
228                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
229                         db.progress_handler (0, null);
230                         return "";
231                 }
232
233                 do {
234                         rc = stmt.step ();
235                         if (rc == Sqlite.ROW) {
236                                 return stmt.column_text (0).replace ("&quot;", "\"");
237                         }
238                 } while (rc == Sqlite.ROW);
239
240                 return "";
241         }
242
243         public int clear () {
244                 int rc;
245
246                 rc = db.exec (
247                         "DROP TABLE IF EXISTS Movies;" +
248                         "CREATE TABLE Movies (Title TEXT PRIMARY KEY COLLATE NOCASE, Year INTEGER, Rating INTEGER, Votes INTEGER NOT NULL DEFAULT 0, Genres INTEGER NOT NULL DEFAULT 0);" +
249                         "DROP TABLE IF EXISTS Genres;" +
250                         "CREATE TABLE Genres (Bit INTEGER PRIMARY KEY, Genre TEXT NOT NULL);" +
251                         "DROP TABLE IF EXISTS Akas;" +
252                         "CREATE TABLE Akas (Aka TEXT NOT NULL COLLATE NOCASE, TitleID INTEGER NOT NULL);" +
253                         "DROP TABLE IF EXISTS Plots;" +
254                         "CREATE TABLE Plots (Plot TEXT NOT NULL, Author TEXT)",
255                         callback, null);
256                 if (rc != Sqlite.OK) {
257                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
258                         return 1;
259                 }
260
261                 return 0;
262         }
263
264         public int create_aka_index () {
265                 int rc;
266
267                 rc = db.exec ("CREATE INDEX AkasAka ON Akas(Aka);", callback, null);
268                 if (rc != Sqlite.OK) {
269                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
270                         return 1;
271                 }
272
273                 return 0;
274         }
275
276         public int create_votes_index () {
277                 int rc;
278
279                 rc = db.exec ("CREATE INDEX MovieVotes ON Movies(Votes);", callback, null);
280                 if (rc != Sqlite.OK) {
281                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
282                         return 1;
283                 }
284
285                 return 0;
286         }
287
288         private Cancellable? _cancellable;
289         public async int query (MovieFilter filter, ReceiveMovieFunction receive_movie, int limit, Cancellable? cancellable) {
290                 var sql = "SELECT Title, Year, Rating, Genres FROM Movies";
291                 var sep = " WHERE ";
292                 string match = null;
293                 Statement stmt;
294                 int rc;
295
296                 // FIXME - how many opcodes until main loop iteration for best responsivity?
297                 _cancellable = cancellable;
298                 db.progress_handler (1000, progress_handler);
299
300                 if (filter.title != null && filter.title != "") {
301                         if ("*" in filter.title) {
302                                 match = "GLOB \"%s (*)\"".printf (filter.title);
303                         } else {
304                                 match = "LIKE \"%s%%\"".printf (filter.title);
305                         }
306                         sql += sep + "(Title %s OR rowid IN (SELECT TitleID FROM Akas WHERE Aka %s))".printf (match, match);
307                         sep = " AND ";
308                 }
309                 if (filter.year_min > 0) {
310                         sql += sep + "Year >= %d".printf (filter.year_min);
311                         sep = " AND ";
312                 }
313                 if (filter.year_max > 0) {
314                         sql += sep + "Year <= %d".printf (filter.year_max);
315                         sep = " AND ";
316                 }
317                 if (filter.rating_min > 0) {
318                         sql += sep + "Rating >= %d".printf (filter.rating_min);
319                         sep = " AND ";
320                 }
321                 if (filter.genres.field != 0) {
322                         sql += sep + "Genres&%d = %d".printf (filter.genres.field, filter.genres.field);
323                 }
324                 sql += " ORDER BY Votes DESC LIMIT %d;".printf (limit + 1);
325
326                 stdout.printf("SQL: \"%s\"\n", sql);
327
328                 rc = db.prepare_v2 (sql, -1, out stmt);
329                 if (rc != Sqlite.OK) {
330                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
331                         db.progress_handler (0, null);
332                         return 0;
333                 }
334
335                 int n = 0;
336                 do {
337                         if (++n > limit)
338                                 break;
339                         Idle.add (query.callback);
340                         yield;
341                         rc = stmt.step ();
342                         if (rc == Sqlite.ROW) {
343                                 int year = stmt.column_int (1);
344                                 string title = stmt.column_text (0);
345                                 int rating;
346                                 if (stmt.column_type (2) != Sqlite.NULL)
347                                         rating = stmt.column_int (2);
348                                 else
349                                         rating = -1;
350                                 int genres = stmt.column_int (3);
351                                 string aka = null;
352                                 if (match != null && !(filter.matches_title (strip_year (title, year)))) {
353                                         aka = movie_aka (title, match);
354                                         if (aka != null)
355                                                 aka = strip_year (aka, year);
356                                 }
357                                 receive_movie (strip_year (title, year), aka, year, rating, genres);
358                         }
359                 } while (rc == Sqlite.ROW);
360
361                 db.progress_handler (0, null);
362                 return n;
363         }
364
365         private string? movie_aka (string title, string match) {
366                 string sql = "SELECT Aka FROM Akas WHERE (TitleID = (SELECT rowid FROM Movies WHERE Title = \"%s\") AND Aka %s) LIMIT 1;".printf (title, match);
367                 Statement stmt;
368                 int rc;
369                 string aka = null;
370
371                 rc = db.prepare_v2 (sql, -1, out stmt);
372                 if (rc != Sqlite.OK) {
373                         stderr.printf ("SQL error: %d, %s\n", rc, db.errmsg ());
374                         return null;
375                 }
376
377                 do {
378                         rc = stmt.step ();
379                         if (rc == Sqlite.ROW) {
380                                 aka = stmt.column_text (0);
381                         }
382                 } while (rc == Sqlite.ROW);
383
384                 return aka;
385         }
386
387         private int progress_handler () {
388                 ((MainContext) null).iteration (false);
389                 return (int) _cancellable.is_cancelled ();
390         }
391
392         private string strip_year (string title, int year) {
393                 string year_suffix = " (%d)".printf (year);
394                 if (title.has_suffix (year_suffix))
395                         return title.substring (0, title.length - year_suffix.length);
396                 year_suffix = " (%d/I)".printf (year);
397                 if (title.has_suffix (year_suffix))
398                         return title.substring (0, title.length - year_suffix.length);
399                 year_suffix = " (%d/II)".printf (year);
400                 if (title.has_suffix (year_suffix))
401                         return title.substring (0, title.length - year_suffix.length);
402                 return title.dup ();
403         }
404 }