comparison Core/SQLite/StatementReference.cpp @ 0:3959d33612cc

initial commit
author Sebastien Jodogne <s.jodogne@gmail.com>
date Thu, 19 Jul 2012 14:32:22 +0200
parents
children db4d996ea264
comparison
equal deleted inserted replaced
-1:000000000000 0:3959d33612cc
1 /**
2 * Palantir - A Lightweight, RESTful DICOM Store
3 * Copyright (C) 2012 Medical Physics Department, CHU of Liege,
4 * Belgium
5 *
6 * This program is free software: you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License as
8 * published by the Free Software Foundation, either version 3 of the
9 * License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 **/
19
20
21 #include "StatementReference.h"
22
23 #include "../PalantirException.h"
24
25 #include <cassert>
26 #include "sqlite3.h"
27
28 namespace Palantir
29 {
30 namespace SQLite
31 {
32 bool StatementReference::IsRoot() const
33 {
34 return root_ == NULL;
35 }
36
37 StatementReference::StatementReference()
38 {
39 root_ = NULL;
40 refCount_ = 0;
41 statement_ = NULL;
42 assert(IsRoot());
43 }
44
45 StatementReference::StatementReference(sqlite3* database,
46 const char* sql)
47 {
48 if (database == NULL || sql == NULL)
49 {
50 throw PalantirException(ErrorCode_ParameterOutOfRange);
51 }
52
53 root_ = NULL;
54 refCount_ = 0;
55
56 int error = sqlite3_prepare_v2(database, sql, -1, &statement_, NULL);
57 if (error != SQLITE_OK)
58 {
59 throw PalantirException("SQLite: " + std::string(sqlite3_errmsg(database)));
60 }
61
62 assert(IsRoot());
63 }
64
65 StatementReference::StatementReference(StatementReference& other)
66 {
67 refCount_ = 0;
68
69 if (other.IsRoot())
70 {
71 root_ = &other;
72 }
73 else
74 {
75 root_ = other.root_;
76 }
77
78 root_->refCount_++;
79 statement_ = root_->statement_;
80
81 assert(!IsRoot());
82 }
83
84 StatementReference::~StatementReference()
85 {
86 if (IsRoot())
87 {
88 if (refCount_ != 0)
89 {
90 // There remain references to this object
91 throw PalantirException(ErrorCode_InternalError);
92 }
93 else if (statement_ != NULL)
94 {
95 sqlite3_finalize(statement_);
96 }
97 }
98 else
99 {
100 if (root_->refCount_ == 0)
101 {
102 throw PalantirException(ErrorCode_InternalError);
103 }
104 else
105 {
106 root_->refCount_--;
107 }
108 }
109 }
110
111 uint32_t StatementReference::GetReferenceCount() const
112 {
113 return refCount_;
114 }
115 }
116 }