This guide covers migrating from Ditto’s legacy query builder API to DQL (Ditto Query Language) in C++. DQL provides a SQL-like syntax that’s more powerful and intuitive for querying and manipulating data.Note: This migration is required alongside the V4→V5 API Migration for a complete upgrade.
Use this prompt when working with an AI coding assistant to migrate your Ditto C++ app to DQL.
Copy AI Migration Prompt (Click to Expand)
I need help migrating a Ditto C++ application from legacy query builder to DQL (Ditto Query Language). Focus on these critical changes:QUERIES:Replace collection().find() with DQL SELECT statements- Use std::map<std::string, CborValue> for parameterized queries- Use empty map {} for queries without parameters- Quote string literals in queries or use parametersMUTATIONS:Replace upsert/update/remove with DQL INSERT/UPDATE/EVICT- Use parameterized arguments for all values- Results use .then() and .on_error() callbacksOBSERVERS:Convert to register_observer(query, args, callback)- Results are std::vector<CborValue> instead of std::vector<DittoDocument>- Same cleanup pattern with .stop()SUBSCRIPTIONS:Convert to register_subscription(query, args)- Cleanup uses .cancel() instead of .close()COUNTERS:Critical change - use PN_INCREMENT BY in APPLY clause- Never initialize counter fields- Use APPLY clause: "APPLY viewCount = PN_INCREMENT BY :amount"BEFORE (LEGACY):```cppditto->store() .collection("cars") .find("color == 'red'") .exec() .then([](auto docs) { // Use docs });ditto->store() .collection("cars") .find_by_id("abc123") .update([](auto& mutable_doc) { mutable_doc["viewCount"].as_counter().increment(1); });```AFTER (DQL):```cppstd::map<std::string, CborValue> args = {{"color", "red"}};ditto->store().execute( "SELECT * FROM cars WHERE color = :color", args).then([](auto result) { auto cars = result.items(); // Use cars});std::map<std::string, CborValue> args = { {"id", "abc123"}, {"amount", 1}};ditto->store().execute( "UPDATE cars APPLY viewCount = PN_INCREMENT BY :amount WHERE _id = :id", args);```COMMON PITFALLS:- Always quote string literals or use parameters- Never initialize counter fields to 0- Use APPLY (not SET) for counter operations- Use {} for queries without parameters- Use .as_string(), .as_int() for type conversionWork through the codebase systematically. Show me each file's changes.
std::map<std::string, CborValue> args = {{"id", "abc123"}};ditto->store().execute( "SELECT * FROM cars WHERE _id = :id", args).then([](auto result) { if (!result.items().empty()) { auto car = result.items()[0]; // Use car }});
std::map<std::string, CborValue> args = {{"color", "red"}};ditto->store().execute( "SELECT * FROM cars WHERE color = :color", args).then([](auto result) { auto red_cars = result.items(); // Use red_cars});
ditto->store().execute( "SELECT * FROM cars", {}).then([](auto result) { auto items = result.items(); for (const auto& car : items) { auto id = car["_id"].as_string(); auto color = car["color"].as_string(); auto miles = car["miles"].as_int(); std::cout << "Car " << id << " is " << color << " with " << miles << " miles" << std::endl; }});
std::string query = "SELECT * FROM cars WHERE color = :color";std::map<std::string, CborValue> args = {{"color", "red"}};auto observer = ditto->store().register_observer( query, args, [](auto result) { auto red_cars = result.items(); // Update UI with red_cars });// Later: clean upobserver.stop();
Key Differences:
DQL observers use register_observer(query, args, callback) instead of .observe()
Results are std::vector<CborValue> instead of std::vector<DittoDocument>
Same cleanup pattern with .stop()
Performance Consideration: DQL observers provide more advanced return results including aggregates and projections. This requires more database full scans to ensure consistent results compared to the legacy query builder.Use indexes on query fields to maintain and improve observer performance. Indexes ensure your observers remain functional with optimal query performance.
Best Practice: Create Indexes for Observer Queries
// Create index on frequently queried fieldsditto->store().execute( "CREATE INDEX idx_cars_color ON cars (color)", {}).then([](auto result) { std::cout << "Index created" << std::endl;});// Then register observer - queries will use the indexauto observer = ditto->store().register_observer( "SELECT * FROM cars WHERE color = :color", {{"color", "red"}}, [](auto result) { // Process results });
Critical Change: Counters are now modified using the PN_INCREMENT BY operation in the APPLY clause, not by setting values directly.
PN_COUNTER is the DQL equivalent of the legacy DittoCounter type. When migrating counter operations from the legacy query builder’s counter methods, use PN_INCREMENT BY in the APPLY clause. This maintains full compatibility with existing counter data created by DittoCounter.
// Get attachment token from queryditto->store().execute( "SELECT avatar FROM cars WHERE _id = :id", {{"id", "abc123"}}).then([ditto](auto result) { if (!result.items().empty()) { auto car = result.items()[0]; auto token = car["avatar"].as_attachment_token(); if (token) { auto fetcher = ditto->store().fetch_attachment( token, [](auto attachment, auto error) { if (!error) { auto data = attachment.data(); // Use attachment data } } ); } }});
DQL observers and queries benefit significantly from proper indexing. When migrating from the legacy query builder to DQL, creating indexes on frequently queried fields is essential for maintaining optimal performance.Why Indexes Matter for DQL:
DQL observers support advanced features like aggregates and projections
These advanced features require full database scans to ensure consistent results
Indexes dramatically reduce query execution time by avoiding full scans
Combining indexes with observers provides better performance than legacy query builder
Creating Indexes:
// Create index on single fieldditto->store().execute( "CREATE INDEX idx_cars_color ON cars (color)", {}).then([](auto result) { std::cout << "Index created" << std::endl;});// Create compound index on multiple fieldsditto->store().execute( "CREATE INDEX idx_cars_color_year ON cars (color, year)", {});// Create index on nested fieldditto->store().execute( "CREATE INDEX idx_cars_location ON cars (_id.locationId)", {});
Best Practices:
Create indexes on fields used in WHERE clauses
Create indexes before registering observers for those queries
Use compound indexes for queries with multiple filter conditions
Monitor query performance and add indexes as needed
For comprehensive information on indexing strategies, syntax, and best practices, see the DQL Indexing documentation.
Use :paramName for parameters, not string literals or concatenation.
// ❌ Wrong: String concatenationstd::string color = "red";ditto->store().execute("SELECT * FROM cars WHERE color = '" + color + "'", {});// ✅ Correct: Using :paramName with std::map<std::string, CborValue>std::map<std::string, CborValue> args = {{"color", "red"}};ditto->store().execute("SELECT * FROM cars WHERE color = :color", args);
Use COUNTER annotation in collection definitions. Do NOT use SET with COUNTER fields. Use APPLY with PN_INCREMENT BY. Pass negative values for decrements.
// ❌ Wrong: Initializing counter with a number (creates REGISTER, not COUNTER)std::map<std::string, CborValue> doc = { {"_id", id}, {"counter", 0}};ditto->store().execute( "INSERT INTO items DOCUMENTS (:doc)", {{"doc", doc}});// ❌ Wrong: Using SET on counter fieldstd::map<std::string, CborValue> args = {{"id", id}};ditto->store().execute( "UPDATE items SET counter = 5 WHERE _id = :id", args);// ✅ Correct: Use PN_INCREMENT BY with APPLY clause (creates counter on first use)std::map<std::string, CborValue> args = {{"value", 1}, {"id", id}};ditto->store().execute( "UPDATE COLLECTION items (counter COUNTER) APPLY counter PN_INCREMENT BY :value WHERE _id = :id", args);// ✅ Correct: Decrement by passing negative valuestd::map<std::string, CborValue> args = {{"value", -1}, {"id", id}};ditto->store().execute( "UPDATE items APPLY counter PN_INCREMENT BY :value WHERE _id = :id", args);