SQLite serializer#

The SQLite store, which the SQLite serializer (ClashDataSerializerSqlite in Python) reads and writes, is the default store of the Suite API. It keeps every query, point-cloud setting, clash and frame of a store in one SQLite database file, by convention with the .ovclashdb extension. It also opens the .clashDetection legacy container of the clash detection extension of Kit. Its schema follows the SQLite serializer of that extension: the same tables, schema versions per table and value encodings.

Choosing a store compares it with the directory store. Persistence covers the data API that both share: records, transactions, fetch-and-save and clash states.

Store path#

The path names one database file:

  • Any file name works. The serializer adds no extension. .ovclashdb (ClashDataSerializerSqlite.SERIALIZED_FILE_EXT) is the convention.

  • A relative path resolves against the current working directory.

  • Paths are UTF-8 on every platform. A path with an embedded NUL character is rejected before the current store is touched.

  • An existing directory at the path fails the open at once. With deferred creation on, the default, the error is SQLite clash data path is a directory: <path>. With it off, SQLite’s open error reports it: Failed to open SQLite database '<path>': ....

  • A missing file is created at the first write, the default, or at open when deferred creation is off; see Deferred creation and unnamed stores. The parent directory must exist.

  • A path that ends in .clashDetection, in any letter case, must name an existing legacy container. A missing one fails the open (Legacy .clashDetection file does not exist: <path>), and a later write does not create it. A file with a valid legacy header opens as a container under any name; see Legacy containers.

  • open("") opens an unnamed store: a private temporary database that SQLite deletes when the store closes, unless save_as(path) names it first.

SQLite can keep sidecar files beside the database while it works: <file>-journal, and <file>-wal and <file>-shm for a database in WAL (write-ahead logging) mode. Keep them with the database. To copy a store that is open, use save_as(), which reads through SQLite and includes committed WAL rows and pending writes.

Python#

This script creates run_01.ovclashdb in the current directory, or opens it when it exists:

from ovclash_suite import ClashData, ClashQuery

data = ClashData()  # creates and owns a ClashDataSerializerSqlite
try:
    data.open("run_01.ovclashdb")
    query = ClashQuery(query_name="Pipe clearances", object_a_path="/World/Pipes",
                       object_b_path="/World/Structure")
    data.insert_query(query)
    for identifier, stored in data.fetch_all_queries().items():
        print(identifier, stored.query_name)
finally:
    data.destroy()

Output on a new store:

1 Pipe clearances
  • ClashData() creates the serializer, and ClashData.destroy() destroys it. To keep your own reference, create a ClashDataSerializerSqlite, pass it to ClashData(serializer) and destroy it yourself.

  • open() raises RuntimeError when the file cannot be opened. An incompatible schema is the exception: it leaves the store closed without raising; see Schema versions and forward compatibility.

  • Each write commits by default.

To save runtime results, pass data, or the serializer itself, as clash_data to ClashDetection.fetch_and_save_overlaps() or ClashDetection.run_async_fetch_and_save(). Fetching Suite runtime results describes both, and Saving detection results gives the transaction rules.

C and C++#

Create the handle with ovclash_suite_data_create(). Every ovclash_suite_data_* function, the cursors and the fetch-and-save calls accept it. Check each returned status against OVCLASH_SUITE_STATUS_SUCCESS. This function belongs in a C source file of your program; it opens the same store and prints its query count:

#include <stdio.h>

#include <ovclash_suite/ovclash_suite.h>

static ovclash_suite_result_t print_query_count(void)
{
    ovclash_suite_data_t* data = NULL;
    ovclash_suite_result_t result = ovclash_suite_data_create(&data);
    if (result.status == OVCLASH_SUITE_STATUS_SUCCESS)
    {
        const char path[] = "run_01.ovclashdb";
        const ovclash_suite_string_t store = { path, sizeof(path) - 1 };
        uint32_t count = 0u;
        result = ovclash_suite_data_open(data, store);
        if (result.status == OVCLASH_SUITE_STATUS_SUCCESS)
            result = ovclash_suite_data_get_query_count(data, &count); /* any data API call */
        if (result.status == OVCLASH_SUITE_STATUS_SUCCESS)
            printf("%u queries\n", count);
        ovclash_suite_result_t cleanup = ovclash_suite_data_destroy(data);
        if (cleanup.status != OVCLASH_SUITE_STATUS_SUCCESS)
            result = cleanup;
    }
    return result;
}
  • In C, an incompatible schema fails ovclash_suite_data_open(). The handle stays not open and keeps its compatibility and migration-possible flags for an explicit migration.

  • To save runtime results, pass the handle as data, with a NULL serializer, to ovclash_suite_runtime_fetch_and_save_async() or to the bounded ovclash_suite_runtime_fetch_and_save_begin(). The operation leases the store until you destroy it; see Saving detection results.

  • The data API comments in <ovclash_suite/ovclash_suite.h>, a header of the SDK archive, hold the full contract.

Sample command line#

The Clash Processor, the C++ and Python programs in samples/clash_suite_api/ that The Clash Processor introduces, runs one query from the command line and stores its results. These options select the stores and exports:

Option

Value

Default

Effect

--clashdb FILE

A file path; .clashDetection is reserved for legacy containers

None

Writes a SQLite store.

--clashdir FOLDER

A directory path

None

Writes a directory store, alone or together with --clashdb.

--json PATH

A file path

None

Exports a JSON report. Without --clashdb and --clashdir, it also writes a SQLite store beside it: report.json gives report.ovclashdb.

--html PATH

A file path

None

Exports an HTML report, with the same SQLite store rule as --json.

--append

None

Off

Appends to every requested store instead of replacing its records.

Before you begin: use the wheel or the SDK archive, whose samples sit under the package root. On Linux, from the package root:

./samples/clash_suite_api/run_clash_suite_api_python.sh -- --stage samples/data/time_sampled.usda --object-a /Root/Xform_Primitives/Cube --object-b /Root/Xform_Primitives/Plane --clashdb results.ovclashdb --json report.json

On Windows, from the package root, run samples\clash_suite_api\run_clash_suite_api_python.bat with the same arguments. The run writes results.ovclashdb and report.json in the current directory. When the launcher first prepares its Python environment, it can install the pinned ovstage runtime with pip; when that fails, see Sample Python setup failed.

Name the file .ovclashdb; the processor reserves .clashDetection for legacy containers. The Clash Processor guide, samples/clash_suite_api/clash_processor.md in the package, covers combined SQLite and directory output and the other options. Samples describes the launchers.

Tables#

A store has five tables:

Table

Holds

Linked by

clash_query

One row per ClashQuery

–

clash_info

One row per ClashInfo

query_id names its query

clash_frame_info

One row per ClashFrameInfo

clash_info_id names its clash

point_cloud_settings

One row per PointCloudSettings

–

version_info

The schema version of each of the four record tables

table_name

  • Each record’s identifier is its id column, assigned by SQLite when the insert generates one.

  • Deleting a query also deletes its clashes, and deleting a clash deletes its frames.

  • Reads return clashes in (overlap_id, id) order and frames in (timecode, id) order.

Columns#

Each column holds the field of the same name in the Python class, unless the table names another; The object model describes the fields. Every id column is an INTEGER PRIMARY KEY AUTOINCREMENT. SQLite does not enforce the length of a VARCHAR.

clash_query:

Column

Declared type

Constraint

Holds

id

INTEGER

Primary key

identifier

query_name

VARCHAR(1024)

None

query_name

object_a_path, object_b_path

TEXT

None

The scope text of sets A and B

clash_detect_settings

TEXT

None

The settings as JSON text

creation_timestamp, last_modified_timestamp

TIMESTAMP

None

The timestamps as text

last_modified_by

VARCHAR(255)

None

last_modified_by

comment, roi_include_path, roi_exclude_path

TEXT

None

The fields of the same names

clash_info:

Column

Declared type

Constraint

Holds

id

INTEGER

Primary key

identifier

query_id

INTEGER

References clash_query(id)

query_id

overlap_id

VARCHAR(40)

NOT NULL

The clash hash as text

overlap_type, num_records, overlap_elements, state, priority

INTEGER

None

The fields of the same names

present

INTEGER(1)

None

present, 0 or 1

min_distance, max_local_depth, depth_epsilon, tolerance

REAL

None

The fields of the same names

object_a_path, object_b_path

VARCHAR(2048)

NOT NULL

The prim paths

object_a_mesh_crc, object_b_mesh_crc

VARCHAR(40)

NOT NULL

The mesh hashes as text

start_timecode, end_timecode

REAL

None

start_time and end_time, in seconds

person_in_charge, last_modified_by

VARCHAR(255)

None

The fields of the same names

creation_timestamp, last_modified_timestamp

TIMESTAMP

None

The timestamps as text

comment

TEXT

None

comment

penetration_depth_px, penetration_depth_nx, penetration_depth_py, penetration_depth_ny, penetration_depth_pz, penetration_depth_nz

REAL

None

The per-axis penetration depths

clash_frame_info:

Column

Declared type

Constraint

Holds

id

INTEGER

Primary key

The frame’s record identifier

clash_info_id

INTEGER

References clash_info(id)

The identifier of the owning clash

timecode, min_distance, max_local_depth

REAL

None

The fields of the same names; timecode is in seconds

overlap_elements

INTEGER

None

overlap_elements

usd_faces_0, usd_faces_1, usd_points_0

BLOB

None

uint32 index buffers

collision_outline, usd_points_0_sizes

BLOB

None

float32 buffers

object_0_matrix, object_1_matrix

TEXT

None

The matrices as JSON text; see Values

penetration_depth_px, penetration_depth_nx, penetration_depth_py, penetration_depth_ny, penetration_depth_pz, penetration_depth_nz

REAL

None

The per-axis penetration depths

point_cloud_settings:

Column

Declared type

Constraint

Holds

id

INTEGER

Primary key

identifier

point_cloud_prim_path, destination_path

TEXT

None

The fields of the same names

save_to_session_layer, skip_rendering

INTEGER(1)

None

The flags, 0 or 1

max_lod_level

INTEGER

DEFAULT 1000000

max_lod_level

version_info:

Column

Declared type

Constraint

Holds

id

INTEGER

Primary key

A row identifier

table_name

VARCHAR(128)

None

The name of a record table

version

INTEGER

None

That table’s schema version

Values#

Column type

Columns

Rules

INTEGER

Identifiers, counts, overlap_type, state, priority and the boolean flags

64-bit integers. Flags hold 0 or 1.

REAL

Distances, depths, tolerances, times and the penetration_depth_* values

Binary64. NaN is rejected on write, infinities are stored, and a negative zero reads back as a positive zero.

TEXT

Paths, names, hashes, comments, timestamps, the query settings and the two frame matrices

UTF-8

BLOB

usd_faces_0, usd_faces_1, collision_outline, usd_points_0 and usd_points_0_sizes

The elements’ raw bytes, read back bit for bit

  • NaN in a REAL column fails the write. The store does not write NULL and read it back as zero. The failure rolls back the handle’s whole pending transaction, as any write that fails after it began does (CRUD). A directory store accepts NaN, so a record that holds one cannot be copied unchanged into a SQLite store.

  • Matrices are JSON text. object_0_matrix and object_1_matrix each hold one row-major 4x4 local-to-world transform:

    Part

    JSON type

    Rule

    Matrix

    Array of exactly 4 rows

    The rows, top to bottom.

    Row

    Array of exactly 4 numbers

    Finite numbers, written with 17 significant digits in the classic C numeric locale, so they read back exactly.

  • Query settings hold the JSON text of ClashQuery.clash_detect_settings.

  • Timestamps are local times in the text form YYYY-MM-DD HH:MM:SS.ffffff.

  • Oversized values are rejected. A text or BLOB value too large for SQLite’s 32-bit bind sizes fails the write instead of being truncated.

Numeric fidelity compares these rules with the directory store.

Reads#

SQLite reads validate stored data strictly, and a malformed row fails the read instead of being skipped:

  • A matrix must be an exact 4x4 JSON array of finite numbers.

  • Each BLOB column must hold whole elements.

  • Stored text with an embedded NUL character, or text that is not UTF-8, fails the read. The error names the column.

  • In Python, a malformed row raises RuntimeError, and an invalid stored timestamp raises ValueError.

Read records sequentially through a cursor. An indexed getter can skip the preceding rows on every call:

  • ovclash_suite_data_get_frame_by_overlap_at() always skips them, so reading a long dynamic clash one index at a time is quadratic in its frame count.

  • ovclash_suite_data_get_query_at(), ovclash_suite_data_get_point_cloud_settings_at() and ovclash_suite_data_get_overlap_by_query_at() seek past the previous row instead when you read consecutive indexes from index 1024 on, while no cursor is open on the handle and nothing has written to the database in between, through this handle or through another connection. Any other call skips the preceding rows.

  • ovclash_suite_data_get_frames_by_overlap() and ovclash_suite_data_get_overlaps_by_query() open one forward-only cursor, and stepping it reads each row once. The Python read methods use these cursors.

Schema versions and forward compatibility#

A SQLite store records each table’s schema version in its version_info table. Open compares them with the versions this build supports:

Table

Version

Python constant

Oldest version that migrates

clash_query

5

ClashQuery.VERSION

3

clash_info

18

ClashInfo.VERSION

15

clash_frame_info

7

ClashFrameInfo.VERSION

5

point_cloud_settings

2

PointCloudSettings.VERSION

A store without the table

Check the versions and an open store from Python. Before you begin: run the dynamic case of Suite Workflows, which writes dynamic.ovclashdb into its working directory. Then run this script from that directory, with the Python that has ovclash installed:

from ovclash_suite import ClashData, ClashFrameInfo, ClashInfo, ClashQuery, PointCloudSettings

for record in (ClashQuery, ClashInfo, ClashFrameInfo, PointCloudSettings):
    print(f"{record.__name__}.VERSION = {record.VERSION}")

data = ClashData()
try:
    data.open("dynamic.ovclashdb")
    print(f"open={data.is_open()} compatible={data.data_structures_compatible}")
finally:
    data.destroy()

Expected output:

ClashQuery.VERSION = 5
ClashInfo.VERSION = 18
ClashFrameInfo.VERSION = 7
PointCloudSettings.VERSION = 2
open=True compatible=True

In C, read the versions with ovclash_suite_get_named_constant() and the names OVCLASH_SUITE_CLASH_QUERY_VERSION, OVCLASH_SUITE_CLASH_INFO_VERSION, OVCLASH_SUITE_CLASH_FRAME_INFO_VERSION and OVCLASH_SUITE_POINT_CLOUD_SETTINGS_VERSION. They are not ovclash release numbers and do not follow the package version. Releases that keep the same schema versions read and write the same files.

Compatibility is forward-only:

File’s schema versions

Behavior

Same as this build

Opens.

None recorded (a new database)

Opens and records the current versions.

Older, with a registered migration chain

open() fails with “SQLite database tables are incompatible; migration to the latest version is possible”. Compatibility reports incompatible and migration-possible reports true. Migrate first.

Older, with no registered chain

Incompatible: “SQLite database tables are incompatible and cannot be migrated to the latest version”. The API cannot recover it.

Newer than this build

Always incompatible: a clean refusal, never a misread. There is no downgrade path.

In Python, an incompatible database leaves open() closed without raising. It logs the reason as a warning through the ovclash_suite logger, and last_error() returns it; see Failures that do not raise. In C, ovclash_suite_data_open() fails.

Purpose

Python

C

Is the open store’s schema current?

ClashData.data_structures_compatible

ovclash_suite_data_structures_compatible

Could it be migrated?

ClashData.data_structures_migration_to_latest_version_possible

ovclash_suite_data_migration_to_latest_possible

Migrate it

migrate_data_structures_to_latest_version(path)

ovclash_suite_data_migrate_to_latest

On a ClashDataSerializerSqlite, data_structures_compatible() and data_structures_migration_to_latest_version_possible() are methods. On ClashData they are properties of the same names.

Migration#

  • Migration works in place. The path names the store to migrate, not an output, and migration never creates a missing file.

  • In C, an empty path migrates the handle’s current store. An unnamed store has no path, so an empty path fails with No clash data file path supplied for migration and leaves the store unchanged.

  • In Python, an empty path uses the cached path. After open() of a .clashDetection container, that path names the container until a save() or save_as() succeeds, and migrating it extracts the container again and discards writes made to the earlier copy; see Legacy Containers.

  • All tables migrate in one transaction, one version step at a time, so a failed step leaves the file unchanged. On success the migrated store is open.

  • To put a migrated store somewhere new, migrate it and then call save_as().

  • Migration rejects a path that is missing, unreadable or not writable before it touches the current store. The handle keeps its path, open state and pending writes.

  • Other migration failures, such as a corrupt or locked file, are found after the current store closes. The handle is then left not open.

  • In Python, migrate_data_structures_to_latest_version() returns False instead of raising, and last_error() gives the reason.

  • A legacy .clashDetection container is only read. Its payload is extracted to a temporary database, and that copy is migrated, so a read-only container migrates too. See Legacy Containers for the rules that keep the copy’s writes.

Legacy containers#

A .clashDetection file is a 16-byte header followed by an ordinary SQLite database, possibly with an older schema. The SQLite serializer reads and writes it through the same handle:

  • Open copies the payload to a private temporary .ovclashdb and opens that copy. The container itself is never changed by writes or commits.

  • save_as(target) with a target that ends in .clashDetection exports a new container and keeps the current store. Any other target receives a plain .ovclashdb and becomes the current store.

  • Close and destroy delete the temporary copy.

  • probe_legacy_clash_detection_file() (C ovclash_suite_probe_legacy_clash_detection_file()) checks the header without opening the SQLite database.

Legacy Containers covers probing, migrating and moving the data to a plain .ovclashdb, and gives the container format.

Commits and ownership#

The commit arguments and commit() work as CRUD describes:

  • The first pending write starts a SQLite BEGIN IMMEDIATE transaction. Pending writes are visible through the owning handle and reach other connections at commit.

  • A write that fails after it began, for example on a NaN REAL value, rolls back every pending write.

  • Closing or destroying the store first attempts to commit pending writes. A failed commit requests a rollback and keeps the handle for inspection or retry.

Saving:

  • save() without a target commits. On a named store it then runs VACUUM when free pages exceed a tenth of the file, which can take a moment on a large store.

  • save_as(path) commits, then copies the database to path through the SQLite backup API, including committed WAL rows and pending writes. The handle adopts the copy only after the backup and the close of the source succeed; otherwise the source stays current. Saving to the current file, or to an existing hard link of it, keeps the current store.

  • An unnamed store becomes a named store through save_as(path).

Several handles, in one process or in several, may open the same database file. SQLite’s file locking serializes their writes:

  • A handle that needs a lock another connection holds waits up to 5 seconds, then fails as busy. Commit promptly when other handles share the file.

  • Serialize all calls on one handle, reads included. Handles for different stores, or different handles on one store, can work concurrently.

  • Writes and commits run on the thread that makes the call. For an asynchronous fetch, that is its background worker. SQLite frame encoding stays on that thread too.

Interrupted commits#

ovclash never changes a database’s journal mode, and it leaves SQLite’s synchronous setting at its default. SQLite’s own atomic commit therefore protects the file: when a process stops during a commit, SQLite rolls the incomplete transaction back the next time the database is opened. Keep the database’s -journal or -wal file beside it until then.

System SQLite library#

Neither the wheel nor the SDK archive ships a SQLite library. The serializer loads the system library at run time, once per process, when a SQLite store first needs a database connection:

Platform

Library

Windows

winsqlite3.dll from the System32 directory, which Windows provides. No other copy is searched for, so a sqlite3.dll on the DLL search path cannot substitute for it.

Linux

libsqlite3.so.0, else libsqlite3.so, through the dynamic loader’s normal search.

  • If the library cannot be loaded, opening or writing a SQLite store fails with winsqlite3.dll could not be loaded on Windows, or with the dynamic loader’s message on Linux. A library that lacks a required function fails with SQLite symbol was not found: <name>.

  • On Linux, install the distribution’s SQLite runtime library when libsqlite3.so.0 is missing, for example libsqlite3-0 on Debian and Ubuntu.

  • On Windows, the operating system provides winsqlite3.dll, and ovclash loads no other copy. When it cannot be loaded, use a directory store, which needs no SQLite.

  • A directory store does not need SQLite, and probe_legacy_clash_detection_file() works without it.