This repository has been archived by the owner on Jan 3, 2024. It is now read-only.
forked from fnc12/sqlite_orm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection_holder.h
75 lines (57 loc) · 1.87 KB
/
connection_holder.h
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
#pragma once
#include <sqlite3.h>
#include <atomic>
#include <string> // std::string
#include "error_code.h"
namespace sqlite_orm {
namespace internal {
struct connection_holder {
connection_holder(std::string filename_) : filename(std::move(filename_)) {}
void retain() {
if(1 == ++this->_retain_count) {
auto rc = sqlite3_open(this->filename.c_str(), &this->db);
if(rc != SQLITE_OK) {
throw_translated_sqlite_error(db);
}
}
}
void release() {
if(0 == --this->_retain_count) {
auto rc = sqlite3_close(this->db);
if(rc != SQLITE_OK) {
throw_translated_sqlite_error(db);
}
}
}
sqlite3* get() const {
return this->db;
}
int retain_count() const {
return this->_retain_count;
}
const std::string filename;
protected:
sqlite3* db = nullptr;
std::atomic_int _retain_count{};
};
struct connection_ref {
connection_ref(connection_holder& holder_) : holder(holder_) {
this->holder.retain();
}
connection_ref(const connection_ref& other) : holder(other.holder) {
this->holder.retain();
}
connection_ref(connection_ref&& other) : holder(other.holder) {
this->holder.retain();
}
~connection_ref() {
this->holder.release();
}
sqlite3* get() const {
return this->holder.get();
}
protected:
connection_holder& holder;
};
}
}