### Initialize and Configure Database Instances Source: https://context7.com/tencent/wcdb/llms.txt Handles database creation, encryption setup, and file management. Use these methods to establish connections and apply security configurations. ```swift // Swift - Create database with path let database = Database(at: "~/Documents/sample.db") // Set database tag for identification database.tag = 1 // Check if database can be opened if database.canOpen { print("Database opened successfully") } // Configure encryption let password = "myPassword".data(using: .ascii)! database.setCipher(key: password, pageSize: 4096) // Custom configuration database.setConfig(named: "secure_delete", with: { handle in let pragma = StatementPragma().pragma(.secureDelete, to: true) try handle.exec(pragma) }) // Memory management database.purge() // Reclaim unused memory for this database Database.purge() // Reclaim memory for all databases // File operations let filesSize = try database.getFilesSize() try database.removeFiles() try database.moveFiles(toDirectory: "~/Backup/") ``` ```cpp // C++ - Create database with encryption WCDB::Database database("~/Documents/sample.db"); // Set cipher key for encryption database.setCipherKey("password".data(), 8); // Check database status if (database.canOpen()) { std::cout << "Database ready" << std::endl; } ``` -------------------------------- ### Perform Value Queries in WCDB Source: https://github.com/tencent/wcdb/wiki/Java|Kotlin-增删查改 Examples demonstrating how to retrieve rows, columns, and individual values from a database table. ```java //Java // 获取所有内容 List allRows = database.getAllRows(DBSample.allFields(), "sampleTable"); System.out.print(allRows.get(2)[0].getInt());// 输出 3 // 获取第二行 Value[] secondRow = database.getOneRow(DBSample.allFields(), "sampleTable", DBSample.id.order(Order.Desc), 1); System.out.print(secondRow[0]);// 输出 3 // 获取第二行 content 列的值 List contentColumn = database.getOneColumn(DBSample.content, "sampleTable"); System.out.print(contentColumn.get(2).getText());// 输出 sample2 // 直接获取第二行 content 列的字符串值,性能更好 List contentStrings = database.getOneColumnString(DBSample.content, "sampleTable"); System.out.print(contentStrings.get(2));//输出 sample2 // 获取第二列第二行的值 Value value = database.getValue(DBSample.content, "sampleTable", DBSample.id.order(Order.Asc), 1); System.out.print(value.getText()); // 获取 identifier 的最大值 Value maxId = database.getValue(DBSample.id.max(), "sampleTable"); System.out.print(maxId.getInt());// 输出 5 ``` ```kotlin //Kotlin // 获取所有内容 val allRows = database.getAllRows(DBSample.allFields(), "sampleTable") print(allRows[2][0].int) // 输出 3 // 获取第二行 val secondRow = database.getOneRow(DBSample.allFields(),"sampleTable", DBSample.id.order(Order.Desc), 1) print(secondRow[0]) // 输出 3 // 获取第三行 content 列的值 val contentColumn = database.getOneColumn(DBSample.content, "sampleTable") print(contentColumn[2].text) // 输出 sample2 // 直接获取第二行 content 列的字符串值,性能更好 val contentStrings = database.getOneColumnString(DBSample.content, "sampleTable") print(contentStrings[2]) //输出 sample2 // 获取第二列第二行的值 val value = database.getValue(DBSample.content, "sampleTable", DBSample.id.order(Order.Asc), 1) print(value.text) // 获取 identifier 的最大值 val maxId = database.getValue(DBSample.id.max(), "sampleTable") print(maxId.int) // 输出 5 ``` -------------------------------- ### Manual Type Conversion for Select Source: https://github.com/tencent/wcdb/wiki/C++-语言集成查询 Example showing the manual conversion process required if direct type compatibility is not handled. ```c++ // 以下为示例代码,并非 WCDB 真正的实现 class StatementSelect { StatementSelect& select(const ResultColumns& resultColumns); // ... } WCDB::Column identifierColumm = WCDB::Column("identifier"); WCDB::Expression identifierExpression = WCDB::Expression(identifierColumm); WCDB::ResultColumn identifierResultColumm = WCDB::ResultColumn(identifierExpression); WCDB::StatementSelect select = WCDB::StatementSelect().select(identifierResultColumm).from("sampleTable"); printf("%s", select.getDescription().data()); // 输出 "SELECT identifier FROM sampleTable" ``` -------------------------------- ### Execute Value Query Operations Source: https://github.com/tencent/wcdb/wiki/Swift-增删查改 Examples of retrieving rows, columns, and specific values from a database table. ```swift // 获取所有内容 let allRows = try database.getRows(fromTable: "sampleTable") print(allRows[row: 2, column: 0].int32Value) // 输出 3 // 获取第二行 let secondRow = try database.getRow(fromTable: "sampleTable", offset: 1) print(secondRow[0].int32Value) // 输出 2 // 获取 description 列 let descriptionColumn = try database.getColumn(on: Sample.Properties.description, fromTable: "sampleTable") print(descriptionColumn) // 输出 "sample1", "sample1", "sample1", "sample2", "sample2" // 获取不重复的 description 列的值 let distinctDescriptionColumn = try database.getDistinctColumn(on: Sample.Properties.description, fromTable: "sampleTable") print(distinctDescriptionColumn) // 输出 "sample1", "sample2" // 获取第二行 description 列的值 let value = try database.getValue(on: Sample.Properties.description, offset: 1) print(value.stringValue) // 输出 "sample1" // 获取 identifier 的最大值 let maxIdentifier = try database.getValue(on: Sample.Properties.identifier.max(), fromTable: "sampleTable") // 获取不重复的 description 的值 let distinctDescription = try database.getDistinctValue(on: Sample.Properties.description, fromTable: "sampleTable") print(distinctDescription.stringValue) // 输出 "sample1" ``` -------------------------------- ### Implement Manual ColumnCodable Source: https://github.com/tencent/wcdb/wiki/Swift-自定义字段映射类型 An example of manually implementing serialization and deserialization for a custom class. Note: This specific example contains logic errors and is provided for illustrative purposes only. ```swift // 错误示例,请勿参照 class MyClass: ColumnCodable { var variable1: String var variable2: String static var columnType: ColumnType { return .BLOB } required init?(with value: Value) { let data = value.dataValue guard data.count > 0 else { return nil } guard let dictionary = try? JSONDecoder().decode([String: String].self, from: data) else { return nil } variable1 = dictionary["variable1"] as? String ?? "" variable2 = dictionary["variable2"] as? String ?? "" } func archivedValue() -> Value { guard let data = try? JSONEncoder().encode([ "variable1": variable1, "variable2": variable2]) else { return Value(data) } return Value(nil) } } ``` -------------------------------- ### Demonstrate Unsupported Type Mapping Source: https://github.com/tencent/wcdb/wiki/Swift-自定义字段映射类型 Example of a class that fails to map to a database table because it does not conform to required protocols. ```swift class MyClass { var variable1: String = "" var variable2: String = "" } class Sample: TableCodable { var myClass: MyClass? = nil // 编译错误,myClass 无法进行字段映射 enum CodingKeys: String, CodingTableKey { typealias Root = Sample static let objectRelationalMapping = TableBinding(CodingKeys.self) case myClass } } ``` -------------------------------- ### Convert Raw SQL to Language Integrated Query Source: https://github.com/tencent/wcdb/wiki/C++-语言集成查询 Examples showing the mapping of raw SQL clauses to WCDB C++ fluent API calls. ```sql SELECT min(identifier) FROM sampleTable WHERE (identifier > 0 || identifier / 2 == 0 ) && description NOT NULL ORDER BY identifier ASC LIMIT 1, 100 ``` ```c++ WCDB::StatementSelect statementSelect = WCDB::StatementSelect() ``` ```c++ statementSelect.select(WCDB_FIELD(Sample::identifier).min().distinct()) statementSelect.from("sampleTable") ``` ```c++ statementSelect.where((WCDB_FIELD(Sample::identifier) > 0 || WCDB_FIELD(Sample::identifier) / 2 == 0) && WCDB_FIELD(Sample::content).notNull()) ``` ```c++ statementSelect.order(WCDB_FIELD(Sample::identifier).asOrder(WCTOrderedAscending)) statementSelect.limit(1, 100) ``` -------------------------------- ### Retrieve All Objects in Kotlin Source: https://github.com/tencent/wcdb/wiki/Java|Kotlin-增删查改 Fetch all data from a table in Kotlin using `getAllObjects`. This is the equivalent of the Java example for retrieving all records. ```kotlin //Kotlin // 返回 sampleTable 中的所有数据 val allObjects = database.getAllObjects(DBSample.allFields(), "sampleTable") ``` -------------------------------- ### Manual Conversion of Expression to ResultColumn Source: https://github.com/tencent/wcdb/wiki/Swift-语言集成查询 This is a conceptual example illustrating the manual conversion process from an Expression to a ResultColumn, which is necessary if the select function strictly accepts ResultColumn objects. It highlights the verbosity before the Convertible protocol. ```swift // 以下为示例代码,并非 WCDB Swift 真正的实现 class StatementSelect { func select(_ ResultColumn: ResultColumn...) -> StatementSelect // ... } let identifierColumn = Column(named: "identifier") let identifierExpression = Expression(identifierColumn) let identifierResultColumn = ResultColumn(with: identifierExpression) let statementSelect = StatementSelect().select(identifierResultColumn).from("sampleTable") print(statementSelect.description) // 输出 "SELECT identifier FROM sampleTable" ``` -------------------------------- ### Retrieve the First Object with Ordering in Java Source: https://github.com/tencent/wcdb/wiki/Java|Kotlin-增删查改 Use `getFirstObject` to retrieve a single object, ordered by a specific criterion. This example fetches the row with the maximum 'id'. ```java // 返回 sampleTable 中 identifier 最大的行的数据 Sample object = database.getFirstObject(DBSample.allFields(), "sampleTable", DBSample.id.order(Order.Desc)); ``` -------------------------------- ### Retrieve Specific Fields in Java Source: https://github.com/tencent/wcdb/wiki/Java|Kotlin-增删查改 Fetch only specific fields from a table by providing an array of `Field` objects. This example retrieves only the 'id' field, leaving 'content' null. ```java // 返回 sampleTable 中的所有id字段,返回结果中的content内容为空 List partialObjects = database.getAllObjects(new Field[]{DBSample.id}, "sampleTable"); ``` -------------------------------- ### Retrieve the First Object with Ordering in Kotlin Source: https://github.com/tencent/wcdb/wiki/Java|Kotlin-增删查改 Get a single, ordered object in Kotlin using `getFirstObject`. This example retrieves the record with the highest 'id' value. ```kotlin // 返回 sampleTable 中 identifier 最大的行的数据 val `object` = database.getFirstObject(DBSample.allFields(),"sampleTable", DBSample.id.order(Order.Desc)) ``` -------------------------------- ### Construct SQL Queries with WINQ in Swift Source: https://context7.com/tencent/wcdb/llms.txt Demonstrates using native Swift syntax for SQL expressions, including comparison, logical, and aggregate operations, as well as building and executing a select statement. ```swift // Swift - WINQ expressions // Comparison operators let condition1 = Sample.Properties.identifier > 1 let condition2 = Sample.Properties.identifier >= 1 let condition3 = Sample.Properties.identifier == 1 let condition4 = Sample.Properties.identifier != 1 let condition5 = Sample.Properties.description.isNull() let condition6 = Sample.Properties.description.isNotNull() // Logical operators let combinedCondition = (Sample.Properties.identifier > 1 && Sample.Properties.identifier < 100) || Sample.Properties.description.like("test%") // Arithmetic operators let expression = Sample.Properties.identifier + 1 let expression2 = Sample.Properties.identifier * 2 // Aggregate functions let maxId = Sample.Properties.identifier.max() let minId = Sample.Properties.identifier.min() let avgId = Sample.Properties.identifier.avg() let sumId = Sample.Properties.identifier.sum() let countAll = Sample.Properties.identifier.count() // String operations let likeCondition = Sample.Properties.description.like("prefix%") let globCondition = Sample.Properties.description.glob("prefix*") let betweenCondition = Sample.Properties.identifier.between(1, 100) let inCondition = Sample.Properties.identifier.in([1, 2, 3, 4, 5]) // Build complete statement let statement = StatementSelect() .select(Sample.Properties.identifier, Sample.Properties.description) .from("sampleTable") .where(Sample.Properties.identifier > 0 || Sample.Properties.description.isNotNull()) .order(by: Sample.Properties.identifier.asOrder(by: .ascending)) .limit(100) print(statement.description) // Output: SELECT identifier, description FROM sampleTable WHERE ((identifier > 0) OR (description IS NOT NULL)) ORDER BY identifier ASC LIMIT 100 // Execute raw statement let rows = try database.getRows(from: statement) ``` -------------------------------- ### Initialize a database object Source: https://github.com/tencent/wcdb/wiki/Swift-快速入门 Create a database instance; WCDB automatically creates necessary intermediate directories. ```swift let database = Database(at: "~/Intermediate/Directories/Will/Be/Created/sample.db") ``` -------------------------------- ### Basic WINQ Query Usage Source: https://github.com/tencent/wcdb/wiki/C++-语言集成查询 Demonstrates a simple database query using WINQ syntax to filter results. ```c++ WCDB::OptionalValueArray objects = database.getAllObjects("sampleTable", WCDB_FIELD(Sample::identifier) > 1); ``` -------------------------------- ### Define Model for Partial Query Source: https://github.com/tencent/wcdb/wiki/Swift-增删查改 Example of a model definition that will fail during partial queries if non-optional properties are not retrieved. ```swift class PartialSample: TableCodable { var identifier: Int? = nil var description: String = "" enum CodingKeys: String, CodingTableKey { typealias Root = PartialSample static let objectRelationalMapping = TableBinding(CodingKeys.self) case identifier case description } } // 由于 description 是 String 类型,"getObject" 过程无法对其进行初始化,因此以下调用会出错。 // 正确的方式应将 `var description: String` 改为 `var description: String?` let partialObjects: [PartialSample] = try database.getObjects(fromTable: "sampleTable", on: Sample.Properties.identifier) ``` -------------------------------- ### Configure Data Migration Source and Target Source: https://github.com/tencent/wcdb/wiki/Swift-数据迁移 Set up source and target databases, create tables, and configure migration mapping before performing any data operations on the target database. This assumes migration is already complete. ```swift let sourceDatabase = Database(at: sourcePath) try sourceDatabase.create(table: "sourceTable", of: Sample.self) let oldObject1 = Sample() oldObject1.identifier = 1; oldObject1.description = "oldContent1" let oldObject2 = Sample() oldObject2.identifier = 2; oldObject2.description = "oldContent2" try sourceDatabase.insert(oldObject1, oldObject2, intoTable: "sourceTable") let targetDatabase = Database(at: targetPath) targetDatabase.addMigration(sourcePath: sourcePath)({ info in if info.table == "targetTable" { info.sourceTable = "sourceTable" } }) try targetDatabase.create(table: "targetTable", of: Sample.self) ``` -------------------------------- ### Configure Data Migration (Swift) Source: https://context7.com/tencent/wcdb/llms.txt Set up data migration between tables or databases. Configure migration rules, create target tables, and manage migration progress. ```swift // Swift - Data migration let sourceDatabase = Database(at: sourcePath) let targetDatabase = Database(at: targetPath) // Configure migration (must be set before any operation on target database) targetDatabase.addMigration(sourcePath: sourcePath) { if info.table == "newUserTable" { info.sourceTable = "oldUserTable" // Optional: filter which rows to migrate // info.filterCondition = Column(named: "active").eq(true) } } // Create target table try targetDatabase.create(table: "newUserTable", of: User.self) // Now you can use target table as if migration is complete // WCDB handles reading from both tables transparently let users: [User] = try targetDatabase.getObjects(fromTable: "newUserTable") // Enable automatic background migration targetDatabase.setAutoMigration(enable: true) // Or manually control migration pace while !targetDatabase.isMigrated() { try targetDatabase.stepMigration() } // Monitor migration progress targetDatabase.setNotification { if let sourceTable = info?.sourceTable { print("Migrated table: \(sourceTable)") } } ``` -------------------------------- ### Configure Data Migration Source Source: https://github.com/tencent/wcdb/wiki/Java|Kotlin-数据迁移 Set up a source database and table, then configure the target database to migrate data from the source. This configuration must be done before any data operations on the target database. ```java Database sourceDatabase = new Database(sourcePath); sourceDatabase.createTable("sourceTable", DBSample.INSTANCE); Sample oldObject1 = new Sample(); oldObject1.id = 1; oldObject1.content = "oldContent1"; Sample oldObject2 = new Sample(); oldObject2.id = 2; oldObject2.content = "oldContent2"; sourceDatabase.insertObjects(Arrays.asList(oldObject1, oldObject2), DBSample.allFields(), "sourceTable"); Database targetDatabase = new Database(targetPath); targetDatabase.addMigrationSource(sourcePath, new Database.MigrationFilter() { @Override public void filterMigrate(Database.MigrationInfo info) { if(info.table.equals("targetTable")) { info.sourceTable = "sourceTable"; } } }); targetDatabase.createTable("targetTable", DBSample.INSTANCE); ``` -------------------------------- ### 安装 WCDB 模版工具 Source: https://github.com/tencent/wcdb/wiki/Swift-模型绑定 通过命令行脚本安装 WCDB 的 Xcode 文件和代码模版。 ```bash curl https://raw.githubusercontent.com/Tencent/wcdb/master/tools/templates/install.sh -s | sh ``` ```bash cd path-to-your-wcdb-dir/tools/templates; sh install.sh; ``` -------------------------------- ### Construct SQL Queries with WINQ in C++ Source: https://context7.com/tencent/wcdb/llms.txt Shows how to use the WCDB_FIELD macro to build type-safe SQL conditions and statements in C++. ```cpp // C++ - WINQ expressions auto condition = WCDB_FIELD(Sample::identifier) > 0 && WCDB_FIELD(Sample::content).like("test%"); auto objects = database.getAllObjects("sampleTable", condition); // Build statement auto statement = WCDB::StatementSelect() .select(WCDB_FIELD(Sample::identifier)) .from("sampleTable") .where(WCDB_FIELD(Sample::identifier) > 0); ``` -------------------------------- ### Bind Sample Class with WCDB Source: https://github.com/tencent/wcdb/wiki/Objc-快速入门 Applying WCDB macros to map the Sample class properties to database table columns. ```objective-c @interface Sample : NSObject @property (nonatomic, assign) int identifier; @property (nonatomic, strong) NSString* content; WCDB_PROPERTY(identifier) WCDB_PROPERTY(content) @end @implementation Sample WCDB_IMPLEMENTATION(Sample) WCDB_SYNTHESIZE(identifier) WCDB_SYNTHESIZE(content) @end ``` -------------------------------- ### Basic WINQ Query with Swift Syntax Source: https://github.com/tencent/wcdb/wiki/Swift-语言集成查询 Demonstrates a simple database query using WINQ, where Swift syntax replaces traditional SQL strings for the WHERE clause. The result of the comparison is an Expression, not a Bool. ```swift let objects: [Sample] = try database.getObjects(fromTable: "sampleTable", where: Sample.Properties.idetifier > 1) ``` -------------------------------- ### Retrieve a Specific Column from a Table Source: https://github.com/tencent/wcdb/wiki/Swift-语言集成查询 Executes a SELECT statement to get all values from the 'content' column in 'sampleTable' using database.getColumn(). It then prints the fourth element of the resulting array. ```swift // 获取第二行 content 列的值 let contentColumn = try database.getColumn(from: StatementSelect().select(Sample.Properties.content).from("sampleTable")) print(contentColumn[3]) //输出 "sample2" ``` -------------------------------- ### Execute Statement and Get Single Value Source: https://github.com/tencent/wcdb/wiki/Objc-语言集成查询 Use `getValueFromStatement:` to execute a statement that returns a single scalar value, such as an aggregate function result (e.g., MAX, COUNT). ```Objective-C // 获取 identifier 的最大值 WCTValue* maxId = [database getValueFromStatement:WCDB::StatementSelect().select(Sample.identifier.max()).from(@"sampleTable")]; NSLog(@"%@", maxId);// 输出 5 ``` ```Objective-C // 获取不同的 content 数 WCTValue* distinctContentCount = [database getValueFromStatement:WCDB::StatementSelect().select(Sample.content.count().distinct()).from(@"sampleTable")]; NSLog(@"%@", distinctContentCount);// 输出 2 ``` -------------------------------- ### Creating a Column and Insert Statement Source: https://github.com/tencent/wcdb/wiki/C++-语言集成查询 Shows how to define a database column and use it within an INSERT statement. ```c++ WCDB::Column identifierColumm = WCDB::Column("identifier"); WCDB::StatementInsert insert = WCDB::StatementInsert() .insertIntoTable("sampleTable") .column(identifierColumm).value(1); printf("%s", insert.getDescription().data()); // 输出 "INSERT INTO sampleTable(identifier) VALUES(1)" ``` -------------------------------- ### Retrieve Specific Fields in Kotlin Source: https://github.com/tencent/wcdb/wiki/Java|Kotlin-增删查改 Select only specific columns when querying data in Kotlin. This example retrieves only the 'id' field, resulting in null values for other fields like 'content'. ```kotlin // 返回 sampleTable 中的所有id字段,返回结果中的content内容为空 val partialObjects: List = database.getAllObjects(arrayOf(DBSample.id), "sampleTable") ``` -------------------------------- ### Optimize Bulk Insert Performance Source: https://github.com/tencent/wcdb/wiki/Java|Kotlin-数据库、表、事务 Demonstrates performance differences between individual inserts, transaction-wrapped inserts, and optimized bulk insert methods. ```java Sample sample = new Sample(); List samples = Collections.nCopies(100000, sample); // 单独插入,效率很差 for(Sample obj : samples){ table.insertObject(obj); } // 事务插入,性能较好 database.runTransaction(new Transaction() { @Override public boolean insideTransaction(Handle handle) throws WCDBException { for(Sample obj : samples){ table.insertObject(obj); } return true; } }); // insert 接口内置了事务,并对批量数据做了针对性的优化,性能更好 table.insertObjects(samples); ``` ```kotlin val sample = Sample() val samples = Collections.nCopies(100000, sample) // 单独插入,效率很差 for (obj in samples) { table.insertObject(obj) } // 事务插入,性能较好 database.runTransaction { for (obj in samples) { table.insertObject(obj) } true } // insert 接口内置了事务,并对批量数据做了针对性的优化,性能更好 table.insertObjects(samples) ``` -------------------------------- ### Execute Statement and Get All Rows Source: https://github.com/tencent/wcdb/wiki/Objc-语言集成查询 Use `getRowsFromStatement:` to execute a SELECT statement and retrieve all resulting rows as a 2D array. Access specific cells using array indexing. ```Objective-C // 获取所有内容 WCTColumnsXRows* allRows = [database getRowsFromStatement:WCDB::StatementSelect().select(Sample.allProperties).from("sampleTable")]; NSLog(@"%@", allRows[2][0]); // 输出 3 ``` -------------------------------- ### Initialize a Table Object Source: https://github.com/tencent/wcdb/wiki/Java|Kotlin-数据库、表、事务 Obtain a Table instance from a database using a table name and a model binding. ```java Table table = database.getTable("sampleTable", DBSample.INSTANCE); ``` ```kotlin val table = database.getTable("sampleTable", DBSample) ``` -------------------------------- ### Retrieve Objects with Conditional Filtering in Java Source: https://github.com/tencent/wcdb/wiki/Java|Kotlin-增删查改 Filter objects based on specific criteria using the `condition` parameter. This example retrieves rows where the 'id' is less than 5 or greater than 10. ```java // 返回 sampleTable 中 identifier 小于 5 或 大于 10 的行的数据 List objects = database.getAllObjects(DBSample.allFields(), "sampleTable", DBSample.id.lt(5).or(DBSample.id.gt(10))); ``` -------------------------------- ### Retrieve All Objects in Java Source: https://github.com/tencent/wcdb/wiki/Java|Kotlin-增删查改 Use `getAllObjects` with `DBSample.allFields()` and the table name to fetch all data from a table. Ensure the `Sample` class is properly mapped. ```java //Java // 返回 sampleTable 中的所有数据 List allObjects = database.getAllObjects(DBSample.allFields(), "sampleTable"); ``` -------------------------------- ### Execute Statement and Get Specific Column Source: https://github.com/tencent/wcdb/wiki/Objc-语言集成查询 Use `getColumnFromStatement:` to retrieve all values from a specific column across multiple rows. The result is a 1D array containing the column's data. ```Objective-C // 获取第二行 content 列的值 WCTOneColumn* contentColumn = [database getColumnFromStatement:WCDB::StatementSelect().select(Sample.content).from("sampleTable")]; NSLog(@"%@", contentColumn); // 输出 "sample1", "sample1", "sample1", "sample2", "sample2" ``` -------------------------------- ### Execute SQL Statements for Data Retrieval Source: https://github.com/tencent/wcdb/wiki/C++-语言集成查询 Demonstrates various methods to execute SELECT statements and retrieve results as values, rows, or columns. ```c++ // 获取所有内容 WCDB::OptionalMultiRows allRows = database.getAllRowsFromStatement(WCDB::StatementSelect().select(Sample::allFields()).from("sampleTable")); printf("%lld", allRows.value()[2][0].intValue()); // 输出 3 // 获取第二行 WCDB::OptionalOneRow secondRow = database.getOneRowFromStatement(WCDB::StatementSelect().select(Sample::allFields()).from("sampleTable").offset(1)); printf("%lld", secondRow.value()[0].intValue()); // 输出 2 // 获取第二行 content 列的值 WCDB::OptionalOneColumn contentColumn = database.getOneColumnFromStatement(WCDB::StatementSelect().select(WCDB_FIELD(Sample::content)).from("sampleTable")); printf("%s", contentColumn.value()[3].textValue().data()); // 输出 "sample2" // 获取 identifier 的最大值 WCDB::OptionalValue maxId = database.getValueFromStatement(WCDB::StatementSelect().select(WCDB_FIELD(Sample::identifier).max()).from("sampleTable")); printf("%lld", maxId.value().intValue());// 输出 5 // 获取不同的 content 数 WCDB::OptionalValue distinctContentCount = database.getValueFromStatement(WCDB::StatementSelect().select(WCDB_FIELD(Sample::content).count().distinct()).from("sampleTable")); printf("%lld", distinctContentCount.value().intValue());// 输出 2 ``` -------------------------------- ### Create a database table Source: https://github.com/tencent/wcdb/wiki/Swift-快速入门 Create a table based on a model-bound class using a single line of code. ```swift // 以下代码等效于 SQL:CREATE TABLE IF NOT EXISTS sampleTable(identifier INTEGER, description TEXT) database.create(table: "sampleTable", of: Sample.self) ``` -------------------------------- ### Retrieve Objects with Conditional Filtering in Kotlin Source: https://github.com/tencent/wcdb/wiki/Java|Kotlin-增删查改 Apply conditions to filter data in Kotlin. This example retrieves rows where the 'id' field meets the specified criteria (less than 5 or greater than 10). ```kotlin // 返回 sampleTable 中 identifier 小于 5 或 大于 10 的行的数据 val objects = database.getAllObjects(DBSample.allFields(), "sampleTable", DBSample.id.lt(5).or(DBSample.id.gt(10))) ``` -------------------------------- ### Perform CRUD Operations with WCDB Source: https://github.com/tencent/wcdb/blob/master/README.md Demonstrates basic insert, update, query, and delete operations using ORM and WINQ across supported languages. ```c++ // C++ database.insertObjects(Sample(1, "text"), myTable); database.updateRow("text2", WCDB_FIELD(Sample::content), myTable, WCDB_FIELD(Sample::id) == 1); auto objects = database.getAllObjects(myTable, WCDB_FIELD(Sample::id) > 0); database.deleteObjects(myTable, WCDB_FIELD(Sample::id) == 1); ``` ```java // Java database.insertObject(new Sample(1, "text"), DBSample.allFields(), myTable); database.updateValue("text2", DBSample.content, myTable, DBSample.id.eq(1)); List objects = database.getAllObjects(DBSample.allFields(), myTable, DBSample.id.gt(0)); database.deleteObjects(myTable, DBSample.id.eq(1)); ``` ```kotlin // Kotlin database.insertObject(Sample(1, "text"), DBSample.allFields(), myTable) database.updateValue("text2", DBSample.content, myTable, DBSample.id.eq(1)) val objects = database.getAllObjects(DBSample.allFields(), myTable, DBSample.id.gt(0)) database.deleteObjects(myTable, DBSample.id.eq(1)) ``` ```swift // Swift try database.insert(Sample(id:1, content:"text"), intoTable: myTable) try database.update(table: myTable, on: Sample.Properties.content, with: "text2" where:Sample.Properties.id == 1) let objects: [Sample] = try database.getObjects(fromTable: myTable, where: Sample.Properties.id > 0) try database.delete(fromTable: myTable where: Sample.Properties.id == 1) ``` ```objective-c // Objc [database insertObject:sample intoTable:myTable]; [database updateTable:myTable setProperty:Sample.content toValue:@"text2" where:Sample.id == 1]; NSArray* objects = [database getObjectsOfClass:Sample.class fromTable:myTable where:Sample.id > 0]; [database deleteFromTable:myTable where:Sample.id == 1]; ``` -------------------------------- ### Implementing Convertible Types Source: https://github.com/tencent/wcdb/wiki/C++-语言集成查询 Demonstrates the use of C++ SFINAE to allow automatic type conversion between WINQ components. ```c++ template class ResultColumnConvertible final : public std::false_type { public: static ResultColumn asResultColumn(const T&); }; template<> class ResultColumnConvertible final : public std::true_type { public: static ResultColumn asResultColumn(const Expression& expression); }; class ResultColumn { template::value>::type> ResultColumn(const T& t) : ResultColumn(ResultColumnConvertible::asResultColumn(t)) { } } ``` ```c++ // WCDB 内部的代码示例 template<> class ExpressionConvertible final : public std::true_type { public: static Expression asExpression(const Column& column); }; template class ResultColumnConvertible::value>::type> final : public std::true_type { public: static ResultColumn asResultColumn(const T& t) { return ExpressionConvertible::asExpression(t); } }; ``` -------------------------------- ### Execute Statement and Get Second Row Source: https://github.com/tencent/wcdb/wiki/Objc-语言集成查询 Use `getRowFromStatement:` to fetch a single row from a SELECT statement, offset by a specified number of rows. The result is a 1D array representing the row's columns. ```Objective-C // 获取第二行 WCTOneRow* secondRow = [database getRowFromStatement:WCDB::StatementSelect().select(Sample.allProperties).from("sampleTable").offset(1)]; NSLog(@"%@", secondRow[0]); // 输出 2 ``` -------------------------------- ### Create Database Object Source: https://github.com/tencent/wcdb/wiki/Objc-快速入门 Initialize a WCTDatabase instance. WCDB automatically creates intermediate directories if they do not exist. ```objective-c WCTDatabase* database = [[WCTDatabase alloc] initWithPath:@"~/Intermediate/Directories/Will/Be/Created/sample.db"]; ``` -------------------------------- ### Initialize StatementSelect in C++ Source: https://github.com/tencent/wcdb/wiki/Objc-语言集成查询 Demonstrates the initialization of a `StatementSelect` object in C++, which is the base for building SELECT queries using WCDB's language-integrated syntax. ```C++ WCDB::StatementSelect statementSelect = WCDB::StatementSelect() ``` -------------------------------- ### Define a basic Swift class Source: https://github.com/tencent/wcdb/wiki/Swift-快速入门 A standard Swift class structure before applying WCDB model binding. ```swift class Sample { var identifier: Int? = nil var description: String? = nil } ``` -------------------------------- ### WCDB Object Query Interface Signatures Source: https://github.com/tencent/wcdb/wiki/Java|Kotlin-增删查改 These are the full signature prototypes for the `getFirstObject` and `getAllObjects` methods in WCDB, illustrating the parameters for querying objects. ```java public T getFirstObject( Field[] fields, //指定查询的字段,查询所有字段可以用DBxxx.allFields() String tableName, //查询的表名 Expression condition, //筛选条件 OrderingTerm order, //排序方式 long limit, //查询的个数 long offset //从第几个开始读取 ) throws WCDBException public List getAllObjects( Field[] fields, //指定查询的字段,查询所有字段可以用DBxxx.allFields() String tableName, //查询的表名 Expression condition, //筛选条件 OrderingTerm order, //排序方式 long limit, //查询的个数 long offset //从第几个开始读取 ) throws WCDBException ``` -------------------------------- ### Querying Database Objects using Model Properties Source: https://github.com/tencent/wcdb/wiki/Swift-语言集成查询 Retrieves database objects by specifying model properties, demonstrating the integration of WINQ with model bindings. This approach avoids string-based column names. ```swift let property = Sample.Properties.identifier.asProperty() let objects: [Sample] = try database.getObjects(on: property, fromTable: "sampleTable") ``` -------------------------------- ### Define Build Targets and Dependencies Source: https://github.com/tencent/wcdb/blob/master/src/CMakeLists.txt Configures the main library target, including standard C++ settings, linking to sqlcipher, and optional inclusion of Zstandard, C++ sources, and bridge components. ```cmake if (UNIX) set(CMAKE_POSITION_INDEPENDENT_CODE ON) endif () set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) add_library(${TARGET_NAME} ${WCDB_COMMON_SRC}) target_link_libraries(${TARGET_NAME} PRIVATE sqlcipher) target_include_directories(${TARGET_NAME} PUBLIC ${WCDB_COMMON_INCLUDES}) if (WCDB_ZSTD) include(zstd.cmake) target_link_libraries(${TARGET_NAME} PRIVATE zstd) target_compile_definitions(${TARGET_NAME} PRIVATE WCDB_ZSTD=1) endif () if (WIN32) target_compile_options(${TARGET_NAME} PRIVATE /EHsc) else () target_compile_options(${TARGET_NAME} PRIVATE -fno-exceptions) endif() if (WCDB_CPP) target_sources(${TARGET_NAME} PRIVATE ${WCDB_CPP_SRC}) target_include_directories(${TARGET_NAME} PUBLIC ${WCDB_CPP_INCLUDES}) endif () if (WCDB_BRIDGE) target_sources(${TARGET_NAME} PRIVATE ${WCDB_BRIDGE_SRC}) target_include_directories(${TARGET_NAME} PUBLIC ${WCDB_BRIDGE_INCLUDES}) endif () ``` -------------------------------- ### Create Database Table Source: https://github.com/tencent/wcdb/wiki/Objc-快速入门 Create a table based on the model-bound class. ```objective-c // 以下代码等效于 SQL:CREATE TABLE IF NOT EXISTS sampleTable(identifier INTEGER, content TEXT) BOOL ret = [database createTable:@"sampleTable" withClass:Sample.class]; ``` -------------------------------- ### Define and Configure WCDB Library Source: https://github.com/tencent/wcdb/blob/master/src/java/main/src/main/cpp/CMakeLists.txt Creates a library target named 'WCDB', sets its visibility to PUBLIC, and adds the discovered JNI source files and include directories to it. Gradle will automatically package shared libraries with your APK. ```cmake target_sources(${TARGET_NAME} PUBLIC ${WCDB_JNI_SRC}) target_include_directories(${TARGET_NAME} PUBLIC ${WCDB_JNI_INCLUDES}) ``` -------------------------------- ### Manage Database Backup and Recovery (Swift) Source: https://context7.com/tencent/wcdb/llms.txt Implement automatic backup, manual backup, and corruption recovery for your database. Configure table filtering for backups and set up corruption notifications. ```swift // Swift - Backup and recovery // Enable automatic backup database.setAutoBackup(enable: true) // Manual backup try database.backup() // Filter tables to backup database.filterBackup { return tableName != "cacheTable" // Don't backup cache } // Set corruption notification database.setNotification { print("Database corrupted: \(corruptedDatabase.path)") print("Is corrupted: \(corruptedDatabase.isAlreadyCorrupted())") } // Repair corrupted database with progress DispatchQueue.global().async { let score = database.retrieve { DispatchQueue.main.async { print("Recovery progress: \(percentage)%") } return true // Return false to abort recovery } print("Recovery completed with score: \(score)") } // Deposit corrupted database for later recovery try database.deposit() if database.containDepositedFiles() { // Later, after recovery succeeds, remove deposited files try database.removeDepositedFiles() } ``` -------------------------------- ### Configure Global Tracing and Error Handling in Swift Source: https://context7.com/tencent/wcdb/llms.txt Use global trace methods to monitor database errors, SQL execution, and performance metrics. Implement do-catch blocks with WCDBError to handle specific database constraints. ```swift // Swift - Error handling and monitoring // Global error monitoring Database.globalTraceError { error in print("WCDB Error: \(error.description)") print("Code: \(error.code)") print("Message: \(error.message ?? "none")") print("SQL: \(error.sql ?? "none")") } // SQL tracing for debugging Database.globalTraceSQL { _, sql, _ in print("Executed SQL: \(sql)") } // Performance tracing Database.globalTracePerformance { _, sql, info in print("SQL: \(sql), Cost: \(info.costInNanoseconds)ns") } // Try-catch pattern do { try database.insert(objects: object, intoTable: "sampleTable") } catch let error as WCDBError { print("Insert failed: \(error.description)") if error.code == .constraint { print("Constraint violation occurred") } } ``` -------------------------------- ### Define and Create Tables with Model Binding Source: https://context7.com/tencent/wcdb/llms.txt Maps native language classes to database tables using protocol conformance, macros, or annotations. Requires defining the model structure before invoking table creation methods. ```swift // Swift - Define a model class with TableCodable protocol class Sample: TableCodable { var identifier: Int? = nil var description: String? = nil enum CodingKeys: String, CodingTableKey { typealias Root = Sample static let objectRelationalMapping = TableBinding(CodingKeys.self) { BindColumnConstraint(identifier, isPrimary: true, isAutoIncrement: true) BindColumnConstraint(description, isNotNull: true, defaultTo: "default") } case identifier case description } var isAutoIncrement: Bool = false var lastInsertedRowID: Int64 = 0 } // Create table based on model binding let database = Database(at: "~/Documents/sample.db") try database.create(table: "sampleTable", of: Sample.self) // Equivalent SQL: CREATE TABLE IF NOT EXISTS sampleTable(identifier INTEGER PRIMARY KEY AUTOINCREMENT, description TEXT NOT NULL DEFAULT 'default') ``` ```cpp // C++ - Define a model class with ORM macros // Sample.hpp class Sample { public: Sample(); Sample(int identifier, const std::string& content); int identifier; std::string content; WCDB_CPP_ORM_DECLARATION(Sample) }; // Sample.cpp WCDB_CPP_ORM_IMPLEMENTATION_BEGIN(Sample) WCDB_CPP_SYNTHESIZE(identifier) WCDB_CPP_SYNTHESIZE(content) WCDB_CPP_PRIMARY(identifier) WCDB_CPP_ORM_IMPLEMENTATION_END // Create table WCDB::Database database("~/Documents/sample.db"); bool ret = database.createTable("sampleTable"); ``` ```java // Java/Kotlin - Define a model class with annotations @WCDBTableCoding public class Sample { @WCDBField public int id; @WCDBField public String content; } // Create table using generated DBSample class Database database = new Database("~/Documents/sample.db"); database.createTable("sampleTable", DBSample.INSTANCE); ``` ```objective-c // Objective-C - Define a model class with WCDB macros @interface Sample : NSObject @property (nonatomic, assign) int identifier; @property (nonatomic, strong) NSString* content; WCDB_PROPERTY(identifier) WCDB_PROPERTY(content) @end @implementation Sample WCDB_IMPLEMENTATION(Sample) WCDB_SYNTHESIZE(identifier) WCDB_SYNTHESIZE(content) @end // Create table WCTDatabase* database = [[WCTDatabase alloc] initWithPath:@"~/Documents/sample.db"]; BOOL ret = [database createTable:@"sampleTable" withClass:Sample.class]; ``` -------------------------------- ### Zlib and OpenSSL Link Directories for Windows Source: https://github.com/tencent/wcdb/blob/master/src/CMakeLists.txt Sets link directories for Zlib and OpenSSL on Windows, with specific paths for win64 and win32 architectures. ```cmake target_link_directories(sqlcipher PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../tools/prebuild/openssl/windows/win64) else () target_link_directories(${TARGET_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../tools/prebuild/zlib/windows/win32) target_link_directories(sqlcipher PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../tools/prebuild/openssl/windows/win32) endif() ``` -------------------------------- ### Batch Insertion Performance Comparison Source: https://github.com/tencent/wcdb/wiki/Objc-数据库、表、事务 Compares the performance of single insertions versus batch insertions using `insertObjects:`. Use `insertObjects:` for better performance as it's optimized for bulk data and includes transactions. ```Objective-C NSMutableArray* objects = [[NSMutableArray alloc] init]; for(int i = 0; i < 100000; i++) { Sample* obj = [[Sample alloc] init]; obj.identifier = i; [objects addObject:obj]; } // 单独插入,效率很差 for(Sample* obj in objects) { [table insertObject:obj]; } // 事务插入,性能较好 [database runTransaction:^BOOL(WCTHandle * handle) { for(Sample* obj in objects) { [table insertObject:obj]; } }]; // insertObjects: 接口内置了事务,并对批量数据做了针对性的优化,性能更好 [table insertObjects:objects]; ``` -------------------------------- ### 升级模型绑定定义 Source: https://github.com/tencent/wcdb/wiki/Swift-模型绑定 通过修改模型绑定并再次调用 create(table:of:) 来实现字段重命名、删除旧字段、新增字段及索引。 ```swift class Sample: TableCodable { var identifier: Int? = nil var content: String? = nil var title: String? = nil enum CodingKeys: String, CodingTableKey { typealias Root = Sample case identifier case content = "description" case title static let objectRelationalMapping = TableBinding(CodingKeys.self) { BindIndex(title, namedWith: "_index") } } } try database.create(table: "sampleTable", of: Sample.self) ``` -------------------------------- ### Define Sample Class Source: https://github.com/tencent/wcdb/wiki/Objc-快速入门 The initial definition of the Sample class before applying WCDB ORM macros. ```objective-c @interface Sample : NSObject @property (nonatomic, assign) int identifier; @property (nonatomic, strong) NSString* content; @end @implementation Sample @end ``` -------------------------------- ### Create WCDB Expressions from Various Types Source: https://github.com/tencent/wcdb/wiki/Swift-语言集成查询 Demonstrates creating Expression objects from integers, doubles, strings, data, and columns. These expressions can be used in database queries. ```swift let expressionInt = Expression(with: 1) let expressionDouble = Expression(with: 2.0) let expressionString = Expression(with: "3") let expressionData = Expression(with: "4".data(using: .ascii)!) let expressionColumn = Expression(with: Column(named: "identifier")) ``` -------------------------------- ### Manual Conversion using asResultColumn() Source: https://github.com/tencent/wcdb/wiki/Swift-语言集成查询 Shows how to manually convert a Column object to a ResultColumn using the `asResultColumn()` method, which is available for types conforming to the ResultColumnConvertible protocol. ```swift let identifierColumn = Column(named: "identifier") let identifierResultColumn = identifierColumn.asResultColumn() ``` -------------------------------- ### Configure WCDB Build Options Source: https://github.com/tencent/wcdb/blob/master/src/java/main/src/main/cpp/CMakeLists.txt Sets various build options for WCDB, such as the target name, enabling bridge functionality, skipping Conan, and building shared libraries. ```cmake set(TARGET_NAME "WCDB") set(WCDB_BRIDGE ON) set(SKIP_WCONAN ON) set(BUILD_SHARED_LIBS ON) ``` -------------------------------- ### Create Table from ORM Model Source: https://github.com/tencent/wcdb/wiki/C++-模型绑定 Use the createTable interface to initialize a database table based on the defined ORM model. ```c++ // 以下代码等效于 SQL:CREATE TABLE IF NOT EXISTS sampleTable(id INTEGER, content TEXT, db_offset INTEGER) bool ret = database.createTable("sampleTable"); ``` -------------------------------- ### Creating and Using a Column in an Insert Statement Source: https://github.com/tencent/wcdb/wiki/Swift-语言集成查询 Shows how to define a database column by its name and use it within an INSERT statement to specify which column receives a value. The output is the generated SQL string. ```swift let identifierColumn = Column(named: "identifier") let statementInsert = StatementInsert().insert(intoTable: "sampleTable") .columns(identifierColumn) .values(1) print(statementInsert.description) // 输出 "INSERT INTO sampleTable(identifier) VALUES(1)" ``` -------------------------------- ### Demonstrate Race Conditions Source: https://github.com/tencent/wcdb/wiki/Java|Kotlin-数据库、表、事务 Shows how concurrent operations can lead to non-deterministic results without transaction atomicity. ```java Thread thread = new Thread(new Runnable() { @Override public void run() { table.deleteObjects(); } }); thread.start(); table.insertObject(sample); Value count = table.getValue(Column.all().count()); System.out.print(count);// 可能输出 0 或 1 ``` ```kotlin val thread = Thread { table.deleteObjects() } thread.start() table.insertObject(sample) val count = table.getValue(Column.all().count()) print(count) // 可能输出 0 或 1 ```