GeoPackage Foreign Keys: Check References Alongside Database Integrity
Run separate read-only SQLite integrity and foreign-key checks on an identified GeoPackage release, preserving each finding without claiming full spatial conformance.

Identify the released database and review question
A GeoPackage can open in a GIS and still require a more explicit review of its internal references. Likewise, a database integrity report that says ok does not answer every relational question. Before accepting a NiVO mapping handoff, identify the consistently released database copy and the checks actually performed. This tutorial separates SQLite integrity checking from declared foreign-key checking. It does not inspect a customer GeoPackage, repair database contents or establish the behavior of a particular NiVO application. Preserve the accepted release and any required companions before interpreting results from a separate working copy.
Record the file revision, producing application, relevant library versions and intended receiving workflow. Confirm that the copy represents the intended committed state, particularly when the producer used an active database or write-ahead logging. A review of an incomplete or different release cannot resolve a discrepancy in the accepted source. Keep the source identity with every report. Ask whether the task concerns container structure, declared table relationships, GeoPackage requirements or suitability for an analytical use. These are related questions, but a successful check at one level should not silently become a claim that all the others were assessed.
Read the two check results in their own scope
SQLite explicitly documents that PRAGMA integrity_check does not find foreign-key errors. Its separate PRAGMA foreign_key_check reports violations of declared foreign-key constraints. The approved OGC GeoPackage 1.4.0 document also lists distinct file-integrity requirements: an ok integrity result and an empty foreign-key-check result without a table parameter. This provides a concrete reason to retain both outputs rather than describing a single successful pragma as complete package validation. Use the applicable GeoPackage version and actual database context for a real review, and preserve any unsupported-build or execution limitation.
A foreign-key check concerns relationships declared in the schema. It does not infer every business relationship that a project intends, and an empty result cannot prove that a missing required declaration was present or correct. GeoPackage schema, metadata and spatial requirements still need their own appropriate checks. The distinction matters when a package contains user tables or extensions with additional rules. Keep those rules and the intended feature population available rather than assuming that every important link will automatically appear in a generic SQLite report. A relational check is useful evidence within its declared scope, not a substitute for the complete delivery specification.

Product context only; this photograph does not depict the constructed examples in this article.
Capture read-only results without changing enforcement
The Python recipe below opens an identified filename through a read-only SQLite URI, records the library version and current foreign-key enforcement state, and returns both check outputs. It does not enable enforcement, write tables or repair references. Confirm that the installed SQLite build supports the requested pragmas before using the method on a real release; SQLite notes that unknown pragma names can be ignored. The example is an inspection aid, not a universal conformance tool. Retain actual exceptions and diagnostics instead of converting an unreadable database or unsupported operation into an empty result set that appears to pass.
The code closes its connection explicitly and preserves each foreign-key result column, including a null child row identifier when SQLite reports one. Run it only on a suitable identified copy, retaining the report outside the received package. No real GeoPackage execution is claimed here. The recipe checks used during preparation operate on small constructed SQLite databases in the private workspace, not complete conformant GeoPackages. They demonstrate the difference between the two query scopes and the read-only opening behavior. They do not exercise geometry decoding, extension support, spatial reference correctness or actual survey content.
import json, pathlib, sqlite3, sys
def inspect_database(filename):
uri = pathlib.Path(filename).resolve().as_uri() + "?mode=ro"
connection = sqlite3.connect(uri, uri=True)
try:
enforcement = connection.execute("PRAGMA foreign_keys").fetchone()
if enforcement is None:
raise RuntimeError("foreign-key support not reported by this build")
integrity = [row[0] for row in connection.execute("PRAGMA integrity_check")]
violations = [dict(zip(("childTable", "childRowid", "parentTable", "constraintIndex"), row))
for row in connection.execute("PRAGMA foreign_key_check")]
return {"sqliteVersion": sqlite3.sqlite_version,
"foreignKeyEnforcement": enforcement[0],
"integrityRows": integrity, "foreignKeyRows": violations}
finally:
connection.close()
if __name__ == "__main__":
print(json.dumps(inspect_database(sys.argv[1]), indent=2))Trace a constructed broken reference without calling it corruption
Imagine a minimal teaching database with a parent table of accepted item identifiers and a child table that declares a reference to it. One child row refers to an identifier absent from the parent. In the constructed fixture, integrity_check returns ok while foreign_key_check returns the broken-reference finding. This demonstrates the documented difference; it is not a result from a NiVO inventory or proof of a real delivery defect. The toy tables do not constitute a GeoPackage. Keep the fixture purpose distinct from an actual package review so a simple database example is not presented as spatial conformance evidence.
SQLite describes each foreign-key finding using the child table, child rowid, parent table and constraint index. For a WITHOUT ROWID child table, the rowid field can be null; preserve that representation rather than replacing it with zero or dropping the finding. Use the relevant schema and suitable identification queries during a real investigation. A report entry points to a declared relationship requiring review, but does not authorize deleting the child record or fabricating the missing parent. The responsible producer must establish the accepted content and correction, with the original release retained as evidence.
Distinguish enforcement settings from existing-data evidence
The foreign_keys pragma reports or controls enforcement for a connection. SQLite documents runtime and build conditions for that support, and advises applications not to assume the default setting. The inspection recipe records the observed state without changing it. Enabling a setting is a different operation from producing a report about the existing database contents. Do not treat a visible enforcement flag as a replacement for the actual check results, and do not infer that the recorded state of this read-only connection proves how every earlier editing application handled constraints when the delivered rows were created.
If a finding requires correction, obtain the producer explanation and create a separately identified candidate through an appropriate supported workflow. Preserve the original release, document the intended change and repeat the relevant database, GeoPackage and receiving checks on the candidate. Avoid silently repairing metadata or removing rows merely to obtain a clean report. A package with consistent declared references can still contain the wrong observations, an incorrect spatial reference or missing required content. Keep those acceptance questions visible and retain the project evidence needed to assess them rather than allowing a tidy relational result to stand in for analytical validation.
Deliver separate structural, relational and spatial findings
A reproducible handoff names the database revision, SQLite build, observed enforcement state, raw integrity rows and foreign-key findings, together with the review scope and any errors. State whether the inspection covered only these two queries or also included the applicable GeoPackage conformance and receiving requirements. Another analyst should be able to reproduce the reports on the same released copy without modifying it. Keep unresolved relationships and producer decisions with the evidence. An empty foreign-key result or an ok integrity string should not be described as a completed spatial acceptance test.
For NiVO geospatial deliveries, this adds a practical distinction to the review record: database structure and declared references each have a report, while spatial and project requirements retain their own evidence. It complements WAL-release and RTree-query reviews while addressing a separate integrity question. The product photograph provides context only and does not depict the constructed database or demonstrate an export capability. Preserve those scopes throughout the handoff so the recipient can understand what was actually checked, which issues remain and what additional review is required before the database supports its intended analytical use.



