SQLiteDynamicStorage.h (2507B)
1 // Copyright (c) Microsoft Corporation. 2 // Licensed under the MIT License. 3 #pragma once 4 #include <winget/SQLiteStorageBase.h> 5 #include <concurrencysal.h> 6 #include <filesystem> 7 #include <memory> 8 9 namespace AppInstaller::SQLite 10 { 11 // Type the allows for the schema version of the underlying storage to be changed dynamically. 12 struct SQLiteDynamicStorage : public SQLiteStorageBase 13 { 14 // Creates a new database with the given schema version. 15 SQLiteDynamicStorage(const std::string& target, const Version& version); 16 SQLiteDynamicStorage(const std::filesystem::path& target, const Version& version); 17 18 // Opens an existing database with the given disposition. 19 SQLiteDynamicStorage(const std::string& filePath, SQLiteStorageBase::OpenDisposition disposition, Utility::ManagedFile&& file = {}); 20 SQLiteDynamicStorage(const std::filesystem::path& filePath, SQLiteStorageBase::OpenDisposition disposition, Utility::ManagedFile&& file = {}); 21 22 // Implicit conversion to a connection object for convenience. 23 operator Connection& (); 24 operator const Connection& () const; 25 Connection& GetConnection(); 26 const Connection& GetConnection() const; 27 28 using SQLiteStorageBase::SetLastWriteTime; 29 30 // Must be kept alive to ensure consistent schema view and exclusive use of the owned connection. 31 struct TransactionLock 32 { 33 _Acquires_lock_(mutex) 34 TransactionLock(std::mutex& mutex); 35 36 _Acquires_lock_(mutex) 37 TransactionLock(std::mutex& mutex, Connection& connection, std::string_view name, bool immediateWrite); 38 39 // Abandons the transaction and any changes; releases the connection lock. 40 void Rollback(bool throwOnError = true); 41 42 // Commits the transaction and releases the connection lock. 43 void Commit(); 44 45 private: 46 std::lock_guard<std::mutex> m_lock; 47 Transaction m_transaction; 48 }; 49 50 // Acquires the connection lock and begins a transaction on the database. 51 // If the returned result is empty, the schema version has changed and the caller must handle this. 52 std::unique_ptr<TransactionLock> TryBeginTransaction(std::string_view name, bool immediateWrite); 53 54 // Locks the connection for use during the schema upgrade. 55 std::unique_ptr<TransactionLock> LockConnection(); 56 }; 57 }