### Initialize and Manage Database Connections
Source: https://context7.com/utelle/wxsqlite3/llms.txt
Demonstrates library initialization, opening encrypted or unencrypted databases, and executing basic DDL and DML statements.
```cpp
#include "wx/wxsqlite3.h"
// Initialize SQLite library (call once at application start)
wxSQLite3Database::InitializeSQLite();
// Open a database connection
wxSQLite3Database db;
try {
// Open unencrypted database (creates if not exists)
db.Open(wxS("mydata.db"));
// Or open with encryption password
db.Open(wxS("secure.db"), wxS("my_secret_password"));
// Check if database is open
if (db.IsOpen()) {
cout << "Database opened successfully" << endl;
cout << "Encrypted: " << (db.IsEncrypted() ? "Yes" : "No") << endl;
}
// Execute DDL statements
db.ExecuteUpdate(wxS("CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY, name TEXT, email TEXT)"));
// Insert data
int rowsAffected = db.ExecuteUpdate(wxS("INSERT INTO users(name, email) VALUES('John Doe', 'john@example.com')"));
cout << rowsAffected << " row(s) inserted" << endl;
// Get the last inserted row ID
wxLongLong lastId = db.GetLastRowId();
cout << "Last inserted ID: " << lastId.ToLong() << endl;
// Close connection
db.Close();
} catch (wxSQLite3Exception& e) {
cerr << "Error " << e.GetErrorCode() << ": " << e.GetMessage().mb_str() << endl;
}
// Shutdown SQLite library (call once at application end)
wxSQLite3Database::ShutdownSQLite();
```
--------------------------------
### Configure wxSQLite3 Build Directory
Source: https://github.com/utelle/wxsqlite3/blob/main/readme.md
Create a build directory and run the configure script with appropriate flags, matching those used for configuring wxWidgets.
```bash
mkdir build-gtk
cd build-gtk
../configure [here you should use the same flags you used to configure wxWidgets]
make
```
--------------------------------
### Perform Online Backup and Restore
Source: https://context7.com/utelle/wxsqlite3/llms.txt
Shows how to implement a progress callback for backup/restore operations and perform these tasks on live databases.
```cpp
// Custom progress callback
class MyBackupProgress : public wxSQLite3BackupProgress {
public:
virtual bool Progress(int totalPages, int remainingPages) {
double percent = ((totalPages - remainingPages) / (double)totalPages) * 100.0;
cout << "Backup progress: " << fixed << setprecision(1) << percent << "%" << endl;
return true; // Return false to cancel backup
}
};
wxSQLite3Database db;
db.Open(wxS("production.db"), wxS("db_password"));
try {
// Set pages copied per iteration (default: 10)
db.SetBackupRestorePageCount(100);
// Simple backup without progress
db.Backup(wxS("backup.db"), wxS("backup_password"));
// Backup with progress callback
MyBackupProgress progress;
db.Backup(&progress, wxS("backup_with_progress.db"), wxS("backup_key"));
// Backup with specific cipher for backup file
wxSQLite3CipherAes256 cipher;
cipher.InitializeFromGlobalDefault();
db.Backup(&progress, wxS("aes_backup.db"), cipher, wxS("aes_key"));
// Backup specific database (when multiple attached)
db.Backup(wxS("main_backup.db"), wxS("key"), wxS("main"));
cout << "Backup completed successfully" << endl;
} catch (wxSQLite3Exception& e) {
cerr << "Backup failed: " << e.GetMessage().mb_str() << endl;
}
// Restore from backup
wxSQLite3Database restoreDb;
restoreDb.Open(wxS(":memory:")); // Restore to in-memory database
try {
MyBackupProgress progress;
restoreDb.Restore(&progress, wxS("backup.db"), wxS("backup_password"));
cout << "Restore completed successfully" << endl;
// Verify restored data
int count = restoreDb.ExecuteScalar(wxS("SELECT COUNT(*) FROM users"));
cout << "Restored " << count << " users" << endl;
} catch (wxSQLite3Exception& e) {
cerr << "Restore failed: " << e.GetMessage().mb_str() << endl;
}
```
--------------------------------
### Configure wx_setup.props for Visual Studio
Source: https://github.com/utelle/wxsqlite3/blob/main/readme.md
Modify these parameters in `wx_setup.props` to use library paths without toolkit versions, typically when compiling wxWidgets yourself.
```xml
vc
```
--------------------------------
### Define Minimal Sample Source Files
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Lists the source files for the minimal sample application.
```cmake
set(MINIMAL_SOURCES
"../samples/minimal.cpp"
)
```
--------------------------------
### Recreate Configure Script with Autoreconf
Source: https://github.com/utelle/wxsqlite3/blob/main/readme.md
Run `autoreconf` to regenerate the configure script when building wxSQLite3 on an autoconf-based system like Linux.
```bash
autoreconf
```
--------------------------------
### Implementing Custom Hooks and Callbacks in wxSQLite3
Source: https://context7.com/utelle/wxsqlite3/llms.txt
Shows how to create custom classes inheriting from wxSQLite3Hook and wxSQLite3Authorizer to monitor and control database operations. Remember to set and remove hooks appropriately.
```cpp
// Custom hook class for monitoring database changes
class DatabaseMonitor : public wxSQLite3Hook {
public:
virtual bool CommitCallback() {
cout << "COMMIT detected" << endl;
return false; // Return true to force rollback
}
virtual void RollbackCallback() {
cout << "ROLLBACK detected" << endl;
}
virtual void UpdateCallback(wxUpdateType type, const wxString& database,
const wxString& table, wxLongLong rowid) {
const char* opName;
switch (type) {
case SQLITE_INSERT: opName = "INSERT"; break;
case SQLITE_UPDATE: opName = "UPDATE"; break;
case SQLITE_DELETE: opName = "DELETE"; break;
default: opName = "UNKNOWN"; break;
}
cout << opName << " on " << table.mb_str() << " (row " << rowid.ToLong() << ")" << endl;
}
virtual int WriteAheadLogCallback(const wxString& database, int numPages) {
cout << "WAL: " << numPages << " pages ready for checkpoint" << endl;
return 0; // Return 0 to continue, non-zero to stop
}
};
// Custom authorizer for access control
class AccessControl : public wxSQLite3Authorizer {
public:
virtual wxAuthorizationResult Authorize(wxAuthorizationCode type,
const wxString& arg1, const wxString& arg2,
const wxString& arg3, const wxString& arg4, const wxString& arg5) {
// Block DELETE operations on sensitive tables
if (type == SQLITE_DELETE && arg1 == wxS("audit_log")) {
cout << "DENIED: Cannot delete from audit_log" << endl;
return SQLITE_DENY;
}
// Allow everything else
return SQLITE_OK;
}
};
// Usage
wxSQLite3Database db;
db.Open(wxS("monitored.db"));
DatabaseMonitor monitor;
AccessControl accessControl;
// Set hooks
db.SetCommitHook(&monitor);
db.SetRollbackHook(&monitor);
db.SetUpdateHook(&monitor);
db.SetWriteAheadLogHook(&monitor);
db.SetAuthorizer(accessControl);
// Operations will trigger callbacks
db.ExecuteUpdate(wxS("INSERT INTO users(name) VALUES('Test')")); // Triggers UpdateCallback
// Remove hooks when done
db.SetUpdateHook(NULL);
db.RemoveAuthorizer();
```
--------------------------------
### Define Treeview Sample Source Files
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Lists the source files for the treeview sample application.
```cmake
set(TREEVIEW_SOURCES
"../samples/treeview/foldertree.cpp"
"../samples/treeview/projectlist.cpp"
"../samples/treeview/treeviewapp.cpp"
"../samples/treeview/treeviewsample.cpp"
)
```
--------------------------------
### Manage Database Encryption with wxSQLite3
Source: https://context7.com/utelle/wxsqlite3/llms.txt
Demonstrates checking encryption support, opening encrypted databases, rekeying, and configuring specific cipher schemes like ChaCha20, SQLCipher, and AES-256.
```cpp
wxSQLite3Database db;
// Check encryption support
if (wxSQLite3Database::HasEncryptionSupport()) {
cout << "Encryption is supported" << endl;
cout << "Default cipher: " << wxSQLite3Cipher::GetCipherName(
wxSQLite3Cipher::GetGlobalCipherDefault()).mb_str() << endl;
}
// Open/Create encrypted database with default cipher (ChaCha20)
try {
db.Open(wxS("encrypted.db"), wxS("my_secret_key"));
cout << "Encrypted database opened" << endl;
// Get key salt (important for recovery)
wxString keySalt = db.GetKeySalt();
cout << "Key salt: " << keySalt.mb_str() << endl;
// Change encryption key (rekey)
db.ReKey(wxS("new_secret_key"));
// Remove encryption (decrypt database)
db.ReKey(wxEmptyString);
db.Close();
} catch (wxSQLite3Exception& e) {
cerr << "Encryption error: " << e.GetMessage().mb_str() << endl;
}
// Open database with specific cipher scheme
wxSQLite3CipherChaCha20 chacha;
chacha.InitializeFromGlobalDefault();
chacha.SetKdfIter(256000); // Set KDF iterations
db.Open(wxS("chacha.db"), chacha, wxS("password"));
// Using SQLCipher compatibility mode (version 4)
wxSQLite3CipherSQLCipher sqlcipher;
sqlcipher.InitializeVersionDefault(4); // Use SQLCipher v4 defaults
db.Open(wxS("sqlcipher_v4.db"), sqlcipher, wxS("testkey"));
// Using AES-256 encryption
wxSQLite3CipherAes256 aes256;
aes256.InitializeFromGlobalDefault();
aes256.SetLegacy(false);
aes256.SetKdfIter(64000);
db.Open(wxS("aes256.db"), aes256, wxS("strong_password"));
// Attach encrypted database to existing connection
wxSQLite3CipherSQLCipher sqlCipher3;
sqlCipher3.InitializeVersionDefault(3);
db.AttachDatabase(wxS("other_encrypted.db"), wxS("attached_db"), sqlCipher3, wxS("attach_key"));
// Detach when done
db.DetachDatabase(wxS("attached_db"));
```
--------------------------------
### Define Library Source Files
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Lists the source files required for building the wxSQLite3 library.
```cmake
set(LIBRARY_SOURCES
"../include/wx/wxsqlite3_version.h"
"../include/wx/wxsqlite3def.h"
"../include/wx/wxsqlite3opt.h"
"../src/sqlite3mc_amalgamation.h"
"../src/sqlite3mc_amalgamation.c"
"../src/wxsqlite3.cpp"
)
```
--------------------------------
### Print Build Configuration
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Iterates through a list of build options and compiler-specific settings, printing their current values to the build output. This helps in verifying the configuration.
```cmake
foreach(V ${COMPILER_SPECIFIC_OPTIONS}
STATIC_RUNTIME
SQLITE_DEBUG
PEDANTIC_COMPILER_FLAGS
THREAD_SAVE_STATIC_INIT
RELEASE_DEBUG_SYMBOLS
SQLITE_CODEC_TYPE
WXSQLITE3_BUILD_SHARED
)
message("${V}: ${${V}}")
endforeach()
```
--------------------------------
### Set VS Startup Project
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Sets the 'treeview' executable as the default startup project within Visual Studio for the current source directory.
```cmake
set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT treeview)
```
--------------------------------
### Define Build Options
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Configures build options such as static runtime linking, shared library building, and static wxWidgets linking.
```cmake
option(STATIC_RUNTIME "link with c++ runtime statically" "ON")
option(WXSQLITE3_BUILD_SHARED "Build wxSQLite3 as shared library" ON)
option(BUILD_SHARED_LIBS "Link with shared wxWidgets library" ON)
```
--------------------------------
### Find and Configure wxWidgets
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Finds the wxWidgets library and configures the build to use it. It adds wxWidgets definitions and flags to the compiler and links the necessary libraries to the targets.
```cmake
find_package (wxWidgets REQUIRED core base adv)
if(wxWidgets_FOUND)
set(WXDEFS "wxWidgets definitions:")
foreach(F ${wxWidgets_DEFINITIONS})
add_definitions("-D${F}")
set(WXDEFS "${WXDEFS} ${F}")
endforeach()
set(WXFLAGS "wxWidgets compiler flags:")
foreach(F ${wxWidgets_CXX_FLAGS})
set(CMAKE_CXX_FLAGS "${COMMON_CXX_FLAGS} ${F}")
set(WXFLAGS "${WXFLAGS} ${F}")
endforeach()
include_directories(${wxWidgets_INCLUDE_DIRS})
target_link_libraries (treeview ${wxWidgets_LIBRARIES})
target_link_libraries (minimal ${wxWidgets_LIBRARIES})
if (WXSQLITE3_BUILD_SHARED)
target_link_libraries (wxsqlite3 ${wxWidgets_LIBRARIES})
endif(WXSQLITE3_BUILD_SHARED)
message(${WXDEFS})
message(${WXFLAGS})
message("wxWidgets include directories: ${wxWidgets_INCLUDE_DIRS}")
message("wxWidgets libraries: ${wxWidgets_LIBRARIES}")
endif(wxWidgets_FOUND)
```
--------------------------------
### Execute Queries and Process Result Sets
Source: https://context7.com/utelle/wxsqlite3/llms.txt
Shows how to iterate through query results using wxSQLite3ResultSet and retrieve scalar values from the database.
```cpp
wxSQLite3Database db;
db.Open(wxS("mydata.db"));
try {
// Execute SELECT query
wxSQLite3ResultSet rs = db.ExecuteQuery(wxS("SELECT id, name, email, salary FROM employees WHERE dept = 'Engineering'"));
// Get column metadata
cout << "Column count: " << rs.GetColumnCount() << endl;
for (int i = 0; i < rs.GetColumnCount(); i++) {
cout << "Column " << i << ": " << rs.GetColumnName(i).mb_str()
<< " (" << rs.GetDeclaredColumnType(i).mb_str() << ")" << endl;
}
// Iterate through results
while (rs.NextRow()) {
// Access by column index
int id = rs.GetInt(0);
wxString name = rs.GetString(1);
// Access by column name
wxString email = rs.GetString(wxS("email"));
double salary = rs.GetDouble(wxS("salary"), 0.0); // 0.0 is default for NULL
// Check for NULL values
if (!rs.IsNull(wxS("email"))) {
cout << "ID: " << id << ", Name: " << name.mb_str()
<< ", Email: " << email.mb_str() << ", Salary: " << salary << endl;
}
}
// Always finalize when done
rs.Finalize();
// Scalar query for single value results (e.g., COUNT, SUM)
int totalEmployees = db.ExecuteScalar(wxS("SELECT COUNT(*) FROM employees"));
cout << "Total employees: " << totalEmployees << endl;
} catch (wxSQLite3Exception& e) {
cerr << "Query error: " << e.GetMessage().mb_str() << endl;
}
```
--------------------------------
### Create Encrypted Database with SQLite Shell
Source: https://github.com/utelle/wxsqlite3/blob/main/readme.md
Use the PRAGMA KEY command to set the encryption key when creating or opening an encrypted database with the SQLite shell.
```sql
PRAGMA KEY="encryption key";
```
--------------------------------
### Registering Custom Scalar and Aggregate Functions in C++
Source: https://context7.com/utelle/wxsqlite3/llms.txt
Implement custom logic by inheriting from wxSQLite3ScalarFunction or wxSQLite3AggregateFunction and registering them with the database instance.
```cpp
// Custom scalar function: uppercase with prefix
class UppercaseFunction : public wxSQLite3ScalarFunction {
public:
virtual void Execute(wxSQLite3FunctionContext& ctx) {
if (ctx.GetArgCount() < 1 || ctx.IsNull(0)) {
ctx.SetResultNull();
return;
}
wxString input = ctx.GetString(0);
wxString prefix = (ctx.GetArgCount() > 1) ? ctx.GetString(1) : wxS("");
ctx.SetResult(prefix + input.Upper());
}
};
// Custom aggregate function: concatenate all values
class ConcatAggFunction : public wxSQLite3AggregateFunction {
public:
virtual void Aggregate(wxSQLite3FunctionContext& ctx) {
// Get temporary storage for intermediate result
wxString** acc = (wxString**)ctx.GetAggregateStruct(sizeof(wxString**));
if (*acc == NULL) {
*acc = new wxString();
}
// Append each value
for (int i = 0; i < ctx.GetArgCount(); i++) {
if (!ctx.IsNull(i)) {
if (!(*acc)->IsEmpty()) (*acc)->Append(wxS(", "));
(*acc)->Append(ctx.GetString(i));
}
}
}
virtual void Finalize(wxSQLite3FunctionContext& ctx) {
wxString** acc = (wxString**)ctx.GetAggregateStruct(sizeof(wxString**));
if (*acc != NULL) {
ctx.SetResult(**acc);
delete *acc;
*acc = NULL;
} else {
ctx.SetResultNull();
}
}
};
// Register and use functions
wxSQLite3Database db;
db.Open(wxS("mydata.db"));
UppercaseFunction upperFunc;
ConcatAggFunction concatFunc;
// Register scalar function (name, arg count, function object, flags)
db.CreateFunction(wxS("my_upper"), -1, upperFunc, WXSQLITE_DETERMINISTIC);
// Register aggregate function
db.CreateFunction(wxS("my_concat"), 1, concatFunc);
// Use in queries
wxSQLite3ResultSet rs = db.ExecuteQuery(
wxS("SELECT my_upper(name, 'Mr. ') FROM employees")
);
while (rs.NextRow()) {
cout << rs.GetString(0).mb_str() << endl; // "MR. JOHN DOE"
}
// Aggregate function usage
rs = db.ExecuteQuery(
wxS("SELECT department, my_concat(name) FROM employees GROUP BY department")
);
while (rs.NextRow()) {
cout << rs.GetString(0).mb_str() << ": " << rs.GetString(1).mb_str() << endl;
}
// Built-in REGEXP support (if wxUSE_REGEX is enabled)
#if wxUSE_REGEX
wxSQLite3RegExpOperator regexpOp;
db.CreateFunction(wxS("regexp"), 2, regexpOp);
rs = db.ExecuteQuery(wxS("SELECT name FROM employees WHERE name REGEXP '^J.*'"));
#endif
```
--------------------------------
### Include Directories
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Adds '../include/' and '../src/' to the compiler's include path. These directories likely contain header files for wxsqlite3 and its dependencies.
```cmake
include_directories(
"../include/"
"../src/"
)
```
--------------------------------
### Define Build Options
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Defines various build options for wxSQLite3 using CMake's 'option' command. These control features like SQLite debugging, pedantic compiler flags, thread-safe initialization, debug symbols, and codec types.
```cmake
option(SQLITE_DEBUG "enable SQLite debug" "OFF")
option(PEDANTIC_COMPILER_FLAGS "Enable additional checking for ill-formed code" "ON")
option(THREAD_SAVE_STATIC_INIT "Enable thread safe initialization of static variables" "OFF")
option(RELEASE_DEBUG_SYMBOLS "Generate debugging symbols for optimized build" "OFF")
set(SQLITE_CODEC_TYPE "DEFAULT" CACHE STRING "DB Codec(AES128, AES256, CHACHA20, SQLCIPHER, RC4, DEFAULT)")
```
--------------------------------
### Configure 32-bit Build Options
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Enables 32-bit compilation and linking when the USE_32 flag is set. This is typically used for cross-compilation or specific platform requirements.
```cmake
if(USE_32)
add_compile_options (-m32)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -m32")
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -m32")
endif(USE_32)
```
--------------------------------
### Define Library Type and Macros
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Sets the library type (SHARED or STATIC) and defines macros for making and using the library based on the WXSQLITE3_BUILD_SHARED flag.
```cmake
if (WXSQLITE3_BUILD_SHARED)
set(WXSQLITE3_LIBRARY_TYPE SHARED)
set(WXSQLITE3_MAKING_DEF "WXMAKINGDLL_WXSQLITE3")
set(WXSQLITE3_USING_DEF "WXUSINGDLL_WXSQLITE3")
else()
set(WXSQLITE3_LIBRARY_TYPE STATIC)
set(WXSQLITE3_MAKING_DEF "WXMAKINGLIB_WXSQLITE3")
set(WXSQLITE3_USING_DEF "WXUSINGLIB_WXSQLITE3")
endif(WXSQLITE3_BUILD_SHARED)
```
--------------------------------
### Execute Prepared Statements with Parameter Binding
Source: https://context7.com/utelle/wxsqlite3/llms.txt
Use wxSQLite3Statement to execute parameterized queries, which helps prevent SQL injection and improves performance for repeated operations. Remember to call Finalize() on statements when they are no longer needed.
```cpp
wxSQLite3Database db;
db.Open(wxS("mydata.db"));
try {
// Prepare statement with placeholders
wxSQLite3Statement stmt = db.PrepareStatement(
wxS("INSERT INTO employees(name, department, salary, hire_date, photo) VALUES(?, ?, ?, ?, ?)")
);
// Bind parameters by index (1-based)
stmt.Bind(1, wxS("Jane Smith")); // String
stmt.Bind(2, wxS("Marketing")); // String
stmt.Bind(3, 75000.50); // Double
stmt.BindDateTime(4, wxDateTime::Now()); // DateTime
// Bind binary data (BLOB)
wxMemoryBuffer photoData;
// ... load photo data into buffer ...
stmt.Bind(5, photoData);
// Execute and check affected rows
int rows = stmt.ExecuteUpdate();
cout << rows << " row(s) inserted" << endl;
// Reset for reuse with different values
stmt.Reset();
stmt.ClearBindings();
// Bind new values and execute again
stmt.Bind(1, wxS("Bob Wilson"));
stmt.Bind(2, wxS("Sales"));
stmt.Bind(3, 65000.00);
stmt.BindDateTime(4, wxDateTime::Now());
stmt.BindNull(5); // NULL for photo
stmt.ExecuteUpdate();
// Prepared SELECT statement
wxSQLite3Statement selectStmt = db.PrepareStatement(
wxS("SELECT * FROM employees WHERE salary > ? AND department = ?")
);
selectStmt.Bind(1, 50000.0);
selectStmt.Bind(2, wxS("Engineering"));
wxSQLite3ResultSet rs = selectStmt.ExecuteQuery();
while (rs.NextRow()) {
cout << rs.GetString(wxS("name")).mb_str() << endl;
}
// Finalize when done
stmt.Finalize();
selectStmt.Finalize();
} catch (wxSQLite3Exception& e) {
cerr << "Statement error: " << e.GetMessage().mb_str() << endl;
}
```
--------------------------------
### Link wxSQLite3 Libraries
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Establishes dependencies and links the 'treeview' and 'minimal' executables with the wxsqlite3 library. It also handles conditional linking for shared library builds.
```cmake
add_dependencies(treeview wxsqlite3)
add_dependencies(minimal wxsqlite3)
target_link_libraries(treeview wxsqlite3)
target_link_libraries(minimal wxsqlite3)
```
--------------------------------
### Performing Incremental BLOB I/O in C++
Source: https://context7.com/utelle/wxsqlite3/llms.txt
Use wxSQLite3Blob to read or write large binary data in chunks without loading the entire object into memory.
```cpp
wxSQLite3Database db;
db.Open(wxS("documents.db"));
try {
// Create table with BLOB column
db.ExecuteUpdate(wxS("CREATE TABLE IF NOT EXISTS files(id INTEGER PRIMARY KEY, name TEXT, data BLOB)"));
// Insert a row with placeholder BLOB (zeroblob)
db.ExecuteUpdate(wxS("INSERT INTO files(name, data) VALUES('largefile.bin', zeroblob(1048576))")); // 1MB
wxLongLong rowId = db.GetLastRowId();
// Get writable BLOB handle
wxSQLite3Blob blob = db.GetWritableBlob(rowId, wxS("data"), wxS("files"));
cout << "BLOB size: " << blob.GetSize() << " bytes" << endl;
// Write data at specific offset
wxMemoryBuffer chunk;
const char* data = "Header data here";
chunk.AppendData(data, strlen(data));
blob.Write(chunk, 0); // Write at offset 0
// Write more data at different offset
chunk.Clear();
const char* footer = "Footer data";
chunk.AppendData(footer, strlen(footer));
blob.Write(chunk, 1048576 - 100); // Write near end
blob.Finalize();
// Read BLOB incrementally
blob = db.GetReadOnlyBlob(rowId, wxS("data"), wxS("files"));
// Read specific portion
wxMemoryBuffer readBuffer;
blob.Read(readBuffer, 16, 0); // Read 16 bytes from offset 0
cout << "Read: " << (char*)readBuffer.GetData() << endl;
// Rebind to different row (efficient for iterating)
// blob.Rebind(anotherRowId);
blob.Finalize();
} catch (wxSQLite3Exception& e) {
cerr << "BLOB error: " << e.GetMessage().mb_str() << endl;
}
```
--------------------------------
### Configure Compiler Specific Options
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Sets compiler-specific options based on whether MSVC or GNU GCC is being used. Includes options like exception handling and thread-safe static initialization.
```cmake
if(MSVC)
set(COMPILER_SPECIFIC_OPTIONS CPP_EXCEPTIONS_ONLY
THREAD_SAVE_STATIC_INIT
)
elseif(CMAKE_COMPILER_IS_GNUCC)
set(COMPILER_SPECIFIC_OPTIONS CPP_EXCEPTIONS_ONLY)
endif(MSVC)
```
--------------------------------
### Attach Encrypted Database with SQLite Shell
Source: https://github.com/utelle/wxsqlite3/blob/main/readme.md
Use the ATTACH DATABASE command with the KEY option to attach an encrypted database to an existing connection.
```sql
ATTACH DATABASE x AS y KEY z;
```
--------------------------------
### Using Named Collections for IN Clauses in wxSQLite3
Source: https://context7.com/utelle/wxsqlite3/llms.txt
Demonstrates creating and binding integer and string collections for use in SQL IN clauses. Ensure the database supports named collections before using this feature.
```cpp
wxSQLite3Database db;
db.Open(wxS("inventory.db"));
if (db.HasNamedCollectionSupport()) {
// Create integer collection
wxSQLite3IntegerCollection productIds = db.CreateIntegerCollection(wxS("product_ids"));
// Bind array of integers
int ids[] = {101, 205, 307, 412, 589};
productIds.Bind(5, ids);
// Use in query (collection name used directly)
wxSQLite3ResultSet rs = db.ExecuteQuery(
wxS("SELECT name, price FROM products WHERE id IN product_ids")
);
while (rs.NextRow()) {
cout << rs.GetString(0).mb_str() << ": $" << rs.GetDouble(1) << endl;
}
// Rebind with wxArrayInt
wxArrayInt moreIds;
moreIds.Add(100);
moreIds.Add(200);
moreIds.Add(300);
productIds.Bind(moreIds);
// Create string collection
wxSQLite3StringCollection categories = db.CreateStringCollection(wxS("cats"));
wxArrayString catList;
catList.Add(wxS("Electronics"));
catList.Add(wxS("Clothing"));
catList.Add(wxS("Books"));
categories.Bind(catList);
// Use string collection in query
rs = db.ExecuteQuery(
wxS("SELECT COUNT(*) as cnt, category FROM products WHERE category IN cats GROUP BY category")
);
while (rs.NextRow()) {
cout << rs.GetString(wxS("category")).mb_str() << ": " << rs.GetInt(wxS("cnt")) << " items" << endl;
}
}
```
--------------------------------
### Conditional 32-bit Binary Option
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Enables an option to create 32-bit binaries if the system is 64-bit and uses GCC.
```cmake
if((CMAKE_SIZEOF_VOID_P EQUAL 8) AND CMAKE_COMPILER_IS_GNUCC)
option(USE_32 "create 32 bit binaries" "OFF")
endif()
```
--------------------------------
### SQLite Debug and Compiler Flags Options
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Sets options for enabling SQLite debugging and pedantic compiler flags.
```cmake
option(SQLITE_DEBUG "enable SQLite debug" "OFF")
option(PEDANTIC_COMPILER_FLAGS "Enable additional checking for ill-formed code" "ON")
```
--------------------------------
### Define wxSQLite3 Executables
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Defines the 'treeview' and 'minimal' executables for the wxSQLite3 project. It specifies source files and sets compiler flags, including the WXSQLITE3_USING_DEF macro.
```cmake
add_executable(
treeview
WIN32
${TREEVIEW_SOURCES}
)
set_target_properties(treeview PROPERTIES COMPILE_FLAGS -D${WXSQLITE3_USING_DEF})
add_executable(
minimal
${MINIMAL_SOURCES}
)
set_target_properties(minimal PROPERTIES COMPILE_FLAGS -D${WXSQLITE3_USING_DEF})
```
--------------------------------
### Set Minimum CMake Version and Project Name
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Specifies the minimum required CMake version and sets the project name.
```cmake
cmake_minimum_required(VERSION 3.6)
project(wxSQLite3)
```
--------------------------------
### MSVC Specific Compiler Options
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Configures MSVC-specific options like exception handling and thread-safe static initialization.
```cmake
if(MSVC)
option(CPP_EXCEPTIONS_ONLY "Catch only C++ exceptions(/EHsc) instead of catching all exceptions(/EHa)" "ON")
option(THREAD_SAVE_STATIC_INIT "Enable thread safe initialization of static variables" "OFF")
endif(MSVC)
```
--------------------------------
### Add wxsqlite3 Library Target
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Defines the 'wxsqlite3' library target, specifying its type (shared or static) and the source files to be compiled.
```cmake
add_library(
wxsqlite3
${WXSQLITE3_LIBRARY_TYPE}
${LIBRARY_SOURCES}
)
```
--------------------------------
### Configure Static Runtime Linking
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Sets linker flags to statically link the C++ runtime libraries when STATIC_RUNTIME is enabled. Includes specific flags for MinGW.
```cmake
if(STATIC_RUNTIME)
if(MINGW)
set(STATIC_LINKER_FLAGS "-static -Wl,--allow-multiple-definition")
else()
set(STATIC_LINKER_FLAGS "-static-libgcc -static-libstdc++")
endif(MINGW)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${STATIC_LINKER_FLAGS}")
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${STATIC_LINKER_FLAGS}")
endif(STATIC_RUNTIME)
```
--------------------------------
### Add Windows Resource Files Conditionally
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Conditionally adds Windows resource files (.rc) to the source lists if the build is for Windows.
```cmake
if(WIN32)
set(LIBRARY_SOURCES
${LIBRARY_SOURCES}
"../src/wxsqlite3_version.rc"
)
set(TREEVIEW_SOURCES
${TREEVIEW_SOURCES}
"../samples/treeview/treeview.rc"
)
set(MINIMAL_SOURCES
${MINIMAL_SOURCES}
"../samples/minimal.rc"
)
endif(WIN32)
```
--------------------------------
### Set MSVC Subsystem
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Configures the linker for the 'minimal' executable on MSVC to use the CONSOLE subsystem, ensuring it runs as a console application.
```cmake
IF(MSVC)
set_target_properties(minimal PROPERTIES LINK_FLAGS "/SUBSYSTEM:CONSOLE")
ENDIF(MSVC)
```
--------------------------------
### Implement and Register Custom Collations in wxSQLite3
Source: https://context7.com/utelle/wxsqlite3/llms.txt
Defines custom collation classes for case-insensitive and reverse string sorting, then registers them with a database instance for use in SQL queries.
```cpp
// Case-insensitive collation
class CaseInsensitiveCollation : public wxSQLite3Collation {
public:
virtual int Compare(const wxString& text1, const wxString& text2) {
return text1.CmpNoCase(text2);
}
};
// Reverse string collation (sort by reversed strings)
class ReverseCollation : public wxSQLite3Collation {
public:
virtual int Compare(const wxString& text1, const wxString& text2) {
wxString rev1, rev2;
for (size_t i = text1.Length(); i > 0; i--) rev1 += text1[i-1];
for (size_t i = text2.Length(); i > 0; i--) rev2 += text2[i-1];
return rev1.Cmp(rev2);
}
};
wxSQLite3Database db;
db.Open(wxS("collation_test.db"));
CaseInsensitiveCollation nocase;
ReverseCollation reverse;
// Register collations
db.SetCollation(wxS("NOCASE_CUSTOM"), &nocase);
db.SetCollation(wxS("REVERSE"), &reverse);
// Use in table definition
db.ExecuteUpdate(wxS("CREATE TABLE names(name TEXT COLLATE NOCASE_CUSTOM)"));
// Insert data
db.ExecuteUpdate(wxS("INSERT INTO names VALUES('alice'), ('Bob'), ('CHARLIE'), ('david')"));
// Query with custom collation (case-insensitive sort)
wxSQLite3ResultSet rs = db.ExecuteQuery(wxS("SELECT name FROM names ORDER BY name"));
cout << "Case-insensitive order:" << endl;
while (rs.NextRow()) {
cout << " " << rs.GetString(0).mb_str() << endl;
}
// Use collation in ORDER BY clause
rs = db.ExecuteQuery(wxS("SELECT name FROM names ORDER BY name COLLATE REVERSE"));
cout << "Reverse string order:" << endl;
while (rs.NextRow()) {
cout << " " << rs.GetString(0).mb_str() << endl;
}
```
--------------------------------
### Manage Database Transactions
Source: https://context7.com/utelle/wxsqlite3/llms.txt
Handle database transactions using explicit Begin/Commit/Rollback calls or the RAII-based wxSQLite3Transaction class for automatic rollback on exceptions. Savepoints can be used for nested transaction control.
```cpp
wxSQLite3Database db;
db.Open(wxS("mydata.db"));
// Method 1: Explicit transaction control
try {
db.Begin(WXSQLITE_TRANSACTION_IMMEDIATE); // Begin immediate transaction
db.ExecuteUpdate(wxS("INSERT INTO accounts(name, balance) VALUES('Alice', 1000)"));
db.ExecuteUpdate(wxS("INSERT INTO accounts(name, balance) VALUES('Bob', 500)"));
db.ExecuteUpdate(wxS("UPDATE accounts SET balance = balance - 100 WHERE name = 'Alice'"));
db.ExecuteUpdate(wxS("UPDATE accounts SET balance = balance + 100 WHERE name = 'Bob'"));
db.Commit(); // Commit changes
cout << "Transaction committed successfully" << endl;
} catch (wxSQLite3Exception& e) {
db.Rollback(); // Rollback on error
cerr << "Transaction rolled back: " << e.GetMessage().mb_str() << endl;
}
// Method 2: RAII transaction (automatic rollback on exception)
try {
wxSQLite3Transaction trans(&db, WXSQLITE_TRANSACTION_EXCLUSIVE);
// Perform operations
db.ExecuteUpdate(wxS("DELETE FROM temp_data WHERE expired = 1"));
db.ExecuteUpdate(wxS("INSERT INTO audit_log(action) VALUES('cleanup')"));
// Verify transaction is active
if (trans.IsActive()) {
cout << "Transaction is active" << endl;
}
// Explicitly commit (if not called, destructor will rollback)
trans.Commit();
} catch (...) {
// Transaction automatically rolled back when trans goes out of scope
cout << "Transaction was automatically rolled back" << endl;
}
// Check autocommit state
cout << "AutoCommit: " << (db.GetAutoCommit() ? "On" : "Off") << endl;
// Using savepoints for nested transaction control
db.Begin();
db.ExecuteUpdate(wxS("INSERT INTO log(msg) VALUES('step 1')"));
db.Savepoint(wxS("sp1"));
db.ExecuteUpdate(wxS("INSERT INTO log(msg) VALUES('step 2')"));
// Rollback to savepoint (undo step 2 only)
db.Rollback(wxS("sp1"));
db.Commit(); // Only step 1 is committed
```
--------------------------------
### Set wxsqlite3 Compile Flags
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Configures compile-time flags for the wxsqlite3 library, including definitions for library type, thread safety, and various SQLite extensions.
```cmake
set_target_properties(wxsqlite3 PROPERTIES COMPILE_FLAGS "-D_LIB \ -D${WXSQLITE3_MAKING_DEF} \ -DSQLITE_THREADSAFE=1 \ -DSQLITE_MAX_ATTACHED=10 \ -DSQLITE_DQS=0 \ -DSQLITE_ENABLE_EXPLAIN_COMMENTS=1 \ -DSQLITE_SOUNDEX=1 \ -DSQLITE_ENABLE_COLUMN_METADATA=1 \ -DSQLITE_SECURE_DELETE=1 \ -DSQLITE_ENABLE_DESERIALIZE=1 \ -DSQLITE_ENABLE_FTS3=1 \ -DSQLITE_ENABLE_FTS3_PARENTHESIS=1 \ -DSQLITE_ENABLE_FTS4=1 \ -DSQLITE_ENABLE_FTS5=1 \ -DSQLITE_ENABLE_JSON1=1 \ -DSQLITE_ENABLE_RTREE=1 \ -DSQLITE_ENABLE_GEOPOLY=1 \ -DSQLITE_CORE=1 \ -DSQLITE_ENABLE_EXTFUNC=1 \ -DSQLITE_ENABLE_CSV=1 \ -DSQLITE_ENABLE_VSV=1 \ -DSQLITE_ENABLE_SHA3=1 \ -DSQLITE_ENABLE_CARRAY=1 \ -DSQLITE_ENABLE_FILEIO=1 \ -DSQLITE_ENABLE_SERIES=1 \ -DSQLITE_ENABLE_UUID=1 \ -DSQLITE_ENABLE_REGEXP=1 \
```
--------------------------------
### Set SQLite Codec Type
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Sets the type of SQLite codec to be used, with a default value.
```cmake
set(SQLITE_CODEC_TYPE "DEFAULT" CACHE STRING "DB Codec(AES128, AES256, CHACHA20, SQLCIPHER, RC4, DEFAULT)")
```
--------------------------------
### Set Compiler Flags for Release and Debug
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Configures CMAKE_CXX_FLAGS_RELEASE and CMAKE_C_FLAGS_RELEASE for optimized builds with debug symbols. Sets CMAKE_CXX_FLAGS_DEBUG and CMAKE_C_FLAGS_DEBUG for debug builds with extensive debugging macros.
```cmake
set(CMAKE_CXX_FLAGS_RELEASE "-O2 ${DBG_FLAG} -DNDEBUG")
set(CMAKE_C_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE})
set(CMAKE_CXX_FLAGS_DEBUG "-O0 -g -D_DEBUG -D__DEBUG__ -DDEBUG_LEVEL=3 -D_GLIBCXX_DEBUG -D_GLIBCXX_DEBUG_PEDANTIC")
set(CMAKE_C_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG})
```
--------------------------------
### MSVC Specific Compile Options
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Sets common MSVC compiler options for debugging, warnings, character sets, calling conventions, and more.
```cmake
if(MSVC)
add_compile_options(/Zi # pdb
/W4 # warning level 4
/J # use unsigned char
/Gd # use cdecl
/MP # multiprocessor compilation
/utf-8 # utf-8 source
/GF # eliminate duplicate strings
/wd4996 # disable 'The POSIX name for this item is deprecated ...'
)
if(PEDANTIC_COMPILER_FLAGS)
add_compile_options(# treat warnings as errors
/we4715 # not all control paths return a value
/we4828 # disallow invalid characters
# prinf-like functions: format mismatch
/we4473 # : not enough arguments passed for format string
/we4474 # : too many arguments passed for format string
/we4475 # : length modifier cannot be used with type field character in format specifier
/we4476 # : unknown type field character in format specifier
/we4477 # : format string requires an argument of type , but variadic argument has type
/we4478 # : positional and non-positional placeholders cannot be mixed in the same format string
/we4775 # nonstandard extension used in format string of function
/we4776 # % is not allowed in the format string of function
/we4777 # : format string requires an argument of type , but variadic argument has type
/we4778 # : unterminated format string
# macro arg mismatch
/we4002 # too many actual parameters for macro 'identifier'
/we4003 # not enough actual parameters for macro 'identifier'
)
endif(PEDANTIC_COMPILER_FLAGS)
if(CPP_EXCEPTIONS_ONLY)
add_compile_options(/EHsc) # exceptions: sync
else()
add_compile_options(/EHa) # exceptions: sync
endif(CPP_EXCEPTIONS_ONLY)
if((NOT THREAD_SAVE_STATIC_INIT) AND (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 19.00))
add_compile_options(/Zc:threadSafeInit-) # https://connect.microsoft.com/VisualStudio/feedback/details/1789709/visual-c-2015-runtime-broken-on-windows-server-2003-c-11-magic-statics
endif()
set(CMAKE_CXX_FLAGS ${CMAKE_C_FLAGS})
add_definitions(-D_CRT_SECURE_NO_WARNINGS)
if(STATIC_RUNTIME)
set(RELEASE_RUNTIME "/MT")
set(DEBUG_RUNTIME "/MTd")
else()
set(RELEASE_RUNTIME "/MD")
set(DEBUG_RUNTIME "/MDd")
endif(STATIC_RUNTIME)
if(RELEASE_DEBUG_SYMBOLS)
```
--------------------------------
### Release Debug Symbols Option
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Option to generate debugging symbols for optimized builds.
```cmake
option(RELEASE_DEBUG_SYMBOLS "Generate debugging symbols for optimized build" "OFF")
```
--------------------------------
### Set CMAKE_CONFIGURATION_TYPES
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Forces the CMake configuration types to Debug and Release.
```cmake
set(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING "" FORCE)
```
--------------------------------
### Set SQLite Debug Macro
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Enables SQLite's internal debugging features by defining SQLITE_ENABLE_DEBUG=1 when the SQLITE_DEBUG flag is set.
```cmake
if(SQLITE_DEBUG)
set(SQLITE_DEBUG_MACRO "-DSQLITE_ENABLE_DEBUG=1")
endif(SQLITE_DEBUG)
```
--------------------------------
### Set Linker Flags for Debug and Valgrind
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Configures linker flags for debug builds and Valgrind analysis, ensuring debug symbols are included. Sets release linker flags to include the debug flag.
```cmake
set(CMAKE_EXE_LINKER_FLAGS_DEBUG "${CMAKE_EXE_LINKER_FLAGS} -g")
set(CMAKE_SHARED_LINKER_FLAGS_DEBUG "${CMAKE_SHARED_LINKER_FLAGS} -g")
set(CMAKE_EXE_LINKER_FLAGS_VALGRIND "${CMAKE_EXE_LINKER_FLAGS} -g")
set(CMAKE_SHARED_LINKER_FLAGS_VALGRIND "${CMAKE_SHARED_LINKER_FLAGS} -g")
set(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS} ${DBG_FLAG}")
set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS} ${DBG_FLAG}")
```
--------------------------------
### Set Executable and Shared Library Linker Flags
Source: https://github.com/utelle/wxsqlite3/blob/main/build/CMakeLists.txt
Appends the rpath '$ORIGIN' to the linker flags for executables and shared libraries. This ensures that shared libraries can be found relative to the executable.
```cmake
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-rpath,'$ORIGIN'" )
endif(MSVC)
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.