Recursive AI

Find SQLite foreign key violations in C#

OneLite is a free, open-source SQLite-compatible database for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

PRAGMA foreign_key_check finds rows that reference a missing parent.

Terminal
dotnet add package RecursiveAI.OneLite

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OneLite;
await using var db =
    await Database.OpenReadOnlyAsync(
        "orders.sqlite3"); // from the zip
var rows = await db.QueryAsync<Violation>(
    $"PRAGMA foreign_key_check");
foreach (var row in rows)
    Console.WriteLine(row);
 
[OneLiteRow]
record Violation(string Table, long? Rowid,
    string Parent, long Fkid);

Unzip the example, then dotnet run.

QueryAsync takes a $-prefixed string even here, where there are no values to bind. Any values in {…} become SQL parameters.

The download includes orders.sqlite3. The output identifies order 11 and the foreign key it breaks:

Text
Violation { Table = orders, Rowid = 11, Parent = customers, Fkid = 0 }

The [OneLiteRow] attribute tells OneLite to generate the mapper at build time; the record’s parameter names match the result columns without regard to case. Here’s the SQL used to make the sample file. Enforcement was disabled just to put a bad reference in it:

SQL
PRAGMA foreign_keys = OFF;
CREATE TABLE customers(id INTEGER PRIMARY KEY);
CREATE TABLE orders(
  id INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id)
);
INSERT INTO customers VALUES (1);
INSERT INTO orders VALUES (10, 1), (11, 99);

The full program

The downloaded program takes a file path. Run dotnet run -- path/to/your.sqlite to check your own file, or just dotnet run to check the sample.

C#
using RecursiveAI.OneLite;
 
var file = args.FirstOrDefault() ?? "orders.sqlite3";
await using var db =
    await Database.OpenReadOnlyAsync(file);
var violations = await db.QueryAsync<Violation>(
    $"PRAGMA foreign_key_check");
Console.WriteLine("table | rowid | parent | fkid");
foreach (var row in violations)
    Console.WriteLine($"{row.Table} | " +
        $"{row.Rowid?.ToString() ?? "NULL"} | " +
        $"{row.Parent} | {row.Fkid}");
 
[OneLiteRow]
record Violation(string Table, long? Rowid,
    string Parent, long Fkid);
Text
table | rowid | parent | fkid
orders | 11 | customers | 0

If no rows violate a foreign key, the program prints only the header. If the schema itself has a foreign key mismatch, such as a reference to a parent key that isn’t unique, the pragma can throw OneLiteException instead of listing rows.

Variations

Check one child table. Replace the QueryAsync call in the program with this. It produces the same output on the sample because orders is its only child table.

C#
var violations = await db.QueryAsync<Violation>(
    $"PRAGMA foreign_key_check(orders)");

The short answer

Open the existing database with Database.OpenReadOnlyAsync, then call QueryAsync with PRAGMA foreign_key_check. Every result identifies a violated constraint on a child row. Omit the table name to check the main database, or pass the child table’s name to check only the constraints declared on that table. The pragma reports problems but doesn’t fix them.

What do rowid and fkid mean in foreign_key_check?

SQLite’s pragma reference defines four columns: the child table with the REFERENCES clause, the offending row’s rowid, the parent table named in the clause, and the foreign key ID. rowid isn’t a line number. In this sample, orders.id is declared INTEGER PRIMARY KEY, so it’s the same value as rowid. If the child uses WITHOUT ROWID, the second column is NULL; that’s why the C# record uses long?. A child row that breaks more than one constraint can produce more than one result.

fkid identifies the constraint, not the missing customer. To see which columns it connects, run this and match the id in its result to the fkid:

SQL
PRAGMA foreign_key_list(orders);

Here, ID 0 maps orders.customer_id to customers.id. The sample row has customer_id = 99 and there’s no customer 99. If the parent table is right but the values are wrong, decide whether to restore the missing parent or correct the child using your source data. The check can’t make that choice for you.

Does SQLite enforce foreign keys automatically?

PRAGMA foreign_keys controls enforcement on a connection; PRAGMA foreign_key_check inspects the data that’s already there. They aren’t interchangeable. OneLite’s Database.OpenAsync enables enforcement by default, but a file can already have bad rows from a previous import or another application. You can inspect those rows without turning enforcement on, as this recipe does with a read-only connection.

PRAGMA integrity_check doesn’t detect foreign key violations. An ok from that check isn’t a substitute for running foreign_key_check after an import or on a database you received from another application.

All onelite recipes