Statements
Import Statement from polynom.statement. Its constructor takes language, statement, optional values, and optional namespace. It holds a query and its parameters independently of a session.
| Method | Behavior |
|---|---|
execute(cursor) |
Delegate to the Python connector’s cursor.executeany(). Fetch results and control the transaction through the cursor and its connection. |
dump() |
Return one statement prefixed by a language and namespace marker, such as /*sql@public*/. SQL parameters are rendered as literals for the export. |
log(app_uuid) |
Write the dumped statement to the named application’s log. An empty or omitted UUID raises ValueError. |
Use bound values for SQL data. dump() uses simple placeholder substitution for its text output. It is intended for generated statements and does not parse arbitrary SQL or handle every value representation. PolyNOM uses the internal Session._execute() method for its own operations. For direct query execution supported by the connector, use Statement.execute(cursor) or call the connector itself. Python connector guide
get_generator_for_data_model(data_model) selects the generator PolyNOM uses internally. In 0.4.0 it returns a SQL generator for DataModel.RELATIONAL and raises NotImplementedError for the document and graph enum members.
Logging
Enable log_statements=True on an application to record schema statements and session statements such as model inserts, updates, and deletes. Model changes routed through a session are logged on commit. Schema operations can log their SQL as they execute, so the file is a record of statements, with transaction behavior depending on the operation. Query builder reads are not comprehensive statement audit events.
The default output is statements_<app_uuid>.log. PolyNOM uses STATEMENT_LOG_FILE_NAME to derive the filename and adds the UUID before the extension. Logs include serialized values. LoggerFactory.get_logger(app_uuid) in polynom.statement_logger provides the per-application logger, and InfiniteRotatingFileHandler handles rollover while retaining old files.
For a database change log, pass log_user to Session. When the session flushes changes to tracked fields, PolyNOM records the application UUID, entry ID, namespace, entity name, user label, timestamp, and old and new field values. The records follow the session’s commit or rollback. The ChangeLog model in polynom.reflection maps to polynom_internal.change_log. Filter by app_uuid to read one application’s entries. The SchemaSnapshot model maps to PolyNOM’s internal schema snapshot table.
Export and restore data
Call Application.dump(file_path) and Application.load(file_path) inside an active application. The dump begins with the format version, the application UUID, and its recorded schema definitions. It writes namespace and table definitions for registered schemas, followed by inserts for the stored rows. The schema snapshot table itself is omitted. Change-log entries are limited to this application UUID.
Loading checks the header and application UUID, then replaces the tables managed by those schemas with statements from the file. Use a dedicated database or dedicate the managed namespaces to the application. Loading can drop managed namespaces and their contents. The public and internal namespaces are protected from being dropped as namespaces. Managed tables in public can still be replaced, and the loader clears this application’s change-log rows. The restore executes commands from the dump, so load only trusted files.
The loader rejects recognized snapshot differences by default. Setting migrate=True allows it to accept a differing dump schema, but the loader replays the dump statements without reconciling them to the current models. The importer reads one marked statement per line and logs individual execution failures before continuing. Check its logs and verify the restored data after loading.
Try a round trip
This script inserts a row, exports it to a temporary file, deletes it, and restores it. It uses a disposable namespace and the same environment variables as the getting started guide. It prints Notebook, then 1 from a direct SQL statement.
from contextlib import closing
from os import getenv
from pathlib import Path
from tempfile import TemporaryDirectory
from uuid import uuid4
import polypheny
from polynom.application import Application
from polynom.model.model import BaseModel
from polynom.schema.field import Field
from polynom.schema.polytypes import VarChar
from polynom.schema.schema import BaseSchema
from polynom.schema.schema_registry import polynom_schema
from polynom.session import Session
from polynom.statement import Statement
address = (getenv("POLYPHENY_HOST", "127.0.0.1"), int(getenv("POLYPHENY_PORT", "20590")))
user = getenv("POLYPHENY_USER", "pa")
password = getenv("POLYPHENY_PASSWORD", "")
app_id = str(uuid4())
namespace = f"polynom_dump_{uuid4().hex}"
@polynom_schema
class ItemSchema(BaseSchema):
namespace_name = namespace
entity_name = "items"
fields = [Field("label", VarChar(80), nullable=False)]
class Item(BaseModel):
schema = ItemSchema()
def __init__(self, label, _entry_id=None):
super().__init__(_entry_id)
self.label = label
with closing(polypheny.connect(address, username=user, password=password, transport="plain")) as connection:
try:
with Application(app_id, address, user=user, password=password) as app, TemporaryDirectory() as directory:
file_path = Path(directory) / "items.sql"
with Session(app) as session:
item = Item("Notebook")
session.add(item)
item_id = item._entry_id
session.commit()
app.dump(file_path)
with Session(app) as session:
session.delete(Item.query(session).get(item_id))
session.commit()
app.load(file_path)
with Session(app) as session:
restored = Item.query(session).get(item_id)
print(restored.label)
with closing(connection.cursor()) as cursor:
Statement("sql", "SELECT 1").execute(cursor)
print(cursor.fetchone()[0])
finally:
with closing(connection.cursor()) as cursor:
cursor.execute(f'DROP NAMESPACE IF EXISTS "{namespace}"')
cursor.execute(
'DELETE FROM "polynom_internal"."snapshot" WHERE "_entry_id" = ?',
(app_id,),
)
connection.commit()