Setup and verification
GCC with C++20, CMake 3.25 or later, CTest and Python 3. Qt 6.8 with Core, Widgets and Test. Qt SQL with the QSQLITE plugin is also required. Set CMAKE_PREFIX_PATH to your Qt installation if it is not discovered automatically. Locally checked with Qt 6.8.3. Extract the ZIP into a new folder. python3 run_checks.py checks example and solution in a temporary copy and preserves your files. Run python3 verify.py for your own build. The demo is then available at build/order_lab. Qt demos use English labels. Automated widget tests default to offscreen. Run the visible demo in a desktop session without QT_QPA_PLATFORM=offscreen. Native Windows execution is not verified.
Verified on 2026-10-21 on Linux x86_64. Real SQLite files, reopening, bound parameters, constraints, a trigger failure after the first INSERT and complete rollback. The exercise checks an atomic status change. No power-loss or multi-process conflict test.
An import consists of several SQL statements. Without a transaction it may leave an erased list or only part of the replacement. The SQLite repository wraps the replacement in one transaction. A test deliberately creates a database error on the second insert. Exactly the previously stored orders must remain readable afterward.
Package contents and individual files
01Provide Qt SQL and its SQLite driver
Install Qt 6.8 including the QSQLITE plugin. CMake links Qt6::Sql. A missing driver or an unopenable file returns an error rather than silently falling back to memory. python3 verify.py checks real SQLite files in temporary directories.
cmake_minimum_required(VERSION 3.25)
project(cpp_21 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
enable_testing()
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
add_compile_options(-Wall -Wextra -Wpedantic -Werror)
endif()
find_package(Qt6 6.8 REQUIRED COMPONENTS Core Test Widgets Sql)
set(CMAKE_AUTOMOC ON)
add_executable(order_lab main.cpp)
target_link_libraries(order_lab PRIVATE Qt6::Core Qt6::Test Qt6::Widgets Qt6::Sql)
add_executable(lesson_tests tests.cpp)
target_link_libraries(lesson_tests PRIVATE Qt6::Core Qt6::Test Qt6::Widgets Qt6::Sql)
add_test(NAME lesson_tests COMMAND lesson_tests)
set_tests_properties(lesson_tests PROPERTIES TIMEOUT 30)
add_executable(exercise_solution solution.cpp)
target_link_libraries(exercise_solution PRIVATE Qt6::Core Qt6::Test Qt6::Widgets Qt6::Sql)
add_test(NAME exercise_solution COMMAND exercise_solution)
set_tests_properties(exercise_solution PROPERTIES TIMEOUT 30)
Tests open real database files without an external database server.
02Implement the existing contract
OrderService remains unchanged. SqliteRepository must implement list and replaceAll. Loaded data is also domain-validated. This remains an example with one writing process. Global conflict resolution among multiple running instances is not part of this contract.
#pragma once
#include "order.hpp"
namespace orders {
class OrderRepository {
public:
virtual ~OrderRepository() = default;
virtual Result<std::vector<Order>> list() const = 0;
// Contract: failure leaves the previously committed batch intact.
virtual Result<Done> replaceAll(std::span<const Order> batch) = 0;
};
class MemoryRepository final : public OrderRepository {
std::vector<Order> data_;
public:
Result<std::vector<Order>> list() const override { return data_; }
Result<Done> replaceAll(std::span<const Order> batch) override {
return replaceValidated(data_, batch);
}
};
class OrderService {
OrderRepository &repository_;
public:
explicit OrderService(OrderRepository &repository)
: repository_(repository) {}
Result<std::vector<Order>> list() const { return repository_.list(); }
Result<Done> replace(std::span<const Order> batch) {
auto result = validateBatch(batch);
if (!succeeded(result))
return std::get<Error>(result);
return repository_.replaceAll(batch);
}
Result<Done> save(const Order &order) {
auto result = repository_.list();
if (!succeeded(result))
return std::get<Error>(result);
auto batch = std::get<std::vector<Order>>(std::move(result));
auto found = std::ranges::find(batch, order.id, &Order::id);
if (found == batch.end())
batch.push_back(order);
else
*found = order;
return replace(batch);
}
Result<Done> remove(int id) {
auto result = repository_.list();
if (!succeeded(result))
return std::get<Error>(result);
auto batch = std::get<std::vector<Order>>(std::move(result));
std::erase_if(batch, [id](const Order &order) { return order.id == id; });
return replace(batch);
}
};
} // namespace orders
The service needs no SQLite-specific methods.
03Bound transactions and resources
Each instance gets a unique Qt connection name. Queries and database handles are released before removing the connection. replaceAll validates input, begins a transaction, deletes the old batch and inserts all replacements using bound parameters. An RAII guard rolls back on every early exit.
#pragma once
#include "repository.hpp"
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QUuid>
#include <QVariant>
namespace orders {
class SqliteRepository final : public OrderRepository {
QString name_ = QUuid::createUuid().toString();
QSqlDatabase database_;
std::string startupError_;
Error failure(const QSqlQuery &query) const {
return {ErrorCode::storage, query.lastError().text().toStdString()};
}
public:
explicit SqliteRepository(const QString &path)
: database_(QSqlDatabase::addDatabase("QSQLITE", name_)) {
database_.setDatabaseName(path);
if (!database_.open()) {
startupError_ = database_.lastError().text().toStdString();
return;
}
QSqlQuery query(database_);
if (!query.exec(
"CREATE TABLE IF NOT EXISTS orders (id INTEGER PRIMARY KEY "
"CHECK(id BETWEEN 1 AND 1000000), title TEXT NOT NULL "
"CHECK(length(CAST(title AS BLOB)) BETWEEN 1 AND 80), priority "
"INTEGER NOT NULL CHECK(priority BETWEEN 0 AND 2), status TEXT NOT "
"NULL CHECK(status IN ('open', 'done')))"))
startupError_ = query.lastError().text().toStdString();
}
SqliteRepository(const SqliteRepository &) = delete;
SqliteRepository &operator=(const SqliteRepository &) = delete;
~SqliteRepository() override {
database_.close();
database_ = QSqlDatabase();
QSqlDatabase::removeDatabase(name_);
}
Result<std::vector<Order>> list() const override {
if (!startupError_.empty())
return Error{ErrorCode::storage, startupError_};
QSqlQuery query(database_);
if (!query.exec("SELECT id,title,priority,status FROM orders ORDER BY id"))
return failure(query);
std::vector<Order> batch;
while (query.next()) {
const auto status = query.value(3).toString();
if (status != "open" && status != "done")
return Error{ErrorCode::invalid, "Unknown stored status"};
batch.push_back({query.value(0).toInt(),
query.value(1).toString().toStdString(),
query.value(2).toInt(),
status == "open" ? Status::open : Status::done});
}
if (query.lastError().isValid())
return failure(query);
auto valid = validateBatch(batch);
if (!succeeded(valid))
return std::get<Error>(valid);
return batch;
}
Result<Done> replaceAll(std::span<const Order> batch) override {
auto valid = validateBatch(batch);
if (!succeeded(valid))
return std::get<Error>(valid);
if (!startupError_.empty())
return Error{ErrorCode::storage, startupError_};
if (!database_.transaction())
return Error{ErrorCode::storage,
database_.lastError().text().toStdString()};
struct Rollback {
QSqlDatabase &database;
bool committed{false};
~Rollback() {
if (!committed)
database.rollback();
}
} transaction{database_};
QSqlQuery query(database_);
if (!query.exec("DELETE FROM orders"))
return failure(query);
if (!query.prepare(
"INSERT INTO orders(id,title,priority,status) VALUES(?,?,?,?)"))
return failure(query);
for (const auto &order : batch) {
query.bindValue(0, order.id);
query.bindValue(1, QString::fromStdString(order.title));
query.bindValue(2, order.priority);
query.bindValue(3, order.status == Status::open ? "open" : "done");
if (!query.exec())
return failure(query);
}
if (!database_.commit())
return Error{ErrorCode::storage,
database_.lastError().text().toStdString()};
transaction.committed = true;
return Done{};
}
};
} // namespace orders
Only a successful commit disables rollback.
04Inject a real database error
The test helper opens a second short-lived connection and installs a trigger that rejects a specific ID. This allows the first new record to be inserted before the second fails. It tests more than invalid input rejected before the transaction even begins.
#pragma once
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QUuid>
inline bool execSql(const QString &path, const QString &sql) {
const auto name = QUuid::createUuid().toString();
bool success = false;
{
auto database = QSqlDatabase::addDatabase("QSQLITE", name);
database.setDatabaseName(path);
if (database.open()) {
QSqlQuery query(database);
success = query.exec(sql);
}
}
QSqlDatabase::removeDatabase(name);
return success;
}
The trigger forces an SQL failure during replacement.
05Verify reopening and rollback
The test closes a repository and opens the same file with another instance. It then triggers the injected failure and compares the entire old batch. Additional cases cover duplicate IDs, quoted titles, an explicitly empty replacement and a missing parent directory.
#include "sql_test_helper.hpp"
#include "sqlite_repository.hpp"
#include "test_support.hpp"
#include <QTemporaryDir>
#include <QtTest>
using namespace orders;
class SqlTests : public QObject {
Q_OBJECT
private slots:
void roundTripAndRollback() {
QTemporaryDir directory;
QVERIFY(directory.isValid());
auto path = directory.filePath("orders.sqlite");
{
SqliteRepository repository(path);
QVERIFY(succeeded(repository.replaceAll(samples())));
}
SqliteRepository reopened(path);
QVERIFY(std::get<std::vector<Order>>(reopened.list()) == samples());
QVERIFY(execSql(
path,
"CREATE TRIGGER reject_import BEFORE INSERT ON orders WHEN NEW.id=22 "
"BEGIN SELECT RAISE(ABORT, 'injected database failure'); END"));
std::vector<Order> incoming{{11, "First insertion"},
{22, "Rejected insertion"}};
auto failed = reopened.replaceAll(incoming);
QVERIFY(!succeeded(failed));
QCOMPARE(std::get<Error>(failed).code, ErrorCode::storage);
QVERIFY(std::get<std::vector<Order>>(reopened.list()) == samples());
incoming[1].id = 11;
QVERIFY(!succeeded(reopened.replaceAll(incoming)));
QVERIFY(std::get<std::vector<Order>>(reopened.list()) == samples());
std::vector<Order> quoted{{9, "O'Reilly \"parts\"", 2}};
QVERIFY(succeeded(reopened.replaceAll(quoted)));
QVERIFY(std::get<std::vector<Order>>(reopened.list()) == quoted);
QVERIFY(succeeded(reopened.replaceAll({})));
QVERIFY(std::get<std::vector<Order>>(reopened.list()).empty());
}
void cannotOpen() {
QTemporaryDir directory;
SqliteRepository bad(directory.filePath("missing/parent/db.sqlite"));
QVERIFY(!succeeded(bad.list()));
QVERIFY(!succeeded(bad.replaceAll(samples())));
}
};
QTEST_GUILESS_MAIN(SqlTests)
#include "tests.moc"
After the failed second INSERT every original order is preserved.
06Add a domain batch operation
finishAll loads the batch, changes statuses to done and passes the whole candidate to replace. A second trigger rejects one order's status update. The solution first verifies complete rollback and then a successful, readable persisted update.
#include "sql_test_helper.hpp"
#include "sqlite_repository.hpp"
#include "test_support.hpp"
#include <QCoreApplication>
#include <QTemporaryDir>
orders::Result<orders::Done> finishAll(orders::OrderService &service) {
auto loaded = service.list();
if (!orders::succeeded(loaded))
return std::get<orders::Error>(loaded);
auto batch = std::get<std::vector<orders::Order>>(loaded);
for (auto &order : batch)
order.status = orders::Status::done;
return service.replace(batch);
}
int main(int argc, char **argv) {
QCoreApplication application(argc, argv);
QTemporaryDir directory;
auto path = directory.filePath("orders.sqlite");
orders::SqliteRepository repository(path);
orders::OrderService service(repository);
require(orders::succeeded(service.replace(samples())), "seed");
require(execSql(path, "CREATE TRIGGER reject_done BEFORE INSERT ON orders "
"WHEN NEW.id=2 AND NEW.status='done' BEGIN SELECT "
"RAISE(ABORT, 'reject done'); END"),
"trigger installed");
require(!orders::succeeded(finishAll(service)), "failure returned");
require(std::get<std::vector<orders::Order>>(service.list()) == samples(),
"no partial completion");
require(execSql(path, "DROP TRIGGER reject_done"), "remove fault");
require(orders::succeeded(finishAll(service)), "complete all");
orders::SqliteRepository reopened(path);
const auto persisted = reopened.list();
require(orders::succeeded(persisted), "reopen succeeds");
for (const auto &order : std::get<std::vector<orders::Order>>(persisted))
require(order.status == orders::Status::done, "persisted done");
}
Either all orders are completed or the entire previous state remains.
Your exercise
Implement finishAll(OrderService&). Complete every saved order together. Simulate a failure on the second record and verify that the first also remains unchanged.
Show the solution and explanation
The solution modifies a loaded candidate and calls service.replace exactly once. The test removes its failure trigger only after proving rollback and checks the successful state through a reopened repository.
#include "sql_test_helper.hpp"
#include "sqlite_repository.hpp"
#include "test_support.hpp"
#include <QCoreApplication>
#include <QTemporaryDir>
orders::Result<orders::Done> finishAll(orders::OrderService &service) {
auto loaded = service.list();
if (!orders::succeeded(loaded))
return std::get<orders::Error>(loaded);
auto batch = std::get<std::vector<orders::Order>>(loaded);
for (auto &order : batch)
order.status = orders::Status::done;
return service.replace(batch);
}
int main(int argc, char **argv) {
QCoreApplication application(argc, argv);
QTemporaryDir directory;
auto path = directory.filePath("orders.sqlite");
orders::SqliteRepository repository(path);
orders::OrderService service(repository);
require(orders::succeeded(service.replace(samples())), "seed");
require(execSql(path, "CREATE TRIGGER reject_done BEFORE INSERT ON orders "
"WHEN NEW.id=2 AND NEW.status='done' BEGIN SELECT "
"RAISE(ABORT, 'reject done'); END"),
"trigger installed");
require(!orders::succeeded(finishAll(service)), "failure returned");
require(std::get<std::vector<orders::Order>>(service.list()) == samples(),
"no partial completion");
require(execSql(path, "DROP TRIGGER reject_done"), "remove fault");
require(orders::succeeded(finishAll(service)), "complete all");
orders::SqliteRepository reopened(path);
const auto persisted = reopened.list();
require(orders::succeeded(persisted), "reopen succeeds");
for (const auto &order : std::get<std::vector<orders::Order>>(persisted))
require(order.status == orders::Status::done, "persisted done");
}
Project context and sources
Independent teaching project using FactoryForge's logistics theme. The existing FactoryForge source revision provides architectural context. SQLite, networking and import features introduced here belong to the teaching project. Order Lab JSON is a separate format.