database.hpp (2259B)
1 /* ReaPack: Package manager for REAPER 2 * Copyright (C) 2015-2025 Christian Fillion 3 * 4 * This program is free software: you can redistribute it and/or modify 5 * it under the terms of the GNU Lesser General Public License as published by 6 * the Free Software Foundation, either version 3 of the License, or 7 * (at your option) any later version. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU Lesser General Public License for more details. 13 * 14 * You should have received a copy of the GNU Lesser General Public License 15 * along with this program. If not, see <http://www.gnu.org/licenses/>. 16 */ 17 18 #ifndef REAPACK_DATABASE_HPP 19 #define REAPACK_DATABASE_HPP 20 21 #include <cstdint> 22 #include <functional> 23 #include <string> 24 #include <vector> 25 26 class reapack_error; 27 28 struct sqlite3; 29 struct sqlite3_stmt; 30 31 class Statement; 32 33 class Database { 34 public: 35 struct Version { 36 int16_t major; 37 int16_t minor; 38 39 operator bool() const { return major || minor; } 40 41 bool operator<(const Version &o) const 42 { 43 return major == o.major ? minor < o.minor : major < o.major; 44 } 45 }; 46 47 Database(const std::string &filename = {}); 48 ~Database(); 49 50 Statement *prepare(const char *sql); 51 void exec(const char *sql); 52 int64_t lastInsertId() const; 53 Version version() const; 54 void setVersion(const Version &); 55 int errorCode() const; 56 57 void begin(); 58 void commit(); 59 void savepoint(); 60 void restore(); 61 void release(); 62 63 private: 64 friend Statement; 65 66 reapack_error lastError() const; 67 68 sqlite3 *m_db; 69 std::vector<Statement *> m_statements; 70 size_t m_savePoint; 71 }; 72 73 class Statement { 74 public: 75 typedef std::function<bool (void)> ExecCallback; 76 77 Statement(const char *sql, const Database *db); 78 ~Statement(); 79 80 void bind(int index, const std::string &text); 81 void bind(int index, int64_t integer); 82 void exec(); 83 void exec(const ExecCallback &); 84 85 int64_t intColumn(int index) const; 86 bool boolColumn(int index) const { return intColumn(index) != 0; } 87 std::string stringColumn(int index) const; 88 89 private: 90 friend Database; 91 92 const Database *m_db; 93 sqlite3_stmt *m_stmt; 94 }; 95 96 #endif