clm-kernel 0.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- clm/__init__.py +230 -0
- clm/__main__.py +25 -0
- clm/cross_cutting/__init__.py +50 -0
- clm/cross_cutting/_test_runner.py +36 -0
- clm/cross_cutting/async_utils.py +25 -0
- clm/cross_cutting/cel_builder.py +123 -0
- clm/cross_cutting/cel_converter.py +697 -0
- clm/cross_cutting/cel_engine.py +252 -0
- clm/cross_cutting/cel_ops.py +72 -0
- clm/cross_cutting/cel_ops_db.py +157 -0
- clm/cross_cutting/cel_ops_files.py +99 -0
- clm/cross_cutting/cel_ops_state.py +71 -0
- clm/cross_cutting/cel_ops_strings.py +64 -0
- clm/cross_cutting/cel_resolver.py +63 -0
- clm/cross_cutting/cel_slices.py +56 -0
- clm/cross_cutting/cel_store.py +330 -0
- clm/cross_cutting/clm_logger.py +140 -0
- clm/cross_cutting/config/__init__.py +155 -0
- clm/cross_cutting/config/config_constants.py +392 -0
- clm/cross_cutting/config/env_parameters.py +90 -0
- clm/cross_cutting/config/logging.py +378 -0
- clm/cross_cutting/config/settings.py +504 -0
- clm/cross_cutting/context.py +5 -0
- clm/cross_cutting/domain_models.py +55 -0
- clm/cross_cutting/domain_types.py +61 -0
- clm/cross_cutting/effects.py +67 -0
- clm/cross_cutting/errors.py +153 -0
- clm/cross_cutting/governance.py +331 -0
- clm/cross_cutting/guards.py +41 -0
- clm/cross_cutting/mcard.py +321 -0
- clm/cross_cutting/native.py +185 -0
- clm/cross_cutting/observability.py +289 -0
- clm/cross_cutting/pcard.py +434 -0
- clm/cross_cutting/registry.py +71 -0
- clm/cross_cutting/resources.py +84 -0
- clm/cross_cutting/secrets.py +44 -0
- clm/cross_cutting/subprocess_utils.py +118 -0
- clm/cross_cutting/telemetry.py +164 -0
- clm/cross_cutting/testing/__init__.py +8 -0
- clm/cross_cutting/testing/comparator.py +187 -0
- clm/cross_cutting/testing/datasets.py +87 -0
- clm/cross_cutting/timeutil.py +20 -0
- clm/cross_cutting/types/new_type_check.py +0 -0
- clm/cross_cutting/utils/__init__.py +1 -0
- clm/cross_cutting/utils/url_safety.py +50 -0
- clm/cross_cutting/vcard.py +560 -0
- clm/cross_cutting/writer.py +118 -0
- clm/layer0/README.md +50 -0
- clm/layer0/__init__.py +223 -0
- clm/layer0/algebra.py +60 -0
- clm/layer0/algebra_baldwin.py +133 -0
- clm/layer0/algebra_baldwin_generators.py +36 -0
- clm/layer0/algebra_equivalence.py +262 -0
- clm/layer0/algebra_ingest.py +306 -0
- clm/layer0/algebra_manifest_io.py +156 -0
- clm/layer0/assembler.py +481 -0
- clm/layer0/cel/__init__.py +23 -0
- clm/layer0/cel_eval.py +491 -0
- clm/layer0/codec.py +106 -0
- clm/layer0/context.py +122 -0
- clm/layer0/db.py +160 -0
- clm/layer0/exceptions.py +73 -0
- clm/layer0/fibration.py +106 -0
- clm/layer0/gates.py +50 -0
- clm/layer0/hash.py +80 -0
- clm/layer0/loader.py +826 -0
- clm/layer0/math_utils.py +163 -0
- clm/layer0/mcard.py +96 -0
- clm/layer0/model/__init__.py +0 -0
- clm/layer0/model/action.py +223 -0
- clm/layer0/model/card.py +280 -0
- clm/layer0/model/card_triad.py +427 -0
- clm/layer0/model/compatibility.py +60 -0
- clm/layer0/model/dictionary.py +46 -0
- clm/layer0/model/dots.py +331 -0
- clm/layer0/model/event_producer.py +88 -0
- clm/layer0/model/g_time.py +89 -0
- clm/layer0/model/handle.py +163 -0
- clm/layer0/model/hash/__init__.py +6 -0
- clm/layer0/model/hash/algorithms/__init__.py +3 -0
- clm/layer0/model/hash/algorithms/custom_hash.py +7 -0
- clm/layer0/model/hash/algorithms/local_sha256.py +178 -0
- clm/layer0/model/hash/constants.py +53 -0
- clm/layer0/model/hash/enums.py +60 -0
- clm/layer0/model/hash/validator.py +307 -0
- clm/layer0/model/interpreter.py +275 -0
- clm/layer0/model/pagination.py +45 -0
- clm/layer0/model/pcard.py +716 -0
- clm/layer0/model/schema.py +44 -0
- clm/layer0/model/utils/__init__.py +1 -0
- clm/layer0/model/utils/content_analyzer.py +152 -0
- clm/layer0/model/validators/__init__.py +1 -0
- clm/layer0/model/validators/base_validator.py +44 -0
- clm/layer0/model/validators/binary_validator.py +66 -0
- clm/layer0/model/validators/text_validator.py +82 -0
- clm/layer0/model/validators/validation_registry.py +49 -0
- clm/layer0/model/vcard.py +823 -0
- clm/layer0/model/vcard_ext/__init__.py +39 -0
- clm/layer0/model/vcard_ext/core.py +60 -0
- clm/layer0/model/vcard_ext/network.py +23 -0
- clm/layer0/model/vcard_ext/observability.py +63 -0
- clm/layer0/model/vcard_ext/storage.py +60 -0
- clm/layer0/model/vcard_ext/vendors.py +211 -0
- clm/layer0/model/vcard_sandwich.py +119 -0
- clm/layer0/model/vcard_vocabulary.py +463 -0
- clm/layer0/model/workflow.py +274 -0
- clm/layer0/narrative.py +431 -0
- clm/layer0/ontology/collection.py +125 -0
- clm/layer0/parser.py +429 -0
- clm/layer0/relations.py +73 -0
- clm/layer0/rule_evaluator.py +251 -0
- clm/layer0/schema/__init__.py +38 -0
- clm/layer0/schema/ddl.py +97 -0
- clm/layer0/templates/abstract.yaml +99 -0
- clm/layer0/templates/balanced.yaml +253 -0
- clm/layer0/templates/concrete.yaml +172 -0
- clm/layer0/type_registry.py +223 -0
- clm/layer0/types.py +204 -0
- clm/layer0/utils.py +886 -0
- clm/layer0/verifier_core.py +262 -0
- clm/layer1/__init__.py +31 -0
- clm/layer1/action_dispatcher.py +275 -0
- clm/layer1/adapter_registry.py +233 -0
- clm/layer1/algebra_baldwin_generators.py +192 -0
- clm/layer1/arrow_compiler.py +525 -0
- clm/layer1/batch_processor.py +152 -0
- clm/layer1/cel/__init__.py +27 -0
- clm/layer1/cel/builder.py +173 -0
- clm/layer1/engine.py +759 -0
- clm/layer1/engine_async.py +89 -0
- clm/layer1/eval_callback.py +49 -0
- clm/layer1/gate_composer.py +229 -0
- clm/layer1/hoare_sandwich.py +298 -0
- clm/layer1/identity_guard.py +348 -0
- clm/layer1/matrix.py +138 -0
- clm/layer1/neural_runtime.py +221 -0
- clm/layer1/operations/__init__.py +123 -0
- clm/layer1/operations/augment.py +156 -0
- clm/layer1/operations/base.py +109 -0
- clm/layer1/operations/builtins.py +338 -0
- clm/layer1/operations/dispatch.py +144 -0
- clm/layer1/operations/exclude.py +107 -0
- clm/layer1/operations/handle.py +197 -0
- clm/layer1/operations/identity.py +139 -0
- clm/layer1/operations/invert.py +66 -0
- clm/layer1/operations/loader.py +116 -0
- clm/layer1/operations/manipulators/__init__.py +23 -0
- clm/layer1/operations/manipulators/document.py +211 -0
- clm/layer1/operations/manipulators/media.py +134 -0
- clm/layer1/operations/manipulators/structured.py +159 -0
- clm/layer1/operations/manipulators/tabular.py +334 -0
- clm/layer1/operations/port.py +65 -0
- clm/layer1/operations/services.py +529 -0
- clm/layer1/operations/split.py +117 -0
- clm/layer1/operations/substitute.py +75 -0
- clm/layer1/petri.py +1052 -0
- clm/layer1/pocketflow_orchestrator.py +408 -0
- clm/layer1/pocketflow_scheduler.py +519 -0
- clm/layer1/protocols.py +197 -0
- clm/layer1/runtime_adapter.py +718 -0
- clm/layer1/runtimes/__init__.py +71 -0
- clm/layer1/runtimes/_generated_assertions.py +125 -0
- clm/layer1/runtimes/_generated_types.py +42 -0
- clm/layer1/runtimes/base.py +265 -0
- clm/layer1/runtimes/binary.py +101 -0
- clm/layer1/runtimes/factory.py +203 -0
- clm/layer1/runtimes/javascript.py +321 -0
- clm/layer1/runtimes/javascript_runtime.js +33 -0
- clm/layer1/runtimes/js_scripts/isomorphism.mjs +22 -0
- clm/layer1/runtimes/js_scripts/loader.mjs +52 -0
- clm/layer1/runtimes/lambda_calc.py +126 -0
- clm/layer1/runtimes/python.py +288 -0
- clm/layer1/runtimes/python_runtime.py +41 -0
- clm/layer1/runtimes/script.py +114 -0
- clm/layer1/sandbox.py +334 -0
- clm/layer1/savepoint_guard.py +136 -0
- clm/layer1/sparse_net.py +122 -0
- clm/layer1/spec_tester.py +165 -0
- clm/layer1/store.py +295 -0
- clm/layer1/test_runner.py +498 -0
- clm/layer1/type_inspector.py +166 -0
- clm/layer1/verifier.py +772 -0
- clm/layer1/vm.py +91 -0
- clm/layer2/__init__.py +78 -0
- clm/layer2/card_collection.py +678 -0
- clm/layer2/classifier.py +479 -0
- clm/layer2/engine/__init__.py +1 -0
- clm/layer2/engine/abstract_sql_engine.py +320 -0
- clm/layer2/engine/base.py +193 -0
- clm/layer2/engine/duckdb_engine.py +576 -0
- clm/layer2/engine/sqlite_engine.py +518 -0
- clm/layer2/fiber/__init__.py +31 -0
- clm/layer2/fiber/context.py +89 -0
- clm/layer2/fiber/disposable.py +163 -0
- clm/layer2/fiber/fiber.py +125 -0
- clm/layer2/fiber/hoare.py +191 -0
- clm/layer2/file_io.py +376 -0
- clm/layer2/file_registrar.py +77 -0
- clm/layer2/ingest.py +202 -0
- clm/layer2/lineage.py +322 -0
- clm/layer2/mcard_fs.py +262 -0
- clm/layer2/merkle.py +11 -0
- clm/layer2/mime.py +244 -0
- clm/layer2/mime_detector.py +245 -0
- clm/layer2/private_collection.py +118 -0
- clm/layer2/shared_store.py +11 -0
- clm/layer2/storage/__init__.py +190 -0
- clm/layer2/storage/db_bitemporal.py +141 -0
- clm/layer2/storage/db_driver.py +331 -0
- clm/layer2/storage/db_hyperlinks.py +214 -0
- clm/layer2/storage/db_pool.py +139 -0
- clm/layer2/storage/db_repository.py +229 -0
- clm/layer2/storage/savepoint.py +78 -0
- clm/layer2/storage/sqlite_wal.py +74 -0
- clm/layer2/tridb.py +245 -0
- clm/layer2/vcard_receipt.py +71 -0
- clm/layer2/vfs.py +17 -0
- clm/layer3/__init__.py +141 -0
- clm/layer3/agency/__init__.py +19 -0
- clm/layer3/agency/config.py +220 -0
- clm/layer3/agency/providers/__init__.py +15 -0
- clm/layer3/agency/providers/base.py +91 -0
- clm/layer3/agency/providers/mlc_llm.py +169 -0
- clm/layer3/agency/providers/ollama.py +203 -0
- clm/layer3/agency/router.py +71 -0
- clm/layer3/agency/runtime.py +524 -0
- clm/layer3/gateway.py +353 -0
- clm/layer3/open_interpreter_adapter.py +159 -0
- clm/layer3/rag/__init__.py +70 -0
- clm/layer3/rag/cli.py +228 -0
- clm/layer3/rag/config.py +153 -0
- clm/layer3/rag/embeddings/__init__.py +16 -0
- clm/layer3/rag/embeddings/base.py +79 -0
- clm/layer3/rag/embeddings/ollama.py +211 -0
- clm/layer3/rag/embeddings/vision.py +290 -0
- clm/layer3/rag/engine.py +276 -0
- clm/layer3/rag/graph/__init__.py +22 -0
- clm/layer3/rag/graph/community.py +198 -0
- clm/layer3/rag/graph/engine.py +433 -0
- clm/layer3/rag/graph/extractor.py +255 -0
- clm/layer3/rag/graph/schema.py +115 -0
- clm/layer3/rag/graph/store.py +641 -0
- clm/layer3/rag/indexer.py +333 -0
- clm/layer3/rag/llm_providers.json +52 -0
- clm/layer3/rag/semantic_versioning.py +313 -0
- clm/layer3/rag/vector/__init__.py +28 -0
- clm/layer3/rag/vector/handle_vector_store.py +749 -0
- clm/layer3/rag/vector/schema.py +151 -0
- clm/layer3/rag/vector/store.py +632 -0
- clm/layer3/reticulum/__init__.py +55 -0
- clm/layer3/reticulum/bridge.py +74 -0
- clm/layer3/reticulum/daemon.py +88 -0
- clm/layer3/reticulum/discovery.py +164 -0
- clm/layer3/reticulum/identity.py +107 -0
- clm/layer3/reticulum/media.py +148 -0
- clm/layer3/reticulum/transport.py +133 -0
- clm/layer3/satori/__init__.py +209 -0
- clm/layer3/satori/alpha_conversion.py +168 -0
- clm/layer3/satori/beta_reduction.py +359 -0
- clm/layer3/satori/continuation.py +38 -0
- clm/layer3/satori/eta_conversion.py +205 -0
- clm/layer3/satori/free_variables.py +163 -0
- clm/layer3/satori/io_effects.py +370 -0
- clm/layer3/satori/lambda_runtime.py +726 -0
- clm/layer3/satori/lambda_term.py +230 -0
- clm/layer3/satori/sheaf_audit.py +261 -0
- clm/layer3/satori/speech_act.py +279 -0
- clm/layer4/README.md +9 -0
- clm/layer4/__init__.py +67 -0
- clm/layer4/_sovereign_executor.py +580 -0
- clm/layer4/action_commands.py +719 -0
- clm/layer4/api.py +236 -0
- clm/layer4/bootstrap/__init__.py +13 -0
- clm/layer4/bootstrap/bootstrapper.py +118 -0
- clm/layer4/bootstrap/cleanup.py +44 -0
- clm/layer4/bootstrap/clm_hooks.py +49 -0
- clm/layer4/bootstrap/genesis.py +77 -0
- clm/layer4/bootstrap/injection.py +125 -0
- clm/layer4/cli.py +549 -0
- clm/layer4/collection_manager.py +553 -0
- clm/layer4/commands/__init__.py +81 -0
- clm/layer4/commands/action_cmd.py +42 -0
- clm/layer4/commands/check_cmd.py +82 -0
- clm/layer4/commands/envelope.py +73 -0
- clm/layer4/commands/evaluate_cmd.py +224 -0
- clm/layer4/commands/mcard_cmd.py +24 -0
- clm/layer4/commands/petri_cmd.py +92 -0
- clm/layer4/commands/tridb_cmd.py +319 -0
- clm/layer4/commands/version_cmd.py +27 -0
- clm/layer4/diff_commands.py +167 -0
- clm/layer4/eoa_sponsor.py +232 -0
- clm/layer4/events.py +69 -0
- clm/layer4/flux_gateway.py +133 -0
- clm/layer4/gateway.py +91 -0
- clm/layer4/loader.py +307 -0
- clm/layer4/mcard_commands.py +166 -0
- clm/layer4/membrane.py +273 -0
- clm/layer4/navigation.py +50 -0
- clm/layer4/protocol/protocol_entry_python.py +108 -0
- clm/layer4/protocol/python_sync.py +126 -0
- clm/layer4/runner.py +150 -0
- clm/layer4/satori.py +262 -0
- clm/layer4/server/python_sync_client.py +150 -0
- clm/layer4/server/python_sync_server.py +139 -0
- clm/layer4/server/service_api.py +315 -0
- clm/layer4/server/start_servers.py +107 -0
- clm/layer4/server/stop_servers.py +24 -0
- clm/layer4/simulated_optimization_fix.py +0 -0
- clm/layer4/storage.py +463 -0
- clm/layer4/tridb_admin.py +268 -0
- clm/layer4/websocket/test_ws_client.py +104 -0
- clm/layer4/websocket/test_ws_server.py +138 -0
- clm/layer4/websocket/ws_server_local.py +160 -0
- clm/layer5/__init__.py +51 -0
- clm/layer5/async_batch_writer.py +133 -0
- clm/layer5/learning.py +276 -0
- clm/layer5/telemetry_hook.py +107 -0
- clm/layer5/type_lattice.py +238 -0
- clm/py.typed +0 -0
- clm/schemas/__init__.py +652 -0
- clm/schemas/abstract_face_schema.yaml +77 -0
- clm/schemas/cel_schema.yaml +416 -0
- clm/schemas/lifecycle/__init__.py +45 -0
- clm/schemas/lifecycle/models.py +123 -0
- clm/schemas/lifecycle/service.py +364 -0
- clm/schemas/mcard_schema.sql +192 -0
- clm/schemas/mcard_vector_schema.sql +283 -0
- clm/schemas/mlp-context-v1.json +91 -0
- clm_kernel-0.0.0.dist-info/METADATA +121 -0
- clm_kernel-0.0.0.dist-info/RECORD +333 -0
- clm_kernel-0.0.0.dist-info/WHEEL +4 -0
- clm_kernel-0.0.0.dist-info/entry_points.txt +3 -0
- clm_kernel-0.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,576 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import re
|
|
3
|
+
|
|
4
|
+
import duckdb
|
|
5
|
+
|
|
6
|
+
from clm.cross_cutting.config.settings import settings
|
|
7
|
+
from clm.layer0.model.card import MCard
|
|
8
|
+
from clm.layer0.model.pagination import Page
|
|
9
|
+
from clm.layer2.engine.abstract_sql_engine import AbstractSqlEngine
|
|
10
|
+
from clm.layer2.engine.base import DatabaseConnection, resolve_db_path
|
|
11
|
+
|
|
12
|
+
DEFAULT_PAGE_SIZE = settings.pagination.default_page_size
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _convert_placeholders(sql: str) -> str:
|
|
18
|
+
"""Convert ``?`` placeholders to DuckDB's ``$1, $2, ...`` syntax."""
|
|
19
|
+
counter = 0
|
|
20
|
+
|
|
21
|
+
def _replacer(match):
|
|
22
|
+
nonlocal counter
|
|
23
|
+
counter += 1
|
|
24
|
+
return f"${counter}"
|
|
25
|
+
|
|
26
|
+
return re.sub(r"\?", _replacer, sql)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class DuckDBConnection(DatabaseConnection):
|
|
30
|
+
"""Database connection for DuckDB -- an embedded columnar OLAP database.
|
|
31
|
+
|
|
32
|
+
This mirrors SQLiteConnection but targets DuckDB, which excels at
|
|
33
|
+
analytical queries, Parquet I/O, and columnar scans. It provides
|
|
34
|
+
a drop-in alternative engine behind the same StorageEngine interface.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(self, db_path: str):
|
|
38
|
+
self.db_path = resolve_db_path(db_path)
|
|
39
|
+
self.conn: duckdb.DuckDBPyConnection | None = None
|
|
40
|
+
|
|
41
|
+
def connect(self):
|
|
42
|
+
"""Open the DuckDB connection and initialise schema."""
|
|
43
|
+
logger.debug(f"Connecting to DuckDB at {self.db_path}")
|
|
44
|
+
try:
|
|
45
|
+
self.conn = duckdb.connect(self.db_path)
|
|
46
|
+
logger.debug(f"Connection established to {self.db_path}")
|
|
47
|
+
|
|
48
|
+
# Check if the card table exists
|
|
49
|
+
result = self.conn.execute(
|
|
50
|
+
"SELECT COUNT(*) FROM information_schema.tables "
|
|
51
|
+
"WHERE table_name = 'card'"
|
|
52
|
+
).fetchone()
|
|
53
|
+
|
|
54
|
+
if result[0] == 0:
|
|
55
|
+
logger.debug(f"Creating new database schema at {self.db_path}")
|
|
56
|
+
self._create_schema()
|
|
57
|
+
logger.debug("Database schema created successfully")
|
|
58
|
+
else:
|
|
59
|
+
logger.debug(f"Using existing database at {self.db_path}")
|
|
60
|
+
|
|
61
|
+
except duckdb.Error as e:
|
|
62
|
+
logger.error(
|
|
63
|
+
f"Database error connecting to {self.db_path}: {e}", exc_info=True
|
|
64
|
+
)
|
|
65
|
+
raise
|
|
66
|
+
|
|
67
|
+
# =====================================================================
|
|
68
|
+
# Single Source of Truth: Schema files
|
|
69
|
+
# =====================================================================
|
|
70
|
+
# The DuckDB engine does NOT define its own schema. It loads all
|
|
71
|
+
# table / index definitions from the canonical SQL files via the
|
|
72
|
+
# MCardSchema singleton and applies only dialect-level transforms.
|
|
73
|
+
#
|
|
74
|
+
# Canonical source files:
|
|
75
|
+
# schema/mcard_schema.sql (REQUIRED -- core tables)
|
|
76
|
+
# schema/mcard_vector_schema.sql (optional -- vector/graph tables)
|
|
77
|
+
#
|
|
78
|
+
# If a new table is added to either file, this engine picks it up
|
|
79
|
+
# automatically. No hardcoded CREATE TABLE statements should ever
|
|
80
|
+
# appear in this file.
|
|
81
|
+
# =====================================================================
|
|
82
|
+
|
|
83
|
+
SCHEMA_SOURCE_FILES = (
|
|
84
|
+
"schema/mcard_schema.sql", # Required -- core tables
|
|
85
|
+
"schema/mcard_vector_schema.sql", # Optional -- vector/graph tables
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def _create_schema(self):
|
|
89
|
+
"""Create the MCard schema by loading from the canonical SQL files
|
|
90
|
+
and applying DuckDB-specific transformations.
|
|
91
|
+
|
|
92
|
+
The schema is loaded via ``MCardSchema`` (which reads
|
|
93
|
+
``schema/mcard_schema.sql`` and ``schema/mcard_vector_schema.sql``)
|
|
94
|
+
so that this engine stays in sync with the single source of truth.
|
|
95
|
+
|
|
96
|
+
DuckDB-specific overrides applied by ``_adapt_statement_for_duckdb``:
|
|
97
|
+
1. Skip ``CREATE VIRTUAL TABLE ... USING fts5(...)`` (unsupported)
|
|
98
|
+
2. ``INTEGER PRIMARY KEY AUTOINCREMENT`` -> sequence + ``nextval()``
|
|
99
|
+
3. ``TEXT`` -> ``VARCHAR`` (DuckDB preference)
|
|
100
|
+
4. Remove FK constraints from ``handle_history`` (DuckDB enforces
|
|
101
|
+
FKs on UPDATE which blocks handle pointer updates)
|
|
102
|
+
5. ``datetime('now')`` -> ``CURRENT_TIMESTAMP``
|
|
103
|
+
|
|
104
|
+
Raises:
|
|
105
|
+
FileNotFoundError: if the required core schema SQL file is missing.
|
|
106
|
+
RuntimeError: if no CREATE statements are loaded from the schema.
|
|
107
|
+
"""
|
|
108
|
+
from clm.schemas import MCardSchema, _find_schema_path
|
|
109
|
+
|
|
110
|
+
# Validate that the canonical schema file exists (raises FileNotFoundError)
|
|
111
|
+
schema_path = _find_schema_path()
|
|
112
|
+
logger.debug(f"DuckDB schema loading from canonical source: {schema_path}")
|
|
113
|
+
|
|
114
|
+
schema = MCardSchema.get_instance()
|
|
115
|
+
statements = schema.get_all_statements()
|
|
116
|
+
|
|
117
|
+
if not statements:
|
|
118
|
+
raise RuntimeError(
|
|
119
|
+
"No CREATE statements loaded from MCardSchema. "
|
|
120
|
+
f"Ensure {self.SCHEMA_SOURCE_FILES[0]} contains valid SQL."
|
|
121
|
+
)
|
|
122
|
+
logger.debug(
|
|
123
|
+
f"Loaded {len(statements)} schema statements from canonical SQL files"
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
sequences_created: set[str] = set()
|
|
127
|
+
|
|
128
|
+
for stmt in statements:
|
|
129
|
+
result = self._adapt_statement_for_duckdb(stmt, sequences_created)
|
|
130
|
+
if result is None:
|
|
131
|
+
# Statement should be skipped (e.g. FTS5 virtual table)
|
|
132
|
+
continue
|
|
133
|
+
seq_name, adapted_sql = result
|
|
134
|
+
# Create the sequence if this table needs one (AUTOINCREMENT)
|
|
135
|
+
if seq_name and seq_name not in sequences_created:
|
|
136
|
+
self.conn.execute(f"CREATE SEQUENCE IF NOT EXISTS {seq_name} START 1")
|
|
137
|
+
sequences_created.add(seq_name)
|
|
138
|
+
self.conn.execute(adapted_sql)
|
|
139
|
+
|
|
140
|
+
# Seed schema_version if not already present
|
|
141
|
+
self.conn.execute(
|
|
142
|
+
"""
|
|
143
|
+
INSERT INTO schema_version (version, applied_at, description)
|
|
144
|
+
SELECT '3.0.0', CURRENT_TIMESTAMP, 'DuckDB Monadic Core Schema'
|
|
145
|
+
WHERE NOT EXISTS (
|
|
146
|
+
SELECT 1 FROM schema_version WHERE version = '3.0.0'
|
|
147
|
+
)
|
|
148
|
+
"""
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
@staticmethod
|
|
152
|
+
def _adapt_statement_for_duckdb(stmt, sequences_created):
|
|
153
|
+
"""Transform a single SQLite CREATE statement for DuckDB.
|
|
154
|
+
|
|
155
|
+
Returns:
|
|
156
|
+
``None`` if the statement should be skipped entirely.
|
|
157
|
+
A tuple ``(seq_name, sql)`` where *seq_name* is the sequence
|
|
158
|
+
name to create (or ``None`` if no sequence is needed) and
|
|
159
|
+
*sql* is the adapted DuckDB-compatible statement.
|
|
160
|
+
"""
|
|
161
|
+
upper = stmt.upper()
|
|
162
|
+
|
|
163
|
+
# -- Skip unsupported constructs ---------------------------------
|
|
164
|
+
# FTS5 / vec0 virtual tables are SQLite-specific extensions
|
|
165
|
+
if "USING FTS5" in upper or "USING VEC0" in upper:
|
|
166
|
+
return None
|
|
167
|
+
# INSERT statements are already filtered by MCardSchema, but guard
|
|
168
|
+
if upper.strip().startswith("INSERT"):
|
|
169
|
+
return None
|
|
170
|
+
# Triggers are SQLite-specific, DuckDB doesn't support them natively
|
|
171
|
+
if upper.strip().startswith("CREATE TRIGGER"):
|
|
172
|
+
return None
|
|
173
|
+
# Standalone END/COMMIT (e.g. from trigger split or transaction)
|
|
174
|
+
if upper.strip() in ("END;", "END", "COMMIT;", "COMMIT"):
|
|
175
|
+
return None
|
|
176
|
+
|
|
177
|
+
seq_name = None
|
|
178
|
+
|
|
179
|
+
# -- AUTOINCREMENT -> sequence + nextval -------------------------
|
|
180
|
+
autoincrement_re = re.compile(
|
|
181
|
+
r"(\w+)\s+INTEGER\s+PRIMARY\s+KEY\s+AUTOINCREMENT",
|
|
182
|
+
re.IGNORECASE,
|
|
183
|
+
)
|
|
184
|
+
match = autoincrement_re.search(stmt)
|
|
185
|
+
if match:
|
|
186
|
+
col_name = match.group(1)
|
|
187
|
+
# Derive sequence name from the table name
|
|
188
|
+
table_match = re.search(
|
|
189
|
+
r"CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(\w+)",
|
|
190
|
+
stmt,
|
|
191
|
+
re.IGNORECASE,
|
|
192
|
+
)
|
|
193
|
+
table_name = table_match.group(1) if table_match else "unnamed"
|
|
194
|
+
seq_name = f"{table_name}_seq"
|
|
195
|
+
replacement = (
|
|
196
|
+
f"{col_name} INTEGER PRIMARY KEY DEFAULT nextval('{seq_name}')"
|
|
197
|
+
)
|
|
198
|
+
stmt = autoincrement_re.sub(replacement, stmt)
|
|
199
|
+
|
|
200
|
+
# -- TEXT -> VARCHAR ---------------------------------------------
|
|
201
|
+
stmt = re.sub(r"\bTEXT\b", "VARCHAR", stmt, flags=re.IGNORECASE)
|
|
202
|
+
|
|
203
|
+
# -- Remove FK constraints from handle_history -------------------
|
|
204
|
+
# DuckDB enforces FK constraints on UPDATE (not just DELETE),
|
|
205
|
+
# which blocks updating handle_registry.current_hash when
|
|
206
|
+
# handle_history references the handle. Integrity is
|
|
207
|
+
# maintained at the application layer instead.
|
|
208
|
+
if re.search(
|
|
209
|
+
r"CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?handle_history\b",
|
|
210
|
+
stmt,
|
|
211
|
+
re.IGNORECASE,
|
|
212
|
+
):
|
|
213
|
+
stmt = re.sub(
|
|
214
|
+
r",\s*FOREIGN\s+KEY\s*\([^)]+\)\s*REFERENCES\s+\w+\s*\([^)]+\)",
|
|
215
|
+
"",
|
|
216
|
+
stmt,
|
|
217
|
+
flags=re.IGNORECASE,
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
# -- datetime('now') -> CURRENT_TIMESTAMP ------------------------
|
|
221
|
+
stmt = stmt.replace("datetime('now')", "CURRENT_TIMESTAMP")
|
|
222
|
+
|
|
223
|
+
return (seq_name, stmt)
|
|
224
|
+
|
|
225
|
+
# =====================================================================
|
|
226
|
+
# Connection lifecycle
|
|
227
|
+
# =====================================================================
|
|
228
|
+
|
|
229
|
+
def disconnect(self):
|
|
230
|
+
if self.conn:
|
|
231
|
+
self.conn.close()
|
|
232
|
+
self.conn = None
|
|
233
|
+
|
|
234
|
+
def commit(self):
|
|
235
|
+
# DuckDB auto-commits by default; explicit commit for consistency
|
|
236
|
+
if self.conn:
|
|
237
|
+
self.conn.commit()
|
|
238
|
+
|
|
239
|
+
def rollback(self):
|
|
240
|
+
if self.conn:
|
|
241
|
+
self.conn.rollback()
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
class DuckDBEngine(AbstractSqlEngine):
|
|
245
|
+
"""Storage engine implementation using DuckDB.
|
|
246
|
+
|
|
247
|
+
Provides the same StorageEngine interface as SQLiteEngine but uses
|
|
248
|
+
DuckDB as the underlying database. DuckDB excels at columnar scans,
|
|
249
|
+
analytical queries, and cross-format I/O (Parquet, CSV, JSON).
|
|
250
|
+
"""
|
|
251
|
+
|
|
252
|
+
def __init__(self, connection: DuckDBConnection):
|
|
253
|
+
self.connection = connection
|
|
254
|
+
self.connection.connect()
|
|
255
|
+
|
|
256
|
+
def __del__(self):
|
|
257
|
+
self.connection.disconnect()
|
|
258
|
+
|
|
259
|
+
def __enter__(self):
|
|
260
|
+
return self
|
|
261
|
+
|
|
262
|
+
def __exit__(self, exc_type, exc_val, _exc_tb):
|
|
263
|
+
self.connection.disconnect()
|
|
264
|
+
return False
|
|
265
|
+
|
|
266
|
+
# =====================================================================
|
|
267
|
+
# AbstractSqlEngine primitives
|
|
268
|
+
# =====================================================================
|
|
269
|
+
|
|
270
|
+
def _query_rows(self, sql: str, params: tuple = ()) -> list[dict]:
|
|
271
|
+
ddb_sql = _convert_placeholders(sql)
|
|
272
|
+
rows = self.connection.conn.execute(ddb_sql, list(params)).fetchall()
|
|
273
|
+
# Get column names from the result description
|
|
274
|
+
desc = self.connection.conn.description
|
|
275
|
+
if not desc:
|
|
276
|
+
return []
|
|
277
|
+
columns = [d[0] for d in desc]
|
|
278
|
+
return [dict(zip(columns, row, strict=False)) for row in rows]
|
|
279
|
+
|
|
280
|
+
def _exec_sql(self, sql: str, params: tuple = ()) -> int:
|
|
281
|
+
ddb_sql = _convert_placeholders(sql)
|
|
282
|
+
# DuckDB doesn't expose rowcount directly; pre-count for DELETEs
|
|
283
|
+
upper = sql.strip().upper()
|
|
284
|
+
if upper.startswith("DELETE"):
|
|
285
|
+
# Extract the WHERE clause to count affected rows
|
|
286
|
+
# Parse table and condition from DELETE FROM <table> WHERE <cond>
|
|
287
|
+
match = re.match(
|
|
288
|
+
r"DELETE\s+FROM\s+(\S+)(?:\s+WHERE\s+(.+))?",
|
|
289
|
+
sql.strip(),
|
|
290
|
+
re.IGNORECASE | re.DOTALL,
|
|
291
|
+
)
|
|
292
|
+
if match:
|
|
293
|
+
table = match.group(1)
|
|
294
|
+
where = match.group(2)
|
|
295
|
+
if where:
|
|
296
|
+
count_sql = _convert_placeholders(
|
|
297
|
+
f"SELECT COUNT(*) FROM {table} WHERE {where}" # nosec B608
|
|
298
|
+
)
|
|
299
|
+
count = self.connection.conn.execute(
|
|
300
|
+
count_sql, list(params)
|
|
301
|
+
).fetchone()[0]
|
|
302
|
+
else:
|
|
303
|
+
count = self.connection.conn.execute(
|
|
304
|
+
f"SELECT COUNT(*) FROM {table}" # nosec B608
|
|
305
|
+
).fetchone()[0]
|
|
306
|
+
self.connection.conn.execute(ddb_sql, list(params))
|
|
307
|
+
return count
|
|
308
|
+
self.connection.conn.execute(ddb_sql, list(params))
|
|
309
|
+
return 0
|
|
310
|
+
|
|
311
|
+
def _ensure_handle_tables(self) -> None:
|
|
312
|
+
"""Ensure handle tables exist (they're created in _create_schema)."""
|
|
313
|
+
result = self.connection.conn.execute(
|
|
314
|
+
"SELECT COUNT(*) FROM information_schema.tables "
|
|
315
|
+
"WHERE table_name = 'handle_registry'"
|
|
316
|
+
).fetchone()
|
|
317
|
+
if result[0] == 0:
|
|
318
|
+
self.connection._create_schema()
|
|
319
|
+
logger.debug("Handle tables ensured.")
|
|
320
|
+
|
|
321
|
+
def _ensure_tombstone_table(self) -> None:
|
|
322
|
+
"""Ensure card_tombstone table exists."""
|
|
323
|
+
result = self.connection.conn.execute(
|
|
324
|
+
"SELECT COUNT(*) FROM information_schema.tables "
|
|
325
|
+
"WHERE table_name = 'card_tombstone'"
|
|
326
|
+
).fetchone()
|
|
327
|
+
if result[0] == 0:
|
|
328
|
+
self.connection.conn.execute(
|
|
329
|
+
"""
|
|
330
|
+
CREATE TABLE IF NOT EXISTS card_tombstone (
|
|
331
|
+
hash VARCHAR PRIMARY KEY,
|
|
332
|
+
tombstoned_at TIMESTAMP NOT NULL,
|
|
333
|
+
reason VARCHAR DEFAULT 'DELETED'
|
|
334
|
+
)
|
|
335
|
+
"""
|
|
336
|
+
)
|
|
337
|
+
logger.debug("Tombstone table ensured.")
|
|
338
|
+
|
|
339
|
+
@classmethod
|
|
340
|
+
def mount_sqlite_replica(cls, sqlite_path: str) -> "DuckDBEngine":
|
|
341
|
+
"""Mount an analytical DuckDB read-replica over an existing SQLite CAS database.
|
|
342
|
+
|
|
343
|
+
Allows high-throughput vectorized OLAP queries directly over the immutable CAS file.
|
|
344
|
+
"""
|
|
345
|
+
conn = DuckDBConnection(":memory:")
|
|
346
|
+
conn.connect()
|
|
347
|
+
conn.conn.execute(f"ATTACH '{sqlite_path}' AS sqlite_cas (TYPE SQLITE)")
|
|
348
|
+
return cls(conn)
|
|
349
|
+
|
|
350
|
+
# =====================================================================
|
|
351
|
+
# Card Operations (engine-specific)
|
|
352
|
+
# =====================================================================
|
|
353
|
+
|
|
354
|
+
def add(self, card: MCard) -> str:
|
|
355
|
+
hash_value = str(card.hash)
|
|
356
|
+
self._ensure_tombstone_table()
|
|
357
|
+
# If previously tombstoned, untombstone
|
|
358
|
+
is_tombstoned = self.connection.conn.execute(
|
|
359
|
+
"SELECT 1 FROM card_tombstone WHERE hash = $1", [hash_value]
|
|
360
|
+
).fetchone()
|
|
361
|
+
if is_tombstoned:
|
|
362
|
+
self.connection.conn.execute(
|
|
363
|
+
"DELETE FROM card_tombstone WHERE hash = $1", [hash_value]
|
|
364
|
+
)
|
|
365
|
+
return hash_value
|
|
366
|
+
|
|
367
|
+
try:
|
|
368
|
+
content_bytes = (
|
|
369
|
+
card.content
|
|
370
|
+
if isinstance(card.content, bytes)
|
|
371
|
+
else card.content.encode("utf-8")
|
|
372
|
+
)
|
|
373
|
+
self.connection.conn.execute(
|
|
374
|
+
"INSERT INTO card (hash, content, g_time) VALUES ($1, $2, $3)",
|
|
375
|
+
[hash_value, content_bytes, str(card.g_time)],
|
|
376
|
+
)
|
|
377
|
+
logger.debug(f"Added card with hash {hash_value}")
|
|
378
|
+
return hash_value
|
|
379
|
+
except duckdb.ConstraintException as e:
|
|
380
|
+
raise ValueError(
|
|
381
|
+
f"Card with hash {hash_value} and {str(card.g_time)} already exists, "
|
|
382
|
+
f"\n Content: {card.content[:20]}"
|
|
383
|
+
) from e
|
|
384
|
+
|
|
385
|
+
def get(self, hash_value: str) -> MCard | None:
|
|
386
|
+
self._ensure_tombstone_table()
|
|
387
|
+
result = self.connection.conn.execute(
|
|
388
|
+
"""
|
|
389
|
+
SELECT c.content, c.g_time, c.hash
|
|
390
|
+
FROM card c
|
|
391
|
+
LEFT JOIN card_tombstone t ON c.hash = t.hash
|
|
392
|
+
WHERE c.hash = $1 AND t.hash IS NULL
|
|
393
|
+
""",
|
|
394
|
+
[str(hash_value)],
|
|
395
|
+
).fetchone()
|
|
396
|
+
|
|
397
|
+
if not result:
|
|
398
|
+
return None
|
|
399
|
+
|
|
400
|
+
content, g_time, hash_val = result
|
|
401
|
+
return self._row_to_card(content, hash_val, g_time)
|
|
402
|
+
|
|
403
|
+
def delete(self, hash_value: str) -> bool:
|
|
404
|
+
"""Tombstones a card to preserve G-Set CRDT immortality (INV-REF-03).
|
|
405
|
+
|
|
406
|
+
No row is deleted from the `card` CAS table.
|
|
407
|
+
"""
|
|
408
|
+
self._ensure_tombstone_table()
|
|
409
|
+
exists = self.connection.conn.execute(
|
|
410
|
+
"SELECT 1 FROM card WHERE hash = $1", [str(hash_value)]
|
|
411
|
+
).fetchone()
|
|
412
|
+
if not exists:
|
|
413
|
+
return False
|
|
414
|
+
|
|
415
|
+
already_tombstoned = self.connection.conn.execute(
|
|
416
|
+
"SELECT 1 FROM card_tombstone WHERE hash = $1", [str(hash_value)]
|
|
417
|
+
).fetchone()
|
|
418
|
+
if already_tombstoned:
|
|
419
|
+
return False
|
|
420
|
+
|
|
421
|
+
self.connection.conn.execute(
|
|
422
|
+
"INSERT INTO card_tombstone (hash, tombstoned_at, reason) VALUES ($1, CURRENT_TIMESTAMP, 'DELETED')",
|
|
423
|
+
[str(hash_value)],
|
|
424
|
+
)
|
|
425
|
+
|
|
426
|
+
self._ensure_handle_tables()
|
|
427
|
+
handles = self.connection.conn.execute(
|
|
428
|
+
"SELECT handle FROM handle_registry WHERE current_hash = $1",
|
|
429
|
+
[str(hash_value)],
|
|
430
|
+
).fetchall()
|
|
431
|
+
for (handle,) in handles:
|
|
432
|
+
self.connection.conn.execute(
|
|
433
|
+
"INSERT INTO handle_history (handle, previous_hash, changed_at, change_type) VALUES ($1, $2, CURRENT_TIMESTAMP, 'TOMBSTONE')",
|
|
434
|
+
[handle, str(hash_value)],
|
|
435
|
+
)
|
|
436
|
+
self.connection.conn.execute(
|
|
437
|
+
"DELETE FROM handle_registry WHERE handle = $1", [handle]
|
|
438
|
+
)
|
|
439
|
+
|
|
440
|
+
return True
|
|
441
|
+
|
|
442
|
+
def search_by_string(
|
|
443
|
+
self,
|
|
444
|
+
search_string: str,
|
|
445
|
+
page_number: int = 1,
|
|
446
|
+
page_size: int = DEFAULT_PAGE_SIZE,
|
|
447
|
+
) -> Page:
|
|
448
|
+
"""Search cards by string in content, hash, or g_time."""
|
|
449
|
+
if page_number < 1:
|
|
450
|
+
raise ValueError("Page number must be >= 1")
|
|
451
|
+
if page_size < 1:
|
|
452
|
+
raise ValueError("Page size must be >= 1")
|
|
453
|
+
|
|
454
|
+
self._ensure_tombstone_table()
|
|
455
|
+
offset = (page_number - 1) * page_size
|
|
456
|
+
pattern = f"%{search_string}%"
|
|
457
|
+
|
|
458
|
+
total_items = self.connection.conn.execute(
|
|
459
|
+
"""
|
|
460
|
+
SELECT COUNT(*) FROM card c
|
|
461
|
+
LEFT JOIN card_tombstone t ON c.hash = t.hash
|
|
462
|
+
WHERE t.hash IS NULL AND (c.hash LIKE $1 OR c.g_time LIKE $2 OR CAST(c.content AS VARCHAR) LIKE $3)
|
|
463
|
+
""",
|
|
464
|
+
[pattern, pattern, pattern],
|
|
465
|
+
).fetchone()[0]
|
|
466
|
+
|
|
467
|
+
rows = self.connection.conn.execute(
|
|
468
|
+
"""
|
|
469
|
+
SELECT c.content, c.g_time, c.hash FROM card c
|
|
470
|
+
LEFT JOIN card_tombstone t ON c.hash = t.hash
|
|
471
|
+
WHERE t.hash IS NULL AND (c.hash LIKE $1 OR c.g_time LIKE $2 OR CAST(c.content AS VARCHAR) LIKE $3)
|
|
472
|
+
ORDER BY c.g_time DESC LIMIT $4 OFFSET $5
|
|
473
|
+
""",
|
|
474
|
+
[pattern, pattern, pattern, page_size, offset],
|
|
475
|
+
).fetchall()
|
|
476
|
+
|
|
477
|
+
items = [
|
|
478
|
+
self._row_to_card(content, hash_val, g_time)
|
|
479
|
+
for content, g_time, hash_val in rows
|
|
480
|
+
]
|
|
481
|
+
return Page.create(items, total_items, page_number, page_size)
|
|
482
|
+
|
|
483
|
+
def search_by_content(
|
|
484
|
+
self,
|
|
485
|
+
search_string: str | bytes,
|
|
486
|
+
page_number: int = 1,
|
|
487
|
+
page_size: int = DEFAULT_PAGE_SIZE,
|
|
488
|
+
) -> Page:
|
|
489
|
+
"""Search cards by content pattern."""
|
|
490
|
+
if page_number < 1:
|
|
491
|
+
raise ValueError("Page number must be >= 1")
|
|
492
|
+
if page_size < 1:
|
|
493
|
+
raise ValueError("Page size must be >= 1")
|
|
494
|
+
if not search_string:
|
|
495
|
+
raise ValueError("Search string cannot be empty")
|
|
496
|
+
|
|
497
|
+
self._ensure_tombstone_table()
|
|
498
|
+
offset = (page_number - 1) * page_size
|
|
499
|
+
|
|
500
|
+
if isinstance(search_string, str):
|
|
501
|
+
search_text = search_string
|
|
502
|
+
else:
|
|
503
|
+
search_text = search_string.decode("utf-8", errors="replace")
|
|
504
|
+
|
|
505
|
+
# DuckDB: position() only works with VARCHAR, so cast BLOB content
|
|
506
|
+
pattern = f"%{search_text}%"
|
|
507
|
+
total_items = self.connection.conn.execute(
|
|
508
|
+
"""
|
|
509
|
+
SELECT COUNT(*) FROM card c
|
|
510
|
+
LEFT JOIN card_tombstone t ON c.hash = t.hash
|
|
511
|
+
WHERE t.hash IS NULL AND CAST(c.content AS VARCHAR) LIKE $1
|
|
512
|
+
""",
|
|
513
|
+
[pattern],
|
|
514
|
+
).fetchone()[0]
|
|
515
|
+
|
|
516
|
+
rows = self.connection.conn.execute(
|
|
517
|
+
"""
|
|
518
|
+
SELECT c.content, c.g_time, c.hash FROM card c
|
|
519
|
+
LEFT JOIN card_tombstone t ON c.hash = t.hash
|
|
520
|
+
WHERE t.hash IS NULL AND CAST(c.content AS VARCHAR) LIKE $1
|
|
521
|
+
ORDER BY c.g_time DESC
|
|
522
|
+
LIMIT $2 OFFSET $3
|
|
523
|
+
""",
|
|
524
|
+
[pattern, page_size, offset],
|
|
525
|
+
).fetchall()
|
|
526
|
+
|
|
527
|
+
items = [
|
|
528
|
+
self._row_to_card(content, hash_val, g_time)
|
|
529
|
+
for content, g_time, hash_val in rows
|
|
530
|
+
]
|
|
531
|
+
return Page.create(items, total_items, page_number, page_size)
|
|
532
|
+
|
|
533
|
+
def count(self) -> int:
|
|
534
|
+
self._ensure_tombstone_table()
|
|
535
|
+
return self.connection.conn.execute(
|
|
536
|
+
"""
|
|
537
|
+
SELECT COUNT(*) FROM card c
|
|
538
|
+
LEFT JOIN card_tombstone t ON c.hash = t.hash
|
|
539
|
+
WHERE t.hash IS NULL
|
|
540
|
+
"""
|
|
541
|
+
).fetchone()[0]
|
|
542
|
+
|
|
543
|
+
def get_cards_by_page(
|
|
544
|
+
self, page_number: int = 1, page_size: int = DEFAULT_PAGE_SIZE
|
|
545
|
+
) -> Page:
|
|
546
|
+
"""Get a page of cards."""
|
|
547
|
+
if page_number < 1:
|
|
548
|
+
raise ValueError("Page number must be >= 1")
|
|
549
|
+
if page_size < 1:
|
|
550
|
+
raise ValueError("Page size must be >= 1")
|
|
551
|
+
|
|
552
|
+
self._ensure_tombstone_table()
|
|
553
|
+
total_items = self.connection.conn.execute(
|
|
554
|
+
"""
|
|
555
|
+
SELECT COUNT(*) FROM card c
|
|
556
|
+
LEFT JOIN card_tombstone t ON c.hash = t.hash
|
|
557
|
+
WHERE t.hash IS NULL
|
|
558
|
+
"""
|
|
559
|
+
).fetchone()[0]
|
|
560
|
+
|
|
561
|
+
offset = (page_number - 1) * page_size
|
|
562
|
+
rows = self.connection.conn.execute(
|
|
563
|
+
"""
|
|
564
|
+
SELECT c.content, c.g_time, c.hash FROM card c
|
|
565
|
+
LEFT JOIN card_tombstone t ON c.hash = t.hash
|
|
566
|
+
WHERE t.hash IS NULL
|
|
567
|
+
ORDER BY c.g_time DESC LIMIT $1 OFFSET $2
|
|
568
|
+
""",
|
|
569
|
+
[page_size, offset],
|
|
570
|
+
).fetchall()
|
|
571
|
+
|
|
572
|
+
items = [
|
|
573
|
+
self._row_to_card(content, hash_val, g_time)
|
|
574
|
+
for content, g_time, hash_val in rows
|
|
575
|
+
]
|
|
576
|
+
return Page.create(items, total_items, page_number, page_size)
|