8 [[noreturn
]] void throwSQLiteError(sqlite3
* db
, const format
& f
)
10 int err
= sqlite3_errcode(db
);
11 if (err
== SQLITE_BUSY
|| err
== SQLITE_PROTOCOL
) {
12 if (err
== SQLITE_PROTOCOL
)
13 printMsg(lvlError
, "warning: SQLite database is busy (SQLITE_PROTOCOL)");
15 static bool warned
= false;
17 printMsg(lvlError
, "warning: SQLite database is busy");
21 /* Sleep for a while since retrying the transaction right away
22 is likely to fail again. */
26 t
.tv_nsec
= (random() % 100) * 1000 * 1000; /* <= 0.1s */
31 throw SQLiteBusy(format("%1%: %2%") % f
.str() % sqlite3_errmsg(db
));
34 throw SQLiteError(format("%1%: %2%") % f
.str() % sqlite3_errmsg(db
));
40 if (db
&& sqlite3_close(db
) != SQLITE_OK
)
41 throwSQLiteError(db
, "closing database");
47 void SQLiteStmt::create(sqlite3
* db
, const string
& s
)
51 if (sqlite3_prepare_v2(db
, s
.c_str(), -1, &stmt
, 0) != SQLITE_OK
)
52 throwSQLiteError(db
, "creating statement");
56 SQLiteStmt::~SQLiteStmt()
59 if (stmt
&& sqlite3_finalize(stmt
) != SQLITE_OK
)
60 throwSQLiteError(db
, "finalizing statement");
66 SQLiteStmt::Use::Use(SQLiteStmt
& stmt
)
70 /* Note: sqlite3_reset() returns the error code for the most
71 recent call to sqlite3_step(). So ignore it. */
75 SQLiteStmt::Use::~Use()
80 SQLiteStmt::Use
& SQLiteStmt::Use::operator () (const std::string
& value
, bool notNull
)
83 if (sqlite3_bind_text(stmt
, curArg
++, value
.c_str(), -1, SQLITE_TRANSIENT
) != SQLITE_OK
)
84 throwSQLiteError(stmt
.db
, "binding argument");
90 SQLiteStmt::Use
& SQLiteStmt::Use::operator () (int64_t value
, bool notNull
)
93 if (sqlite3_bind_int64(stmt
, curArg
++, value
) != SQLITE_OK
)
94 throwSQLiteError(stmt
.db
, "binding argument");
100 SQLiteStmt::Use
& SQLiteStmt::Use::bind()
102 if (sqlite3_bind_null(stmt
, curArg
++) != SQLITE_OK
)
103 throwSQLiteError(stmt
.db
, "binding argument");
107 int SQLiteStmt::Use::step()
109 return sqlite3_step(stmt
);
112 void SQLiteStmt::Use::exec()
115 assert(r
!= SQLITE_ROW
);
116 if (r
!= SQLITE_DONE
)
117 throwSQLiteError(stmt
.db
, "executing SQLite statement");
120 bool SQLiteStmt::Use::next()
123 if (r
!= SQLITE_DONE
&& r
!= SQLITE_ROW
)
124 throwSQLiteError(stmt
.db
, "executing SQLite query");
125 return r
== SQLITE_ROW
;
128 std::string
SQLiteStmt::Use::getStr(int col
)
130 auto s
= (const char *) sqlite3_column_text(stmt
, col
);
135 int64_t SQLiteStmt::Use::getInt(int col
)
137 // FIXME: detect nulls?
138 return sqlite3_column_int64(stmt
, col
);
141 SQLiteTxn::SQLiteTxn(sqlite3
* db
)
144 if (sqlite3_exec(db
, "begin;", 0, 0, 0) != SQLITE_OK
)
145 throwSQLiteError(db
, "starting transaction");
149 void SQLiteTxn::commit()
151 if (sqlite3_exec(db
, "commit;", 0, 0, 0) != SQLITE_OK
)
152 throwSQLiteError(db
, "committing transaction");
156 SQLiteTxn::~SQLiteTxn()
159 if (active
&& sqlite3_exec(db
, "rollback;", 0, 0, 0) != SQLITE_OK
)
160 throwSQLiteError(db
, "aborting transaction");