blob: 01488c6adafa309be7b9fe5443d07e50afe0cfea (
plain)
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
|
// file : bpkg/database.cxx -*- C++ -*-
// copyright : Copyright (c) 2014-2015 Code Synthesis Ltd
// license : MIT; see accompanying LICENSE file
#include <bpkg/database>
#include <memory> // unique_ptr
#include <utility> // move()
#include <odb/schema-catalog.hxx>
#include <odb/sqlite/exceptions.hxx>
#include <bpkg/types>
#include <bpkg/diagnostics>
using namespace std;
namespace bpkg
{
using namespace odb::sqlite;
using odb::schema_catalog;
database
open (const dir_path& d, bool create)
{
path f (d / path ("bpkg.sqlite3"));
try
{
// We don't need the thread pool.
//
unique_ptr<connection_factory> cf (new single_connection_factory);
database db (f.string (),
SQLITE_OPEN_READWRITE | (create ? SQLITE_OPEN_CREATE : 0),
true, // Enable FKs.
"", // Default VFS.
move (cf));
// Lock the database for as long as the connection is active. First
// we set locking_mode to EXCLUSIVE which instructs SQLite not to
// release any locks until the connection is closed. Then we force
// SQLite to acquire the write lock by starting exclusive transaction.
// See the locking_mode pragma documentation for details. This will
// also fail if the database is inaccessible (e.g., file does not
// exist, already used by another process, etc).
//
{
db.connection ()->execute ("PRAGMA locking_mode = EXCLUSIVE");
transaction t (db.begin_exclusive ());
t.commit ();
}
if (create)
{
// Create the new schema.
//
if (db.schema_version () != 0)
fail << f << ": already has database schema";
transaction t (db.begin ());
schema_catalog::create_schema (db);
t.commit ();
}
else
{
// Migrate the database if necessary.
//
transaction t (db.begin ());
schema_catalog::migrate (db);
t.commit ();
}
return db;
}
catch (const database_exception& e)
{
error << f << ": " << e.message ();
throw failed ();
}
}
}
|