Skip to content

SQL-backed graphs

A SQL-backed graph stores its definition across tables: one row identifies the graph, and associated rows describe its nodes, edges, conditions, text and terminal outputs. SqlGraphRepository reads those records as one complete definition. SqlGraphLoader then checks the definition and constructs the Graph your application gives to the engine.

This is useful when your application manages graph definitions in a database. Your application creates and updates the records; the repository provides the reading path. The source selection remains a graph code, so changing where the definition is stored does not require changing how your application starts or navigates it.

This guide reuses learning-path from Anatomy of a graph. Its root node 10 offers Read the guide through edge 101 to terminal 20, and Practise in the browser through edge 102 to terminal 30. The second choice requires practiceEnabled: true. The JSON definition also contains English and Spanish presentation data and the outputs for both terminals.

The canonical code is learning-path. SQL also needs an integer key for the graphs row; this example assigns id = 1. Every child row uses graph_id = 1 to belong to that definition. This storage key is separate from the node IDs 10, 20 and 30, and from the edge IDs 101 and 102.

Table Data stored for this example
graphs Code learning-path, root 10, default language en, and allowed languages en / es.
graph_nodes Three nodes and their terminal flags.
graph_edges Two edges, each with its origin and destination node IDs.
graph_edge_conditions The context_value condition on edge 102.
graph_node_metadata Six records: a title and associated presentation data for each node in each language.
graph_edge_labels Four records: one label for each edge in each language.
graph_terminal_outputs Five records: translated content and links for node 20, and a language-neutral redirect for node 30.
graph_webhooks, graph_node_webhooks, graph_edge_webhooks No rows in this example. The tables still belong to the complete schema.

SQL relationships for learning-path: child graph_id values refer to graphs.id, while root, node and edge references are checked within the selected graph by the loader.

The solid connections in the figure are foreign keys declared by the SQL schema. The dashed arrows represent references checked when the graph is loaded. In particular, from_node_id and to_node_id must identify nodes in the same graph. Accepting a row into the database does not by itself establish that those nodes exist.

Each child table also has sort_order. It preserves the order of its collection when the repository reconstructs the definition. Use non-negative values that are unique within that table for the graph: the four label rows use 0, 1, 2, 3, including both languages. Do not restart the label order for each edge or language. Node and edge IDs can be reused by a different graph because their identity is scoped by graph_id.

The SQL representation adds a few storage details. Node terminal flags are 0 or 1; the repository converts them to booleans. Languages, condition parameters and extras are JSON text in their respective columns. Metadata rows require an integer id; the complete SQL example supplies IDs 1 through 6 for the six translated records. The graph definition schema describes the fields and their constraints in detail.

Prepare a connection and the complete schema

Section titled “Prepare a connection and the complete schema”

The procedure below uses SQLite through PDO. It assumes an existing PHP application with ExecKernel installed and its Composer autoloader loaded. The PHP runtime needs pdo_sqlite; Installation and requirements covers the package setup.

Start with a new database file. These paths are relative to your application’s root:

$pdo = new PDO('sqlite:learning-graphs.sqlite');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('PRAGMA foreign_keys = ON');
$schema = file_get_contents(
'vendor/execkernel/execkernel/'
. 'Infrastructure/Repository/schema/sqlite.sql',
);
$pdo->exec($schema);

PDO opens or creates the SQLite database. Exception mode is required by the repository, and the pragma enables SQLite’s declared foreign-key checks. Apply the schema once when preparing a new database. For an existing application, include that schema in its database preparation or migration process.

Use the complete supplied schema, including the webhook tables that remain empty here. The repository reads every collection needed for a complete graph; creating only graphs, graph_nodes and graph_edges would leave that reading path incomplete.

The complete learning-path.sql file contains the records corresponding to the JSON definition. Its structural rows show how the graph key, collection order and graph-local IDs fit together:

INSERT INTO graphs
(id, code, root_node_id, default_lang, allowed_langs)
VALUES
(1, 'learning-path', 10, 'en', '["en","es"]');
INSERT INTO graph_nodes
(graph_id, sort_order, id, is_terminal)
VALUES
(1, 0, 10, 0),
(1, 1, 20, 1),
(1, 2, 30, 1);
INSERT INTO graph_edges
(graph_id, sort_order, id, from_node_id, to_node_id)
VALUES
(1, 0, 101, 10, 20),
(1, 1, 102, 10, 30);

For example, the last row belongs to graph 1, occupies position 1 in its edge collection, and defines edge 102 from node 10 to node 30. The condition refers to that edge ID:

INSERT INTO graph_edge_conditions
(graph_id, sort_order, edge_id, rule, params)
VALUES
(1, 0, 102, 'context_value',
'{"key":"practiceEnabled","operator":"==","value":true}');

When the repository reads params, it decodes that JSON into the parameter array used by the condition. The boolean true remains a boolean. Labels and metadata use the same association pattern through edge_id or node_id, with lang selecting the translation.

The SQL blocks above explain part of the data. Import the complete file once to include the presentation and terminal outputs as well:

$rows = file_get_contents(__DIR__ . '/learning-path.sql');
$pdo->beginTransaction();
try {
$pdo->exec($rows);
$pdo->commit();
} catch (Throwable $exception) {
$pdo->rollBack();
throw $exception;
}

Here, learning-path.sql is beside the PHP file performing the import. The transaction keeps the insertion together. Finish that write transaction before loading: the repository needs to open its own read transaction to obtain a consistent definition.

Connect the prepared PDO connection to the repository, then give that repository to the loader:

use ExecKernel\Infrastructure\Loader\SqlGraphLoader;
use ExecKernel\Infrastructure\Repository\SqlGraphRepository;
$repository = new SqlGraphRepository($pdo);
$loader = new SqlGraphLoader($repository);
$graph = $loader->load('learning-path');

The repository selects graphs.code, reads the collections for its integer key, converts stored values to the expected types, and preserves their sort_order. The loader checks the assembled definition and returns a Graph. In this example, $graph->rootNodeId is 10, nodesById contains three nodes and edgesById contains two edges.

Use the string code for normal application selection. For compatibility, load(1) selects the integer SQL key. A numeric string first selects an exact code; only if that code is absent does the SQL adapter try it as an integer ID. Using 'learning-path' makes the intended identity clear.

Your application can now give $graph to the engine exactly as it would a graph loaded from a file. The shared execution block is developed in Graph loaders and repositories. With language en and context ['practiceEnabled' => true], the complete example reports:

learning-path: root=10, nodes=3, edges=2
How would you like to learn?
101: Read the guide [available]
102: Practise in the browser [available]

The first line summarizes the reconstructed definition. The next lines come from the engine’s initial payload: the title, labels and availability that your application can present.

The complete load-learning-path-sqlite.php program contains the connection, schema preparation, import, loading and engine call explained here. Keep it beside learning-path.sql and run it from your application’s root, using a new database filename:

Terminal window
php examples/load-learning-path-sqlite.php learning-graphs.sqlite en

In this command, examples/ is the directory where you placed the two downloads. The program refuses to overwrite an existing database file. After the initial preparation, ordinary application requests only need the connection and loading code; they do not recreate the schema or reinsert the definition.

Inspect validation and repair a broken reference

Section titled “Inspect validation and repair a broken reference”

A successful SqlGraphLoader::load() has already checked the definition. If your application needs the validation warnings as data, use the repository and keep the intermediate array loader explicitly:

use ExecKernel\Infrastructure\Loader\ArrayGraphLoader;
$definition = $repository->fetch('learning-path');
$inspectionLoader = new ArrayGraphLoader($definition);
$graph = $inspectionLoader->load('learning-path');
$warnings = $inspectionLoader->validationResult()->toArray();

This is an alternative loading path for inspecting the result; it performs the same array-based construction used by SqlGraphLoader. For the complete example, $warnings is []. The warnings become available after a successful load; a structural error interrupts loading with an exception.

Consider an imported row that mistakenly points edge 102 at node 999:

UPDATE graph_edges
SET to_node_id = 999
WHERE graph_id = 1 AND id = 102;

The database can accept this change because the schema’s foreign key checks graph_id, while the endpoint reference is checked by the loader. The next load('learning-path') raises InvalidGraphStructureException with ekCode = EK-SEC-LOD-001. Its context identifies the bad reference:

{
"edge_id": 102,
"from": 10,
"to": 999,
"validation_ek_code": "EK-GRAPH-010"
}

This tells your application which edge failed and which endpoint needs checking. In the example, node 30 is the intended destination, so the repair is:

UPDATE graph_edges
SET to_node_id = 30
WHERE graph_id = 1 AND id = 102;

Loading succeeds again after that correction. Keeping graph_id = 1 in the update matters: another graph can also have an edge numbered 102.

Other failures point to different preparation problems:

Symptom or diagnostic What to check
Graph not found The selected code must exist exactly in graphs.code.
reason: sql_graph_read_failed Check the complete schema, connection access and SQL state reported by the exception.
Invalid JSON, with a field such as condition.params Store the JSON structure expected by that column; for example, params must decode to a PHP array containing the condition parameters, not null.
Duplicate or invalid sort_order Use distinct non-negative positions for that graph within each child table.
reason: graph_snapshot_requires_own_transaction Finish the application’s transaction before fetching the definition, or use a separate connection for graph reads.
reason: graph_repository_requires_pdo_exception_mode Configure PDO::ATTR_ERRMODE as PDO::ERRMODE_EXCEPTION.

For validation beyond these SQL-specific cases, continue with Graph validation and diagnostics.

The repository supports PDO’s sqlite and mysql drivers. For MySQL, prepare the connection and apply Infrastructure/Repository/schema/mysql.sql from the package instead of the SQLite schema. Its tables use InnoDB, and the graph code uses binary comparison to preserve exact identity.

The repository opens a read-only transaction at REPEATABLE READ isolation for its MySQL read, so it can assemble the definition consistently across the tables. It requires the same exception mode and ownership of its transaction. The SQLite pragma and connection string above belong to the SQLite path; the code that constructs SqlGraphRepository, SqlGraphLoader and selects the graph remains the same.

These tables store graph definitions. They do not retain a person’s current node, context or history; choose a separate session store and persistence mode when your application needs to resume executions.