File: database-internal.vala

package info (click to toggle)
listaller 0.5.5-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 3,812 kB
  • sloc: ansic: 2,152; sh: 1,735; perl: 1,452; xml: 874; cpp: 765; java: 157; makefile: 150; cs: 48; python: 24
file content (950 lines) | stat: -rw-r--r-- 26,285 bytes parent folder | download
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
/* database-internal.vala - The Listaller application & dependency information storage
 *
 * Copyright (C) 2010-2012 Matthias Klumpp <matthias@tenstral.net>
 *
 * Licensed under the GNU Lesser General Public License Version 3
 *
 * This library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library.  If not, see <http://www.gnu.org/licenses/>.
 */

using GLib;
using Gee;
using Sqlite;
using Listaller;
using Listaller.Utils;

namespace Listaller {

private const string DATABASE = ""
		+ "CREATE TABLE applications ("
		+ "name TEXT PRIMARY KEY, "
		+ "full_name TEXT NOT NULL, "
		+ "version TEXT NOT NULL, "
		+ "desktop_file TEXT,"
		+ "author TEXT, "
		+ "publisher TEXT, "
		+ "categories TEXT, "
		+ "description TEXT, "
		+ "homepage TEXT, "
		+ "architecture TEXT NOT NULL, "
		+ "install_time INTEGER, "
		+ "dependencies TEXT, "
		+ "replaces TEXT, "
		+ "origin TEXT NOT NULL"
		+ "); "
		+ "CREATE TABLE dependencies ("
		+ "name TEXT PRIMARY KEY, "
		+ "full_name TEXT NOT NULL, "
		+ "version TEXT NOT NULL, "
		+ "description TEXT, "
		+ "author TEXT, "
		+ "homepage TEXT, "
		+ "architecture TEXT NOT NULL, "
		+ "install_time INTEGER, "
		+ "provided_by TEXT NOT NULL, "
		+ "components TEXT NOT NULL, "
		+ "environment TEXT, "
		+ "dependencies TEXT"
		+ ");" +
		"";

private const string appcols = "name, full_name, version, desktop_file, author, publisher, categories, " +
			"description, homepage, architecture, install_time, dependencies, replaces, origin";
private const string depcols = "name, full_name, version, description, author, homepage, architecture, " +
			"install_time, provided_by, components, environment, dependencies";

private enum AppRow {
	IDNAME = 0,
	FULLNAME = 1,
	VERSION = 2,
	DESKTOPFILE = 3,
	AUTHOR = 4,
	PUBLISHER = 5,
	CATEGORIES = 6,
	DESCRIPTION = 7,
	HOMEPAGE = 8,
	ARCHITECTURE = 9,
	INST_TIME = 10,
	DEPS = 11,
	REPLACES = 12,
	ORIGIN = 13;
}

private enum DepRow {
	IDNAME = 0,
	FULLNAME = 1,
	VERSION = 2,
	DESCRIPTION = 3,
	AUTHOR = 4,
	HOMEPAGE = 5,
	ARCHITECTURE = 6,
	INST_TIME = 7,
	PROVIDED_BY = 8,
	COMPONENTS = 9,
	ENVIRONMENT = 10,
	DEPENDENCIES = 11;
}

public errordomain DatabaseError {
	ERROR,
	BACKING,
	MEMORY,
	ABORT,
	LIMITS,
	TYPESPEC,
	LOCKED
}

public enum DatabaseStatus {
	OPENED,
	LOCKED,
	UNLOCKED,
	SUCCESS,
	FAILURE,
	CLOSED;

	public string to_string() {
		switch (this) {
			case OPENED:
				return _("Software database opened");

			case LOCKED:
				return _("Database locked");

			case UNLOCKED:
				return _("Database unlocked");

			case SUCCESS:
				return _("Database action successful");

			case FAILURE:
				return _("Database action failed");

			case CLOSED:
				return _("Software database closed");

			default:
				return _("Software database message (%d)").printf((int) this);
		}
	}
}

private class InternalDB : Object {
	private Database db;

	private bool locked;
	private string regdir;
	private string dbname;
	private bool shared_db;
	private bool writeable;

	private Sqlite.Statement insert_app;
	private Sqlite.Statement insert_dep;

	public signal void message (MessageItem message);

	public InternalDB (bool sumode, bool _testmode = false) {
		// Create internal dummy configuration to fetch required data
		var tmpConf = new Listaller.Settings (sumode);
		tmpConf.testmode = _testmode;

		// Path with additional data (e.g. the file-list or icons) which is not stored in the SQLite DB
		regdir = Path.build_filename (tmpConf.appregister_dir (), "info", null);
		// The database filename
		dbname = tmpConf.database_file ();
		// Whether we fetch data from the "shared" or "private" application database
		shared_db = sumode;
		writeable = false;
	}

	~InternalDB () {
		// Delete the lock
		remove_db_lock ();
	}

	public bool database_locked () {
		// If no DB is found, it can't be locked, right?
		if (!FileUtils.test (dbname, FileTest.IS_REGULAR)) {
			locked = false;
			return locked;
		}

		Database tmpDB;
		int rc = Database.open_v2 (dbname, out db);
		if (rc == Sqlite.BUSY) {
			locked = true;
		} else {
			locked = false;
		}
		return locked;
	}

	public bool database_writeable () {
		return (!database_locked ()) && (writeable);
	}

	private void emit_message (string msg) {
		// Construct info message
		MessageItem item = new MessageItem(MessageEnum.INFO);
		item.details = msg;
		message (item);
		debug (msg);
	}

	public string get_database_name () {
		return dbname;
	}

	private bool open_db () throws DatabaseError {
		bool create_db = false;
		int rc;

		if (!FileUtils.test (dbname, FileTest.IS_REGULAR)) {
			emit_message ("Software database does not exist - will be created.");
			create_db = true;
		}

		rc = Database.open_v2 (dbname, out db);
		if (rc == Sqlite.BUSY) {
			locked = true;
			throw new DatabaseError.LOCKED (_("Tried to access locked database! This shouldn't happen."));
		}
		if (rc != Sqlite.OK) {
			string msg = "Can't open database! (Message: %d, %s)".printf (rc, db.errmsg ());
			stderr.printf (msg);
			throw new DatabaseError.ERROR (msg);
		}

		create_dir_parents (regdir);

		// Ensure the database is okay and all tables are created
		if ((create_db) && (!create_database ())) {
			throw new DatabaseError.ERROR (_("Could not create software database!"));
		}

		// Prepare statements

		// InsertApp statement
		try {
			db_assert (db.prepare_v2 ("INSERT INTO applications (" + appcols + ") "
				+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
					-1, out insert_app), "prepare app insert statement");
		} catch (Error e) {
			throw new DatabaseError.ERROR (e.message);
		}

		// InsertDep statement
		try {
			db_assert (db.prepare_v2 ("INSERT INTO dependencies (" + depcols + ") "
				+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
					-1, out insert_dep), "prepare dependency insert statement");
		} catch (Error e) {
			throw new DatabaseError.ERROR (e.message);
		}

		return true;
	}

	public bool open_rw () throws DatabaseError {
		bool ret;

		// If database is locked, we should not try to write on it
		if (database_locked ()) {
			// We set locked to false, because this DB is NOT locked (because it can't be opened)
			locked = false;
			return false;
		}

		ret = open_db ();
		return_if_fail (ret == true);

		// Lock the database
		try {
			db_assert (db.exec ("PRAGMA locking_mode = RESERVED"));
		} catch (Error e) {
			throw e;
		}


		// DB is now locked
		locked = true;
		// ... and writeable
		writeable = true;

		return true;
	}

	public bool open_r () throws DatabaseError {
		bool ret;
		try {
			ret = open_db ();
		} catch (DatabaseError e) {
			throw e;
		}

		return ret;
	}

	protected void remove_db_lock () throws DatabaseError {
		if (db == null)
			return;

		if (locked) {
			// Set db locking back to normal
			try {
				db_assert (db.exec ("PRAGMA locking_mode = NORMAL"));
			} catch (Error e) {
				throw e;
			}
			locked = false;
		}
	}

	/*
	 * This method will throw an error on an SQLite return code unless it's OK, DONE, or ROW, which
	 * are considered normal results.
	 */
	protected void db_assert (int result, string action_name = "") throws DatabaseError {
		if (action_name == "")
			action_name = "generic action";
		string msg = _("Database action '%s' failed: %s").printf (action_name, db.errmsg ());

		switch (result) {
			case Sqlite.OK:
			case Sqlite.DONE:
			case Sqlite.ROW:
				return;

			case Sqlite.PERM:
			case Sqlite.BUSY:
				throw new DatabaseError.LOCKED (_("Tried to access locked database! This shouldn't happen. Message: %s").printf (msg));
			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 has_table (string table_name) throws DatabaseError {
		Sqlite.Statement stmt;
		int res = db.prepare_v2 ("PRAGMA table_info(%s)".printf(table_name), -1, out stmt);

		try {
			db_assert (res, "prepare db");
		} catch (Error e) {
			throw new DatabaseError.ERROR (e.message);
		}

		res = stmt.step ();

		return (res != Sqlite.DONE);
	}

	protected bool create_database () throws DatabaseError {
		Sqlite.Statement stmt;

		int res = db.exec (DATABASE);
		try {
			db_assert (res);
		} catch (Error e) {
			critical (_("Unable to create database tables: %s").printf (db.errmsg ()));
			return false;
		}
		try {
			db_assert (db.exec ("PRAGMA synchronous = OFF"));
			db_assert (db.exec ("PRAGMA temp_store = MEMORY"));
			db_assert (db.exec ("PRAGMA journal_mode = MEMORY"));
			db_assert (db.exec ("PRAGMA count_changes = OFF"));
		} catch (Error e) {
			warning (e.message);
			return false;
		}

		/* create database config */
		res = db.exec ("CREATE TABLE config (" +
				"data TEXT primary key," +
				"value INTEGER);");
		try {
			db_assert (res);
		} catch (Error e) {
			critical (_("Unable to create database config table: %s").printf (db.errmsg ()));
			return false;
		}

		res = db.exec ("INSERT INTO config (data, value) VALUES ('dbversion', 0);");
		try {
			db_assert (res);
		} catch (Error e) {
			critical (_("Can't create dbversion: %s").printf (db.errmsg ()));
			return false;
		}

		// db_assert (db.exec ("PRAGMA user_version = %d".printf (SUPPORTED_VERSION)));

		return true;
	}

	/* Application stuff */

	public bool add_application (AppItem item) throws DatabaseError {
		if (!database_writeable ()) {
			throw new DatabaseError.ERROR (_("Tried to write on readonly database! (This should never happen)"));
		}

		// Set install timestamp
		DateTime dt = new DateTime.now_local ();
		item.install_time = dt.to_unix ();

		// Assign values
		try {
			db_assert (insert_app.bind_text (AppRow.IDNAME +1, item.idname), "assign value");

			db_assert (insert_app.bind_text (AppRow.VERSION +1, item.version), "assign value");

			db_assert (insert_app.bind_text (AppRow.FULLNAME +1, item.full_name), "assign value");

			db_assert (insert_app.bind_text (AppRow.DESKTOPFILE +1, item.desktop_file), "assign value");

			db_assert (insert_app.bind_text (AppRow.AUTHOR +1, item.author), "assign value");

			db_assert (insert_app.bind_text (AppRow.PUBLISHER +1, item.publisher), "assign value");

			db_assert (insert_app.bind_text (AppRow.CATEGORIES +1, item.categories), "assign value");

			db_assert (insert_app.bind_text (AppRow.DESCRIPTION +1, "%s\n\n%s".printf (item.summary, item.description)), "assign value");

			db_assert (insert_app.bind_text (AppRow.HOMEPAGE +1, item.website), "assign value");

			//TODO: Handle arch field
			db_assert (insert_app.bind_text (AppRow.ARCHITECTURE +1, "current"), "assign value");

			db_assert (insert_app.bind_int64 (AppRow.INST_TIME +1, item.install_time), "assign value");

			db_assert (insert_app.bind_text (AppRow.ORIGIN +1, item.origin.to_string ()), "assign value");

			db_assert (insert_app.bind_text (AppRow.DEPS +1, item.dependencies), "assign value");

			db_assert (insert_app.bind_text (AppRow.REPLACES +1, item.replaces), "assign value");

			db_assert (insert_app.step (), "execute app insert");

			db_assert (insert_app.reset (), "reset statement");
		} catch (Error e) {
			throw new DatabaseError.ERROR (e.message);
		}

		return true;
	}

	public bool add_application_filelist (AppItem aid, Collection<IPK.FileEntry> flist) {
		if (!database_writeable ()) {
			throw new DatabaseError.ERROR (_("Tried to write on readonly database! (This should not happen)"));
		}
		string metadir = Path.build_filename (regdir, aid.idname, null);
		create_dir_parents (metadir);

		try {
			var file = File.new_for_path (Path.build_filename (metadir, "files.list", null));
			{
				var file_stream = file.create (FileCreateFlags.NONE);

				if (!file.query_exists ())
					return false;

				var data_stream = new DataOutputStream (file_stream);
				data_stream.put_string ("# File list for " + aid.full_name + "\n\n");
				// Now write file list to file
				foreach (IPK.FileEntry fe in flist) {
					if (fe.is_installed ()) {
						string fname = fe.fname_installed;
						if (!shared_db)
							fname = fold_user_dir (fname);
						data_stream.put_string (fname + "\n");
					}
				}
			}
		} catch (Error e) {
			throw new DatabaseError.ERROR (_("Unable to write application file list! Message: %s").printf (e.message));
		}
		return true;
	}

	public ArrayList<string>? get_application_filelist (AppItem app) throws DatabaseError {
		string metadir = Path.build_filename (regdir, app.idname, null);

		var file = File.new_for_path (Path.build_filename (metadir, "files.list", null));
		if (!file.query_exists ()) {
			return null;
		}

		ArrayList<string> flist = new ArrayList<string> ();
		try {
			var dis = new DataInputStream (file.read ());
			string line;
			// Read lines until end of file (null) is reached
			while ((line = dis.read_line (null)) != null) {
				if ((!line.has_prefix ("#")) && (line.strip () != "")) {
					string fname = line;
					if (!shared_db)
						fname = expand_user_dir (fname);
					flist.add (fname);
				}
			}
		} catch (Error e) {
			throw new DatabaseError.ERROR (_("Unable to fetch application file list! Message: %s").printf (e.message));
		}
		return flist;
	}

	public int get_applications_count () throws DatabaseError {
		Sqlite.Statement stmt;
		int res = db.prepare_v2 ("SELECT Count(*) FROM applications", -1, out stmt);

		try {
			db_assert (res, "get applications count");
			db_assert (stmt.step ());
		} catch (Error e) {
			throw new DatabaseError.ERROR (e.message);
		}

		int count = stmt.column_int (0);
		return count;
	}

	private AppItem? retrieve_app_item (Sqlite.Statement stmt) {
		AppItem item = new AppItem.blank ();

		item.idname = stmt.column_text (AppRow.IDNAME);
		item.full_name = stmt.column_text (AppRow.FULLNAME);
		item.version = stmt.column_text (AppRow.VERSION);
		item.desktop_file = stmt.column_text (AppRow.DESKTOPFILE);
		item.author = stmt.column_text (AppRow.AUTHOR);
		item.publisher = stmt.column_text (AppRow.PUBLISHER);
		item.categories = stmt.column_text (AppRow.CATEGORIES);
		item.website = stmt.column_text (AppRow.HOMEPAGE);

		string s = stmt.column_text (AppRow.DESCRIPTION);
		string[] desc = s.split ("\n\n", 2);
		if (desc[0] != null) {
			item.summary = desc[0];
			if (desc[1] != null)
				item.description = desc[1];
		} else {
			item.summary = s;
		}

		item.install_time = stmt.column_int (AppRow.INST_TIME);
		item.set_origin_from_string (stmt.column_text (AppRow.ORIGIN));
		item.dependencies = stmt.column_text (AppRow.DEPS);
		item.replaces = stmt.column_text (AppRow.REPLACES);
		item.shared = shared_db;

		return item;
	}

	public AppItem? get_application_by_idname (string appIdName) throws DatabaseError {
		Sqlite.Statement stmt;
		try {
			db_assert (db.prepare_v2 ("SELECT * FROM applications WHERE name=?", -1, out stmt),
				   "prepare find app by idname statement");

			db_assert (stmt.bind_text (1, appIdName), "bind value");

			int res = stmt.step ();
			db_assert (res, "execute");
			if (res != Sqlite.ROW)
				return null;
		} catch (Error e) {
			throw new DatabaseError.ERROR (e.message);
		}

		AppItem? item = retrieve_app_item (stmt);

		// Fast sanity checks
		if (item != null)
			item.fast_check ();

		return item;
	}

	public ArrayList<AppItem>? get_applications_by_fullname (string appFullName) throws DatabaseError {
		Sqlite.Statement stmt;
		int res = db.prepare_v2 ("SELECT * FROM applications WHERE full_name=?", -1, out stmt);

		try {
			db_assert (res, "get application (by full_name)");
			db_assert (stmt.bind_text (1, appFullName), "bind value");

			res = stmt.step ();
			db_assert (res, "execute");
			if (res != Sqlite.ROW)
				return null;
		} catch (Error e) {
			throw new DatabaseError.ERROR (e.message);
		}

		ArrayList<AppItem>? itemList = null;
		do {
			switch (res) {
				case Sqlite.DONE:
					break;
				case Sqlite.ROW:
					// Check if we have the container ready
					if (itemList == null)
						itemList = new ArrayList<AppItem> ();

					// Fetch a new AppItem
					AppItem? tmpApp = retrieve_app_item (stmt);
					// Fast sanity checks
					if (tmpApp != null)
						tmpApp.fast_check ();
					else
						throw new DatabaseError.ERROR ("Unable to retrieve an application from database! DB might be in an inconstistent state!");
					itemList.add (tmpApp);
					break;
				default:
					db_assert (res, "execute");
					break;
			}
			res = stmt.step ();
		} while (res == Sqlite.ROW);

		return itemList;
	}

	public ArrayList<AppItem>? get_applications_all () throws DatabaseError {
		Sqlite.Statement stmt;
		int res = db.prepare_v2 ("SELECT * FROM applications", -1, out stmt);

		try {
			db_assert (res, "get all applications");

			res = stmt.step ();
			db_assert (res, "execute");
			if (res != Sqlite.ROW)
				return null;
		} catch (Error e) {
			throw new DatabaseError.ERROR (e.message);
		}

		ArrayList<AppItem>? itemList = null;
		do {
			switch (res) {
				case Sqlite.DONE:
					break;
				case Sqlite.ROW:
					// Check if we have the container ready
					if (itemList == null)
						itemList = new ArrayList<AppItem> ();

					// Fetch a new AppItem
					AppItem? tmpApp = retrieve_app_item (stmt);
					// Fast sanity checks
					if (tmpApp != null)
						tmpApp.fast_check ();
					else
						throw new DatabaseError.ERROR ("Unable to retrieve an application from database! DB might be in an inconstistent state!");

					itemList.add (tmpApp);
					break;
				default:
					db_assert (res, "execute");
					break;
			}
			res = stmt.step ();
		} while (res == Sqlite.ROW);

		return itemList;
	}

	public AppItem? get_application_by_name_version (string appName, string appVersion) throws DatabaseError {
		Sqlite.Statement stmt;
		int res = db.prepare_v2 ("SELECT * FROM applications WHERE name=? AND version=?", -1, out stmt);
		try {
			db_assert (res, "get application (by full_name and version)");
			db_assert (stmt.bind_text (1, appName), "bind value");
			db_assert (stmt.bind_text (2, appVersion), "bind value");

			res = stmt.step ();
			db_assert (res, "execute");
			if (res != Sqlite.ROW)
				return null;
		} catch (Error e) {
			throw new DatabaseError.ERROR (e.message);
		}

		AppItem? item = retrieve_app_item (stmt);

		// Fast sanity checks
		if (item != null)
			item.fast_check ();

		return item;
	}

	public bool remove_application (AppItem app) throws DatabaseError {
		bool ret = true;
		string metadir = Path.build_filename (regdir, app.idname, null);
		Sqlite.Statement stmt;
		int res = db.prepare_v2 ("DELETE FROM applications WHERE name=?", -1, out stmt);

		try {
			db_assert (res, "delete application (prepare statement)");
			db_assert (stmt.bind_text (1, app.idname), "bind text");
			db_assert (stmt.step(), "execute action");
		} catch (Error e) {
			throw new DatabaseError.ERROR (e.message);
		}

		ret = delete_dir_recursive (metadir);
		if (!ret)
			warning ("Could not remove metadata directory for application-id %s!".printf (app.idname));
		return ret;
	}

	private bool string_in_app_item (AppItem item, string s) {
		string str = s.down ();
		if (item.idname.down ().index_of (str) > -1)
			return true;
		if (item.full_name.down ().index_of (str) > -1)
			return true;
		if (item.summary.down ().index_of (str) > -1)
			return true;
		if (item.description.down ().index_of (str) > -1)
			return true;
		return false;
	}

	public ArrayList<AppItem> find_applications ([CCode (array_null_terminated = true, array_length = false)] string[] values) {
		ArrayList<AppItem> resList = new ArrayList<AppItem> ();
		if (values[0] == null)
			return resList;

		HashSet<AppItem> tmpList = new HashSet<AppItem> ();

		Sqlite.Statement stmt;
		try {
			db_assert (db.prepare_v2 ("SELECT * FROM applications", -1, out stmt),
				   "prepare list all applications statement");

			int rc = 0;
			do {
				rc = stmt.step();
				switch (rc) {
					case Sqlite.DONE:
						break;
					case Sqlite.ROW:
						// Fetch a new AppItem
						AppItem? tmpApp = retrieve_app_item (stmt);
						// Fast sanity checks
						if (tmpApp != null)
							tmpApp.fast_check ();
						else
							throw new DatabaseError.ERROR ("Unable to retrieve an application from database! DB might be in an inconstistent state!");

						// Now check if app matches our criteroa
						for (int j = 0; values[j] != null; j++) {
							if (string_in_app_item (tmpApp, values[j])) {
								tmpList.add (tmpApp);
								break;
							}
						}

						break;
					default:
						db_assert (rc, "execute");
						break;
				}
			} while (rc == Sqlite.ROW);

		} catch (Error e) {
			throw new DatabaseError.ERROR (e.message);
		}

		resList.add_all (tmpList.read_only_view);

		return resList;
	}

	public bool set_application_dependencies (string appName, ArrayList<IPK.Dependency> deps) throws DatabaseError {
		Sqlite.Statement stmt;
		int res = db.prepare_v2 ("UPDATE applications SET dependencies=? WHERE name=?", -1, out stmt);

		string depstr = "";
		foreach (IPK.Dependency d in deps)
			depstr += d.idname + "\n";

		try {
			db_assert (res, "update application deps (by name)");
			db_assert (stmt.bind_text (1, depstr), "bind text value");
			db_assert (stmt.bind_text (2, appName), "bind text value");
			db_assert (stmt.step ());
		} catch (Error e) {
			throw new DatabaseError.ERROR (e.message);
		}

		return true;
	}

	/* Dependency stuff */

	public bool add_dependency (IPK.Dependency dep) throws DatabaseError {
		if (!database_writeable ()) {
			throw new DatabaseError.ERROR (_("Tried to write on readonly database! (This should never happen)"));
		}

		// Set install timestamp
		DateTime dt = new DateTime.now_local ();
		dep.install_time = dt.to_unix ();

		try {
			// Assign values
			db_assert (insert_dep.bind_text (DepRow.IDNAME +1, dep.idname), "bind value");

			db_assert (insert_dep.bind_text (DepRow.FULLNAME +1, dep.full_name), "bind value");

			db_assert (insert_dep.bind_text (DepRow.VERSION +1, dep.version), "bind value");

			db_assert (insert_dep.bind_text (DepRow.DESCRIPTION +1, "%s\n\n%s".printf (dep.summary, dep.description)), "bind value");

			db_assert (insert_dep.bind_text (DepRow.HOMEPAGE +1, dep.homepage), "bind value");

			db_assert (insert_dep.bind_text (DepRow.AUTHOR +1, dep.author), "bind value");

			db_assert (insert_dep.bind_int64 (DepRow.INST_TIME +1, dep.install_time), "bind value");

			db_assert (insert_dep.bind_text (DepRow.ARCHITECTURE +1, dep.architecture), "bind value");

			db_assert (insert_dep.bind_text (DepRow.PROVIDED_BY +1, dep.get_installdata_as_string ()), "bind value");

			db_assert (insert_dep.bind_text (DepRow.COMPONENTS +1, dep.get_componentdata_as_string ()), "bind value");

			db_assert (insert_dep.bind_text (DepRow.ENVIRONMENT +1, dep.environment), "bind value");

			db_assert (insert_dep.bind_text (DepRow.DEPENDENCIES +1, ""), "bind value");

			db_assert (insert_dep.step (), "add dependency");

			db_assert (insert_dep.reset (), "reset insert_dep statement");
		} catch (Error e) {
			throw new DatabaseError.ERROR (e.message);
		}

		return true;
	}

	private IPK.Dependency? retrieve_dependency (Sqlite.Statement stmt) {
		IPK.Dependency dep = new IPK.Dependency.blank ();

		dep.idname = stmt.column_text (DepRow.IDNAME);
		dep.full_name = stmt.column_text (DepRow.FULLNAME);
		dep.version = stmt.column_text (DepRow.VERSION);

		string s = stmt.column_text (DepRow.DESCRIPTION);
		string[] desc = s.split ("\n\n", 2);
		if (desc[0] != null) {
			dep.summary = desc[0];
			if (desc[1] != null)
				dep.description = desc[1];
		} else {
			dep.summary = s;
		}

		dep.homepage = stmt.column_text (DepRow.HOMEPAGE);
		dep.author = stmt.column_text (DepRow.AUTHOR);
		dep.install_time = stmt.column_int (DepRow.INST_TIME);
		dep.architecture = stmt.column_text (DepRow.ARCHITECTURE);
		dep.set_componentdata_from_string (stmt.column_text (DepRow.COMPONENTS));
		dep.set_installdata_from_string (stmt.column_text (DepRow.PROVIDED_BY));
		dep.environment = stmt.column_text (DepRow.ENVIRONMENT);

		// Because dep is in the database already, it has to be satisfied
		dep.satisfied = true;

		return dep;
	}

	public IPK.Dependency? get_dependency_by_id (string depIdName) {
		Sqlite.Statement stmt;
		int res = db.prepare_v2 ("SELECT * FROM dependencies WHERE name=?", -1, out stmt);

		try {
			db_assert (res, "get dependency (by id)");
			db_assert (stmt.bind_text (1, depIdName), "bind text");

			res = stmt.step ();
			db_assert (res, "execute");
			if (res != Sqlite.ROW)
				return null;
		} catch (Error e) {
			throw new DatabaseError.ERROR (e.message);
		}

		IPK.Dependency? dep = retrieve_dependency (stmt);
		return dep;
	}

	public bool set_dependency_environment (string depIdName, string env) throws DatabaseError {
		Sqlite.Statement stmt;
		int res = db.prepare_v2 ("UPDATE dependencies SET environment=? WHERE name=?", -1, out stmt);

		try {
			db_assert (res, "get dependency (by id)");
			db_assert (stmt.bind_text (1, env), "bind text");
			db_assert (stmt.bind_text (2, depIdName), "bind text");

			res = stmt.step ();
			db_assert (res, "execute");
			if (res != Sqlite.DONE)
				return false;
		} catch (Error e) {
			throw new DatabaseError.ERROR (e.message);
		}

		return true;
	}

}

} // End of namespace