๐ Query Builder
The ZTeraDBQuery class provides a type-safe, fluent, and chainable interface to build database operations across your entire infrastructure without writing raw SQL.
๐ฏ Core Capabilitiesโ
ZTeraDBQuery encapsulates standard CRUD actions and advanced data modification matrices into an abstracted object:
- Unified Syntax: Write queries once; execute seamlessly regardless of whether the target database is relational or document-oriented.
- Filtering Strategies: Apply both simple strict-equality filters and complex operational abstract syntax trees (ASTs).
- Sorting Matrices: Define index priority scan orders cleanly via directional weighting markers.
- Pagination Control: Restrict network payload weight sizes natively via structural offset limiting.
- Related Field Lookups (Joins): Perform effortless entity relation stitching by recursively scoping query parameters inside connected models.
- Prevent Injection: Parameters are structurally parsed to isolate execution logic from data inputs.
๐ง Query Lifecycleโ
๐ Operations Matrixโ
| Operation | Method | Primary Purpose |
|---|---|---|
| Read | .select() | Retrieves records from the target collection/schema. |
| Create | .insert() | Appends new datasets or entries to the infrastructure layer. |
| Update | .update() | Modifies existing values based on matched criteria. |
| Destroy | .delete() | Purges target rows/documents from persistence layers. |
๐น Initializing a Query Instanceโ
Pass your targeted table or schema name directly to the class constructor block.
from zteradb import ZTeraDBQuery
query = ZTeraDBQuery("schemaName")
๐ท Executing Basic CRUD Operationsโ
- SELECT (with Field Projections)
query = (
ZTeraDBQuery("user")
.select()
.fields({
"email": 1,
"status": 1
})
)
- INSERT
Always bind your input data state to the runtime context via
.fields()right after executing your creation hooks.
query = (
ZTeraDBQuery("user")
.insert()
.fields({
"name": "John",
"email": "john@test.com",
"status": True
})
)
- UPDATE
Combines data mutations assigned through
.fields()alongside conditional filtering targets.
query = (
ZTeraDBQuery("user")
.update()
.fields({"status": False})
.filter({"id": 1})
)
- DELETE Restricts target deletion records utilizing basic evaluation scope parameters.
query = (
ZTeraDBQuery("user")
.delete()
.filter({"id": 5})
)
๐ฏ Query Filtering Strategyโ
ZTeraDB supports two execution paths for evaluation constraints depending on query complexity.
Basic Key-Value Matching (filter)โ
For deterministic equality evaluations (WHERE field = value), use the high-performance dictionary layout.
query.filter({"status": True})
query.filter({"id": 10})
query.filter({"email": "abc@test.com"})
Advanced AST Parsing (filter_condition)โ
For complex functional evaluations containing algebraic computations, multi-conditional clauses, or mathematical boundaries, use AST operation wrappers imported from the library.
from zteradb.query.filter_condition import ZTEQUAL, ZTMUL
# Compiles to: WHERE price * quantity = 200
query.filter_condition(
ZTEQUAL([
ZTMUL(["price", "quantity"]),
200
])
)
๐ Related Fields Lookup (Joins)โ
Entity relationships can be fetched and stitched recursively by embedding isolated query builder pipelines into properties via .related_fields().
# 1. Establish the isolated scope constraint for the related entity
user_filter = (
ZTeraDBQuery("user")
.select()
.fields({"email": 1})
.filter({"status": True})
)
# 2. Map the relationship scope directly into the host query pipeline
query = (
ZTeraDBQuery("order")
.select()
.related_fields({
"user": user_filter
})
)
๐ Sorting, Pagination, & Aggregationsโ
Sorting Modifiersโ
Configure delivery sorting vectors using standard indexing weights: 1 for Ascending and -1 for Descending execution orders.
query.sort({"price": 1}) # Ascending (Low to High)
query.sort({"price": -1}) # Descending (High to Low)
Offset Paginationโ
Limit network payload memory sizes at runtime by requesting distinct chunk offsets via .limit(offset: int, count: int).
query.limit(0, 10) # Fetches the first 10 matching records
Count Aggregationsโ
To return an integer indexing the total quantity of rows matching your parameters without retrieving heavy data payloads, call .count().
query.count()
๐งช Comprehensive Blueprint Exampleโ
# query_example.py
from zteradb.query import ZTeraDBQuery
query = (
ZTeraDBQuery("product")
.select()
.fields({
"name": 1,
"price": 1
})
.filter({"status": "A"})
.sort({"price": 1})
.limit(0, 20) # From the beginning, fetch the top 20 records
)
โ ๏ธ Common Developer Anti-Patternsโ
-
โ Over-using Complex Operations: Invoking
filter_condition()for simple, strict equalities.- Fix: Default to
.filter()for strict key-value dictionaries to leverage internal driver string-parsing optimizations.
- Fix: Default to
-
โ Skipping Input Payload Mappings: Forgetting to pass dictionary attributes via
.fields()during creation or patch cycles.- Fix: The driver throws runtime exceptions if data mutation states are missing during an
insert()orupdate().
- Fix: The driver throws runtime exceptions if data mutation states are missing during an
-
โ Invalid Sort Directions: Passing arbitrary string evaluation characters like
"ASC","DESC", or an un-indexed boundary step like0.- Fix: Strictly utilize
1or-1for direction control.
- Fix: Strictly utilize
-
โ Instantiating Without Schema Identifiers: Attempting to build an orphan configuration without giving the constructor a target database schema.
- Fix: Always pass a valid schema name into the
ZTeraDBQuery()invocation sequence.
- Fix: Always pass a valid schema name into the
๐ Next Stepโ
Dive deep into creating relational conditions, nested logic expressions, and advanced query operators:
๐ Filter Condition Guide