Metadata-Version: 2.4
Name: SPARQLMojo
Version: 0.19.0rc3
Summary: An SQLAlchemy-like ORM for SPARQL endpoints.
License-Expression: MIT
License-File: LICENSE
Keywords: sparql,rdf,orm,pydantic,linked-data,semantic-web
Author: Oliver Sampson
Requires-Python: >=3.12
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Database
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Provides-Extra: shacl
Requires-Dist: SPARQLWrapper (>=2.0.0)
Requires-Dist: pydantic (>=2.12.4,<3.0.0)
Requires-Dist: pyshacl (>=0.40.1,<0.41.0) ; extra == "shacl"
Requires-Dist: rdflib (>=6.0.0)
Project-URL: Documentation, https://gitterdan.gitlab.io/sparqlmojo
Project-URL: Homepage, https://gitlab.com/gitterdan/sparqlmojo
Project-URL: Repository, https://gitlab.com/gitterdan/sparqlmojo
Description-Content-Type: text/markdown

# SPARQLMojo

An SQLAlchemy-like ORM for SPARQL endpoints with Pydantic validation. Currently in beta, so there may be breaking changes.

## Table of Contents

- **[Full Documentation Index](https://gitterdan.gitlab.io/sparqlmojo)**
- [Features](#features)
- [Installation](#installation)
- [Version](#version)
- [Usage](#usage)
- [HTTP Method Configuration](#http-method-configuration)
- [Identity Map](#identity-map)
- [PREFIX Management System](#prefix-management-system)
- [Language-Tagged Literals](#language-tagged-literals)
- [Collection Fields](#collection-fields)
- [UPDATE Operations](#update-operations)
- [VALUES Clause Support](#values-clause-support)
- [Property Paths](#property-paths)
- [CONSTRUCT Queries](#construct-queries)
- [Ontology-Aware Models with SchemaRegistry](#ontology-aware-models-with-schemaregistry)
- [SHACL Validation](#shacl-validation)
- [Class Hierarchy Support](#class-hierarchy-support)
- [Field-Level Filtering](#field-level-filtering)
- [Aggregate Queries](#aggregate-queries)
- [Temporal Graphs](#temporal-graphs)
- [Running Tests](#running-tests)
- [Test Dataset](#test-dataset)
- [Limitations](#limitations)
- [Known Issues and Risks](#known-issues-and-risks)
- [Release Process](#release-process)
- [Dependencies](#dependencies)
- [Key Benefits of Pydantic Integration](#key-benefits-of-pydantic-integration)
- [Strict Validation](#strict-validation)
- [License](#license)

## Features

- Declarative RDF models using Python classes with **Pydantic validation**
- Type-safe field definitions with automatic validation
- A session layer for querying and updating SPARQL endpoints
- A query compiler that converts Pythonic queries to SPARQL
- **Session identity map** to prevent duplicate instances and ensure consistency
- **PREFIX management system** for namespace handling with short-form IRIs
- **Language-tagged literal support** for multilingual text data
- **Property path support** with ORM-like convenience methods and inverse path support for reverse relationship traversal
- **CONSTRUCT query support** via `.construct()`/`.graph()`, reusing the `Query` builder's filter/VALUES/collection-field machinery instead of raw SPARQL
- **Field-level filtering** with intuitive syntax and automatic datatype casting for numeric comparisons
- **String filtering on IRI fields** with chainable `str()`, `lower()`, `upper()` methods for case-insensitive matching
- **Ontology-aware models** with SchemaRegistry for automatic inverse relationship discovery via `owl:inverseOf`
- **SHACL validation** on add/update via an optional `ShapesRegistry`, layered on top of existing validation and gated behind the `sparqlmojo[shacl]` extra
- **InverseField** for clean, semantic reverse relationship navigation with automatic fallback to SPARQL `^` operator
- **Class hierarchy support** with automatic polymorphic queries — querying a base class returns all subclass instances without any extra configuration

## Installation

```bash
# Install dependencies
poetry install

# Or install the package in editable mode
pip install -e .
```

## Version

Check the installed version:

```python
import sparqlmojo
print(sparqlmojo.__version__)  # Output: 0.1.0
```

Or from the command line:

```bash
python -c "import sparqlmojo; print(sparqlmojo.__version__)"
```

### Versioning Workflow

This project uses semantic versioning with automated releases. See the [Release Process](#release-process) section for details on creating releases.

## Usage

```python
from typing import Annotated

from sparqlmojo import (
    InverseField,
    IRIField,
    LiteralField,
    Model,
    ObjectPropertyField,
    RDF_TYPE,
    SchemaRegistry,
    Session,
    SPARQLCompiler,
    SubjectField,
)


class Person(Model):
    rdf_type: Annotated[str, IRIField(RDF_TYPE, default="schema:Person")]
    iri: Annotated[str, SubjectField()]
    name: Annotated[str | None, LiteralField("schema:name")] = None
    age: Annotated[int | None, LiteralField("schema:age")] = None
    knows: Annotated[str | None, ObjectPropertyField("schema:knows", range_="Person")] = None


# Create a session
s = Session(endpoint="http://example.org/sparql")

# For endpoints with separate read/write URLs (e.g., Fuseki):
# s = Session(
#     endpoint="http://example.org/sparql",           # For SELECT queries
#     write_endpoint="http://example.org/update"      # For INSERT/DELETE/UPDATE
# )

# Configure HTTP method for queries (see "HTTP Method Configuration" below):
# s = Session(endpoint="http://example.org/sparql", query_method="GET")

# Build and compile a query
q = s.query(Person).filter(Person.age > 30).limit(5)
sparql = SPARQLCompiler.compile_query(q)
print(sparql)

# Create an instance with validation
bob = Person(iri="http://example.org/bob", name="Bob", age=28)
s.add(bob)
s.commit()

# Pydantic validates types automatically
try:
    invalid = Person(iri="http://example.org/alice", name="Alice", age="not a number")  # Raises ValidationError
except Exception as e:
    print(f"Validation error: {e}")
```

## HTTP Method Configuration

SPARQLMojo supports configurable HTTP methods for SPARQL queries (SELECT, ASK and CONSTRUCT). By default, POST is used to avoid URL length limitations with large queries.

### Query Methods

| Method | Description | Use Case |
|--------|-------------|----------|
| `POST` | Use HTTP POST for queries (default) | Recommended for most cases; avoids URL length issues |
| `GET` | Use HTTP GET for queries | Required by some read-only endpoints; better caching |

### Configuration

```python
from sparqlmojo import Session

# Default: Always use POST (safest option)
session = Session(endpoint="http://example.org/sparql")
# or explicitly:
session = Session(endpoint="http://example.org/sparql", query_method="POST")

# Use GET (for endpoints that require it or for caching benefits)
session = Session(endpoint="http://example.org/sparql", query_method="GET")
```

### When to Use Each Mode

**POST (Default)**
- Recommended for most applications
- No risk of HTTP 414 "URI Too Long" errors
- Works with queries of any size, including large VALUES clauses
- Some proxies/CDNs may not cache POST requests

**GET**
- Better HTTP caching (responses can be cached by proxies)
- Required by some read-only SPARQL endpoints
- Risk of HTTP 414 errors with large queries (URLs > 2000 characters)
- Query is visible in server access logs (potential security consideration)

Note: UPDATE queries (INSERT, DELETE) always use POST regardless of this setting, as required by the SPARQL protocol.

### Hand-written SPARQL

`session.execute_sparql()` sends a request object, whose class says what kind of
request it is: `SelectRequest` and `AskRequest` return the SPARQL JSON results,
`ConstructRequest` (also for `DESCRIBE`) returns Turtle, and `UpdateRequest` goes to
the write endpoint on the update protocol. The class decides, not the words in the
text, so an update into a graph such as `<http://example.org/select/g>` is still sent
as an update.

```python
from sparqlmojo import SelectRequest, UpdateRequest

session.execute_sparql(UpdateRequest("DROP SILENT GRAPH <http://example.org/g>"))
rows = session.execute_sparql(SelectRequest("SELECT ?s WHERE { ?s ?p ?o }"))
```

## Identity Map

SPARQLMojo now includes a Session identity map to prevent duplicate instances and ensure consistency:

```python
# First retrieval creates new instance
person1 = session.get(Person, "http://example.org/bob")

# Second retrieval returns the SAME instance (not a duplicate)
person2 = session.get(Person, "http://example.org/bob")

assert person1 is person2  # True - same object reference

# Changes to one reference are visible in all references
person1.name = "Robert"
print(person2.name)  # "Robert" - same object
```

### Benefits

- **Memory Efficiency**: Uses weak references for automatic garbage collection
- **Consistency**: All operations on the same entity work with the same object
- **Performance**: Avoids creating duplicate objects for the same entity
- **Automatic Management**: No manual cache management required

### Manual Cache Management

```python
# Remove specific instance from identity map
session.expunge(person)

# Clear all instances from identity map
session.expunge_all()
```

## PREFIX Management System

SPARQLMojo now includes a comprehensive PREFIX management system for namespace handling:

### Features

- **Built-in Common Prefixes**: schema, foaf, rdf, rdfs, owl, xsd, dc, dcterms, skos, ex, tg
- **Custom Prefix Registration**: Add your own namespace prefixes
- **Short-form IRI Support**: Use `schema:Person` instead of full IRIs
- **Automatic PREFIX Declarations**: SPARQL queries include proper PREFIX clauses
- **IRI Expansion/Contraction**: Convert between short-form and full IRIs
- **Query Values**: `filter()`, `filter_by()` (including the subject field) and `values()` (IRI fields and the subject column) expand short-form IRIs against the session's registered prefixes
- **One rule for IRI values**: an IRI field's values, its default (`rdf_type` included) and subject IRIs are resolved the same way wherever they are used (writes, filters, polymorphic type lists). The rule covers values, not predicates: a field's predicate follows the rules in [Property Paths](docs/property-paths.md#writing-the-predicate-of-a-field). Text whose scheme is directly followed by `//` (`http://example.org/a`) and text in angle brackets (`<ex:a>`) are absolute IRIs as written. Otherwise a prefixed name whose prefix the session registers is expanded (`ex:a//b` and `ex:a://b` included); with an unregistered prefix the text is an absolute IRI when its local part contains `//` or its scheme is one of `urn`, `mailto`, `did`, `tag`, `doi`, `ark`, `geo`, `data`, `info`, `ipfs`, and anything else raises `UnregisteredPrefixError`. Text with no scheme (`:a`, `relative/a`) or no local part (`ex:`) raises `IRIError`. An IRI field default is parsed at declaration, so a relative or malformed one fails there. A query compiled without a session resolves through the prefixes a new session starts with. Every stored IRI that parses as a prefixed name, `urn:isbn:1` and `mailto:` IRIs included, reads back in brackets (`"<urn:isbn:1>"`), whatever prefixes are registered, so writing the value back names the IRI that was read; this includes subject IRIs, temporal edge targets, `group_by()` keys and `min()`/`max()` over an IRI field, and a subject may be given in brackets too

### Usage

```python
from typing import Annotated

from sparqlmojo import IRIField, LiteralField, Model, RDF_TYPE, Session, SubjectField

# Define model with short-form IRIs
class Person(Model):
    rdf_type: Annotated[str, IRIField(RDF_TYPE, default="schema:Person")]
    iri: Annotated[str, SubjectField()]
    name: Annotated[str | None, LiteralField("schema:name")] = None
    age: Annotated[int | None, LiteralField("schema:age")] = None

# Create session with built-in prefix registry
session = Session()

# Register custom prefix
session.register_prefix("my", "http://example.org/my/")

# Query generation with automatic PREFIX declarations
query = session.query(Person)
sparql = query.compile()
# Generates: PREFIX schema: <http://schema.org/> ...

# IRI expansion/contraction
expanded = session.expand_iri("schema:Person")  # "http://schema.org/Person"
contracted = session.contract_iri("http://schema.org/Person")  # "schema:Person"
```

### Benefits

- **Improved Developer Experience**: No need to write full IRIs everywhere
- **Better Readability**: Code is more concise and understandable
- **Easy Maintenance**: Update namespace URIs in one place
- **Standards Compliance**: Generates proper SPARQL PREFIX declarations

## Language-Tagged Literals

SPARQLMojo supports language-tagged literals via `LangString` and `MultiLangString` fields for multilingual text data with BCP 47-shaped language tag validation.

→ [Full documentation](docs/language-tagged-literals.md)

## Collection Fields

SPARQLMojo supports collection fields (`LiteralList`, `LangStringList`, `IRIList`, `TypedLiteralList`) for aggregating multiple values from multi-valued RDF properties into Python lists, with support for filtering, size limiting, and efficient multi-field queries.

→ [Full documentation](docs/collection-fields.md)

## UPDATE Operations

SPARQLMojo supports UPDATE operations with dirty tracking, as well as batch inserts, updates, and deletes with automatic chunking for large datasets.

→ [Full documentation](docs/update-operations.md)

## Running Tests

```bash
# Run all tests
poetry run pytest

# Run specific test file
poetry run pytest tests/test_basic.py
```

**See Also**: [Test Fixtures Documentation](tests/README.md) for comprehensive documentation of shared fixtures, test models, and test organization.

## Test Dataset

The project includes a comprehensive library management test dataset in `tests/fixtures/library.ttl` with Books, Users, and Checkout Records, along with worked examples showing how Python model instances translate to RDF triples.

→ [Full documentation](docs/test-dataset.md)

## Limitations

This is a prototype with several intentional limitations:

- **No transaction support**: Simple staging mechanism for inserts only
- **No conflict resolution**: Basic operations only
- **Not production-ready**: Focuses on demonstrating design patterns

For real-world use, consider adding:
- Proper literal typing
- Better parsing of results
- Streaming results and pagination
- Transaction support

## Known Issues and Risks

### Pydantic Internal API Dependency

SPARQLMojo uses Pydantic's internal `ModelMetaclass` to enable the intuitive field-level filtering syntax:

```python
# This clean syntax is powered by the custom metaclass
query.filter(Person.name == "Alice")
query.filter(Product.price > 100)
```

**The Risk**: The metaclass is imported from Pydantic's **private internal API**:

```python
from pydantic._internal._model_construction import ModelMetaclass as PydanticModelMetaclass
```

The `_internal` prefix indicates this is not part of Pydantic's public API and **could change without notice** in any Pydantic release. According to the Pydantic maintainers, they "want to be able to refactor the `ModelMetaclass` without it being considered a breaking change."

**What This Means**:
- ⚠️ **No stability guarantees**: The metaclass implementation may change in minor/patch releases
- ⚠️ **No deprecation warnings**: Changes won't be announced in advance
- ⚠️ **Potential breakage**: Any Pydantic update could require code changes

**Mitigation Strategy**:
1. **Pin Pydantic version** carefully in production environments
2. **Test thoroughly** after any Pydantic updates before upgrading
3. **Fallback available**: If the metaclass breaks, fall back to the less elegant method-based approach:
   ```python
   # Alternative syntax that doesn't depend on private APIs
   query.filter(Person._get_field_filter("name") == "Alice")
   ```

**Why We Use It Anyway**: The UX benefit of the SQLAlchemy-like syntax is significant for a prototype focused on design clarity. For production use, consider the risk-reward tradeoff for your specific needs.

**References**:
- [Pydantic Issue #6381: ModelMetaclass Import Location](https://github.com/pydantic/pydantic/issues/6381)
- [Pydantic Discussion #7185: ModelField and ModelMetaclass in v2](https://github.com/pydantic/pydantic/discussions/7185)

## VALUES Clause Support

`values()` restricts a query to the subjects matching one of a list of rows (a subject, field values, or both), via an ORM-style field-reference API and a dict-style API for rows of several fields. Instances still hold every stored value of their fields.

→ [Full documentation](docs/values-clause.md)

## Property Paths

SPARQLMojo supports SPARQL property paths for advanced relationship traversal, with ORM-like convenience methods (`transitive`, `zero_or_more`, `inverse`, etc.) and `.path()` for any other path expression.

→ [Full documentation](docs/property-paths.md)

## CONSTRUCT Queries

SPARQLMojo supports building and executing `CONSTRUCT` queries through the `Query` builder — reusing the same `.filter()`/`.filter_by()`/`.values()`/collection-field machinery as `SELECT` queries — via `.construct()` and `.graph()`, which executes and returns an `rdflib.Graph`.

→ [Full documentation](docs/construct-queries.md)

## Ontology-Aware Models with SchemaRegistry

SPARQLMojo provides ontology-aware modeling through `SchemaRegistry`, enabling automatic inverse relationship discovery via `owl:inverseOf` and compile-time schema validation (domain, range, cardinality).

→ [Full documentation](docs/schema-registry.md)

## SHACL Validation

`Session.add()`/`add_all()`/`update()`/`update_all()` can run [SHACL](https://www.w3.org/TR/shacl/) validation against an instance's triples before staging the write, layered on top of `validate_instance()` and any `validator=` callables. Requires the optional `sparqlmojo[shacl]` extra (`poetry add sparqlmojo[shacl]`).

→ [Full documentation](docs/shacl-validation.md)

## Class Hierarchy Support

SPARQLMojo supports `rdfs:subClassOf` class hierarchies — querying a base class automatically returns all registered subclass instances via polymorphic `VALUES ?s·type` queries, with no extra configuration required.

→ [Full documentation](docs/class-hierarchy.md)

## Field-Level Filtering

SPARQLMojo provides intuitive field-level filtering similar to SQLAlchemy, with Python comparison operators, automatic datatype casting, chainable string methods for IRI fields, and logical operators (`and_`, `or_`, `not_`).

→ [Full documentation](docs/field-level-filtering.md)

## Aggregate Queries

`count_()`, `sum()`, `avg()`, `min()` and `max()`, grouped with `group_by()`, return one dictionary per group. Subjects count once however many values their fields hold, a collection field is aggregated value by value, and `filter=` on one aggregate narrows only that aggregate's values (`count_("age", filter=Person.age > 40)`), while `filter()` selects the subjects every aggregate reads.

→ [Full documentation](docs/aggregates.md)

## Temporal Graphs

SPARQLMojo can bitemporally track a field's history — when a fact held in the world (valid time) and when the record said so (transaction time) — opt-in per field via `TemporalEdgeField`/`TemporalEdgeList`/`TemporalLiteralField`/`TemporalLiteralList`. `session.at(valid=..., belief=...)` reads any past slice, `session.history()` returns the full audit trail, and `close_interval()`/`correct()` retract by superseding, never by deleting.

→ [Full documentation](docs/temporal-graphs.md)

## Local CI

`scripts/local-ci.sh` runs the pipeline's checks on your machine. The ruff and mypy versions, the coverage floor, the Fuseki/Oxigraph image tags and the Fuseki service's command line are read from `.gitlab-ci.yml`; a local engine container made for a different image or command is replaced. The pytest marker expressions and the ruff and mypy command lines must appear there verbatim, or the script refuses to run. Other job details (install steps, extra pytest flags) are not mirrored.

```bash
scripts/local-ci.sh                 # ruff (pinned), mypy --strict (pinned), pytest with the coverage floor
scripts/local-ci.sh --outbound      # + outbound suite against a local Fuseki container
scripts/local-ci.sh --portability   # + outbound suite against a local Oxigraph container
scripts/local-ci.sh --docs          # + mkdocs build --strict (needs `poetry install --with docs`)
scripts/local-ci.sh --all           # everything above
scripts/local-ci.sh containers {start|stop|status}
```

Requirements: `poetry install --all-extras`, Docker for the outbound flags, and `flock`/`curl`. The script exits non-zero on any failure; every check that runs ends with a PASS or FAIL line, followed by a final `LOCAL CI: PASS` or `LOCAL CI: FAIL`.

- Changes to the read path (query compilation, result parsing, session reads) should be run with `--portability` as well as `--outbound`, since every outbound test must pass on both engines.
- Outbound runs (and `containers stop`) hold an exclusive `flock` on `${TMPDIR:-/tmp}/sparqlmojo-outbound.lock` (override with `SM_CI_LOCK_FILE`), because concurrent local runs against one dataset interfere.
- The container helper is idempotent: it starts `sm-ci-fuseki` and `sm-ci-oxigraph` only if they are not already running. Hosts and ports are overridable with `SM_CI_FUSEKI_HOST`, `SM_CI_FUSEKI_PORT`, `SM_CI_OXIGRAPH_HOST` and `SM_CI_OXIGRAPH_PORT`.
- Type-checking resolves imports against your full dev environment, whereas the pipeline installs only the main dependencies.

## Release Process

SPARQLMojo uses a tag-based release workflow with automated CHANGELOG management, PyPI publishing, and GitLab Releases.

### Workflow Overview

1. **During Development**: Update `CHANGELOG.md` in the `[Unreleased]` section when creating merge requests
2. **Accumulate Changes**: Multiple MRs can add to `[Unreleased]` before a release
3. **Create Release**: Tag the commit to trigger automated release creation

### For Contributors (Merge Request Time)

When creating a merge request, update `CHANGELOG.md` under the `[Unreleased]` section:

```markdown
## [Unreleased]

### Fixed
- Issue #123: Fixed bug in query compilation

### Added
- New feature for advanced filtering

### Changed
- Improved performance of batch operations
```

Follow [Keep a Changelog](https://keepachangelog.com/) format with sections:
- `Fixed` - Bug fixes
- `Added` - New features
- `Changed` - Changes to existing functionality
- `Deprecated` - Soon-to-be removed features
- `Removed` - Removed features
- `Security` - Security fixes

### For Maintainers (Release Time)

When ready to release a new version:

```bash
# 1. Preview release notes and create tag
./scripts/tag-release.sh 0.12.0

# 2. Push the tag to trigger CI/CD automation
git push origin 0.12.0
```

Pushing the tag triggers two jobs in the `release` stage of `.gitlab-ci.yml`:
- **`publish-pypi`** builds the package and publishes it to PyPI
- **`create-release`** runs `publish-release.sh`, which:
  - Extracts release notes from the `[Unreleased]` section
  - Updates `CHANGELOG.md` (`[Unreleased]` → `[0.12.0] - 2026-03-05`)
  - Adds new empty `[Unreleased]` section at the top
  - Commits and pushes the CHANGELOG update to main
  - Creates the GitLab release with the extracted notes

**Release candidates**: tag `X.Y.Z-rcN` (e.g. `./scripts/tag-release.sh 0.19.0-rc1`). The same
jobs run, publishing PEP 440 pre-release `0.19.0rc1` to PyPI (not installed by default) and a
GitLab release, but `CHANGELOG.md` is left untouched; `[Unreleased]` is promoted by the final
`X.Y.Z` release.

**Manual Alternative** (if CI/CD unavailable):

```bash
# 1. Create tag
git tag 0.12.0

# 2. Run publish script (pushes the tag, updates and pushes CHANGELOG,
#    creates the GitLab release)
./scripts/publish-release.sh 0.12.0
```

### Release Scripts

- **`tag-release.sh`** - Create annotated tag with release notes preview
- **`publish-release.sh`** - Update CHANGELOG and publish to GitLab
- **`create-release.sh`** - Legacy all-in-one script (use `tag-release.sh` instead)

See `scripts/README.md` for detailed documentation.

### Version Format

Use semantic versioning: `MAJOR.MINOR.PATCH`

- **MAJOR**: Breaking changes
- **MINOR**: New features (backward compatible)
- **PATCH**: Bug fixes (backward compatible)

Examples: `0.11.0`, `1.0.0`, `1.2.3`

## Dependencies

- `pydantic>=2.12.4` - Data validation and type checking
- `SPARQLWrapper>=2.0.0` - SPARQL endpoint communication
- `rdflib>=6.0.0` - RDF graph parsing and manipulation

Optional (`sparqlmojo[shacl]` extra):

- `pyshacl` - SHACL shape validation (see [SHACL Validation](#shacl-validation))

## Key Benefits of Pydantic Integration

- **Type Safety**: Fields are validated at runtime against their type annotations
- **Better IDE Support**: Full autocomplete and type hints in modern IDEs
- **Clear Error Messages**: Pydantic provides detailed validation errors
- **Strict Validation**: No value is converted to another type: `"123"` is refused for an `int` field (see [Strict Validation](#strict-validation))
- **Extra Field Protection**: Unknown fields are rejected by default

## Strict Validation

Every model validates in Pydantic's strict mode, at construction, on
assignment, in `model_copy(update=...)` and inside temporal wrappers: a value
must already have its field's declared type. `Person(age="30")` raises
`pydantic.ValidationError`; pass `age=30`. Convert input from text (forms,
CSV, JSON strings) before building a model.

A value read from the store must read as its field's declared type, or the
read raises `StoredValueError`, which names the model, the field, the
subject and the stored term (`error.model`, `error.field`, `error.subject`,
`error.term`), so the data can be found and fixed. The library never guesses
a value:

- The field tries its declared type, or each member of a union in order
  (`int | float`), and takes the first that reads the term. A typed literal
  is read as its datatype's value (`"7"^^xsd:short` is `7` on an `int`
  field); a plain literal (`xsd:string` counts as plain), or a literal whose
  datatype derives from the one the type is written as, is parsed as the
  type (`"7"` on an `int` field is `7`, an `xsd:dateTimeStamp` on a
  `datetime` field a `datetime`). A `Decimal` or `float` field reads any XSD
  number (`"1.5"^^xsd:double` on a `Decimal` field is `Decimal("1.5")`); an
  `int` field only integers. An enum field takes the member the value names.
- A field whose type admits `str` (`str`, `str | None`, `int | str`) keeps
  the lexical form as stored (`"yes"^^xsd:boolean` reads as `"yes"`).
- Anything else is refused: `"abc"^^xsd:integer` or `"1.5"^^xsd:decimal` on
  an `int` field, `"yes"^^xsd:boolean` on a `bool` field, `"7"` on an enum
  field with no member 7, a literal on an `IRIField`, an IRI on a
  `LiteralField`.
- A stored subject the model refuses at construction (an http or https IRI
  with no host, such as `https:x`) fails the read the same way, naming the
  subject field. A model with `validate_iris = False` reads it.

The model's own validators, field validators and `Field(...)` constraints
still run on each instance read; a value they refuse raises
`StoredValueError` too (with an empty `error.field` for a model validator).
Catch `StoredValueError`, not `pydantic.ValidationError`, around a read.

A plain list field's value checks every item put into it (`append()`,
`extend()`, `insert()`, `+=`, item assignment) as construction would, and
raises `pydantic.ValidationError` with the list unchanged. A plain `Enum`
member is written as its value (`"red"`), and read back as the member.

A list field read through `GROUP_CONCAT` names an item by its
lexical form with the datatype the field writes, since the aggregation keeps
only the text.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

