1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
|
/* Copyright 2016 Software Freedom Conservancy Inc.
*
* This software is licensed under the GNU LGPL (version 2.1 or later).
* See the COPYING file in this distribution.
*/
public errordomain DatabaseError {
ERROR,
BACKING,
MEMORY,
ABORT,
LIMITS,
TYPESPEC
}
public abstract class DatabaseTable {
/***
* This number should be incremented every time any database schema is altered.
*
* NOTE: Adding or removing tables or removing columns do not need a new schema version, because
* tables are created on demand and tables and columns are easily ignored when already present.
* However, the change should be noted in upgrade_database() as a comment.
***/
public const int SCHEMA_VERSION = 24;
protected static Sqlite.Database db;
private static int in_transaction = 0;
public string table_name = null;
static Gee.HashMap<string, Regex> regex_map;
private static void regexp_replace(Sqlite.Context context, Sqlite.Value[] args) {
var pattern = args[0].to_text();
if (pattern == null) {
context.result_error("Missing regular expression", Sqlite.ERROR);
return;
}
var text = args[1].to_text();
if (text == null) {
return;
}
var replacement = args[2].to_text();
if (replacement == null) {
context.result_value(args[1]);
return;
}
Regex re;
if (regex_map == null) {
regex_map = new Gee.HashMap<string, Regex>();
}
if (regex_map.has_key(pattern)) {
re = regex_map[pattern];
} else {
try {
re = new Regex(pattern, RegexCompileFlags.DEFAULT, RegexMatchFlags.DEFAULT);
regex_map[pattern] = re;
} catch (Error err) {
context.result_error("Invalid pattern: %s".printf(err.message), Sqlite.ERROR);
return;
}
}
try {
var result = re.replace(text, -1, 0, replacement, RegexMatchFlags.DEFAULT);
context.result_text(result);
} catch (Error err) {
context.result_error("Replacement failed: %s".printf(err.message), Sqlite.ERROR);
}
}
[CCode (cname="SQLITE_DETERMINISTIC", cheader_filename="sqlite3.h")]
extern static int SQLITE_DETERMINISTIC;
private static void prepare_db(string filename) {
// Open DB.
int res = Sqlite.Database.open_v2(filename, out db, Sqlite.OPEN_READWRITE | Sqlite.OPEN_CREATE,
null);
db.create_function("regexp_replace", 3, Sqlite.UTF8 | SQLITE_DETERMINISTIC, null,
DatabaseTable.regexp_replace, null, null);
if (res != Sqlite.OK)
AppWindow.panic(_("Unable to open/create photo database %s: error code %d").printf(filename,
res));
// Check if we have write access to database.
if (filename != Db.IN_MEMORY_NAME) {
try {
File file_db = File.new_for_path(filename);
FileInfo info = file_db.query_info(FileAttribute.ACCESS_CAN_WRITE, FileQueryInfoFlags.NONE);
if (!info.get_attribute_boolean(FileAttribute.ACCESS_CAN_WRITE))
AppWindow.panic(_("Unable to write to photo database file:\n %s").printf(filename));
} catch (Error e) {
AppWindow.panic(_("Error accessing database file:\n %s\n\nError was: \n%s").printf(filename,
e.message));
}
}
unowned string? sql_debug = Environment.get_variable
("SHOTWELL_SQL_DEBUG");
if (sql_debug != null && sql_debug != "") {
db.trace (on_trace);
}
}
public static void on_trace (string message) {
debug ("SQLITE: %s", message);
}
public static void init(string filename) {
// Open DB.
prepare_db(filename);
// Try a query to make sure DB is intact; if not, try to use the backup
Sqlite.Statement stmt;
int res = db.prepare_v2("CREATE TABLE IF NOT EXISTS VersionTable ("
+ "id INTEGER PRIMARY KEY, "
+ "schema_version INTEGER, "
+ "app_version TEXT, "
+ "user_data TEXT NULL"
+ ")", -1, out stmt);
// Query on db failed, copy over backup and open it
if(res != Sqlite.OK) {
db = null;
string backup_path = filename + ".bak";
try {
File src = File.new_for_commandline_arg(backup_path);
File dest = File.new_for_commandline_arg(filename);
src.copy(dest,
FileCopyFlags.OVERWRITE |
FileCopyFlags.ALL_METADATA);
prepare_db(filename);
} catch (Error error) {
AppWindow.panic(_("Unable to restore photo database %s").printf(error.message));
}
}
// disable synchronized commits for performance reasons ... this is not vital, hence we
// don't error out if this fails
res = db.exec("PRAGMA synchronous=OFF");
if (res != Sqlite.OK)
warning("Unable to disable synchronous mode", res);
}
public static void terminate() {
// freeing the database closes it
db = null;
}
// XXX: errmsg() is global, and so this will not be accurate in a threaded situation
protected static void fatal(string op, int res) {
error("%s: [%d] %s", op, res, db.errmsg());
}
// XXX: errmsg() is global, and so this will not be accurate in a threaded situation
protected static void warning(string op, int res) {
GLib.warning("%s: [%d] %s", op, res, db.errmsg());
}
protected void set_table_name(string table_name) {
this.table_name = table_name;
}
// This method will throw an error on an SQLite return code unless it's OK, DONE, or ROW, which
// are considered normal results.
protected static void throw_error(string method, int res) throws DatabaseError {
string msg = "(%s) [%d] - %s".printf(method, res, db.errmsg());
switch (res) {
case Sqlite.OK:
case Sqlite.DONE:
case Sqlite.ROW:
return;
case Sqlite.PERM:
case Sqlite.BUSY:
case Sqlite.READONLY:
case Sqlite.IOERR:
case Sqlite.CORRUPT:
case Sqlite.CANTOPEN:
case Sqlite.NOLFS:
case Sqlite.AUTH:
case Sqlite.FORMAT:
case Sqlite.NOTADB:
throw new DatabaseError.BACKING(msg);
case Sqlite.NOMEM:
throw new DatabaseError.MEMORY(msg);
case Sqlite.ABORT:
case Sqlite.LOCKED:
case Sqlite.INTERRUPT:
throw new DatabaseError.ABORT(msg);
case Sqlite.FULL:
case Sqlite.EMPTY:
case Sqlite.TOOBIG:
case Sqlite.CONSTRAINT:
case Sqlite.RANGE:
throw new DatabaseError.LIMITS(msg);
case Sqlite.SCHEMA:
case Sqlite.MISMATCH:
throw new DatabaseError.TYPESPEC(msg);
case Sqlite.ERROR:
case Sqlite.INTERNAL:
case Sqlite.MISUSE:
default:
throw new DatabaseError.ERROR(msg);
}
}
protected bool exists_by_id(int64 id) {
Sqlite.Statement stmt;
int res = db.prepare_v2("SELECT id FROM %s WHERE id=?".printf(table_name), -1, out stmt);
assert(res == Sqlite.OK);
res = stmt.bind_int64(1, id);
assert(res == Sqlite.OK);
res = stmt.step();
if (res != Sqlite.ROW && res != Sqlite.DONE)
fatal("exists_by_id [%s] %s".printf(id.to_string(), table_name), res);
return (res == Sqlite.ROW);
}
protected bool select_by_id(int64 id, string columns, out Sqlite.Statement stmt) {
string sql = "SELECT %s FROM %s WHERE id=?".printf(columns, table_name);
int res = db.prepare_v2(sql, -1, out stmt);
assert(res == Sqlite.OK);
res = stmt.bind_int64(1, id);
assert(res == Sqlite.OK);
res = stmt.step();
if (res != Sqlite.ROW && res != Sqlite.DONE)
fatal("select_by_id [%s] %s %s".printf(id.to_string(), table_name, columns), res);
return (res == Sqlite.ROW);
}
// Caller needs to bind value #1 before calling execute_update_by_id()
private void prepare_update_by_id(int64 id, string column, out Sqlite.Statement stmt) {
string sql = "UPDATE %s SET %s=? WHERE id=?".printf(table_name, column);
int res = db.prepare_v2(sql, -1, out stmt);
assert(res == Sqlite.OK);
res = stmt.bind_int64(2, id);
assert(res == Sqlite.OK);
}
private bool execute_update_by_id(Sqlite.Statement stmt) {
int res = stmt.step();
if (res != Sqlite.DONE) {
fatal("execute_update_by_id", res);
return false;
}
return true;
}
protected bool update_text_by_id(int64 id, string column, string text) {
Sqlite.Statement stmt;
prepare_update_by_id(id, column, out stmt);
int res = stmt.bind_text(1, text);
assert(res == Sqlite.OK);
return execute_update_by_id(stmt);
}
protected void update_text_by_id_2(int64 id, string column, string text) throws DatabaseError {
Sqlite.Statement stmt;
prepare_update_by_id(id, column, out stmt);
int res = stmt.bind_text(1, text);
assert(res == Sqlite.OK);
res = stmt.step();
if (res != Sqlite.DONE)
throw_error("DatabaseTable.update_text_by_id_2 %s.%s".printf(table_name, column), res);
}
protected bool update_int_by_id(int64 id, string column, int value) {
Sqlite.Statement stmt;
prepare_update_by_id(id, column, out stmt);
int res = stmt.bind_int(1, value);
assert(res == Sqlite.OK);
return execute_update_by_id(stmt);
}
protected void update_int_by_id_2(int64 id, string column, int value) throws DatabaseError {
Sqlite.Statement stmt;
prepare_update_by_id(id, column, out stmt);
int res = stmt.bind_int(1, value);
assert(res == Sqlite.OK);
res = stmt.step();
if (res != Sqlite.DONE)
throw_error("DatabaseTable.update_int_by_id_2 %s.%s".printf(table_name, column), res);
}
protected bool update_int64_by_id(int64 id, string column, int64 value) {
Sqlite.Statement stmt;
prepare_update_by_id(id, column, out stmt);
int res = stmt.bind_int64(1, value);
assert(res == Sqlite.OK);
return execute_update_by_id(stmt);
}
protected void update_int64_by_id_2(int64 id, string column, int64 value) throws DatabaseError {
Sqlite.Statement stmt;
prepare_update_by_id(id, column, out stmt);
int res = stmt.bind_int64(1, value);
assert(res == Sqlite.OK);
res = stmt.step();
if (res != Sqlite.DONE)
throw_error("DatabaseTable.update_int64_by_id_2 %s.%s".printf(table_name, column), res);
}
protected void update_double_by_id_2(int64 id, string column, double value) throws DatabaseError {
Sqlite.Statement stmt;
prepare_update_by_id(id, column, out stmt);
int res = stmt.bind_double(1, value);
assert(res == Sqlite.OK);
res = stmt.step();
if (res != Sqlite.DONE)
throw_error("DatabaseTable.update_double_by_id_2 %s.%s".printf(table_name, column), res);
}
protected void delete_by_id(int64 id) throws DatabaseError {
Sqlite.Statement stmt;
int res = db.prepare_v2("DELETE FROM %s WHERE id=?".printf(table_name), -1, out stmt);
assert(res == Sqlite.OK);
res = stmt.bind_int64(1, id);
assert(res == Sqlite.OK);
res = stmt.step();
if (res != Sqlite.DONE)
throw_error("%s.remove".printf(table_name), res);
}
public static bool has_column(string table_name, string column_name) {
Sqlite.Statement stmt;
int res = db.prepare_v2("PRAGMA table_info(%s)".printf(table_name), -1, out stmt);
assert(res == Sqlite.OK);
for (;;) {
res = stmt.step();
if (res == Sqlite.DONE) {
break;
} else if (res != Sqlite.ROW) {
fatal("has_column %s".printf(table_name), res);
break;
} else {
string column = stmt.column_text(1);
if (column != null && column == column_name)
return true;
}
}
return false;
}
public static bool has_table(string table_name) {
Sqlite.Statement stmt;
int res = db.prepare_v2("PRAGMA table_info(%s)".printf(table_name), -1, out stmt);
assert(res == Sqlite.OK);
res = stmt.step();
return (res != Sqlite.DONE);
}
public static bool add_column(string table_name, string column_name, string column_constraints) {
Sqlite.Statement stmt;
int res = db.prepare_v2("ALTER TABLE %s ADD COLUMN %s %s".printf(table_name, column_name,
column_constraints), -1, out stmt);
assert(res == Sqlite.OK);
res = stmt.step();
if (res != Sqlite.DONE) {
critical("Unable to add column %s %s %s: (%d) %s", table_name, column_name, column_constraints,
res, db.errmsg());
return false;
}
return true;
}
// This method will only add the column if a table exists (relying on the table object
// to build a new one when first referenced) and only if the column does not exist. In essence,
// it's a cleaner way to run has_table(), has_column(), and add_column().
public static bool ensure_column(string table_name, string column_name, string column_constraints,
string upgrade_msg) {
if (!has_table(table_name) || has_column(table_name, column_name))
return true;
message("%s", upgrade_msg);
return add_column(table_name, column_name, column_constraints);
}
public int get_row_count() {
Sqlite.Statement stmt;
int res = db.prepare_v2("SELECT COUNT(id) AS RowCount FROM %s".printf(table_name), -1, out stmt);
assert(res == Sqlite.OK);
res = stmt.step();
if (res != Sqlite.ROW) {
critical("Unable to retrieve row count on %s: (%d) %s", table_name, res, db.errmsg());
return 0;
}
return stmt.column_int(0);
}
// This is not thread-safe.
public static void begin_transaction() {
if (in_transaction++ != 0)
return;
int res = db.exec("BEGIN TRANSACTION");
assert(res == Sqlite.OK);
}
// This is not thread-safe.
public static void commit_transaction() throws DatabaseError {
assert(in_transaction > 0);
if (--in_transaction != 0)
return;
int res = db.exec("COMMIT TRANSACTION");
if (res != Sqlite.DONE)
throw_error("commit_transaction", res);
}
}
|