SQLCommenter#
SQLCommenter formatting, context management, and query comment injection.
Context and Attributes#
- class sqlspec.core.sqlcommenter.SQLCommenterContext[source]#
Bases:
objectRequest-scoped storage for sqlcommenter attributes via contextvars.
Framework middlewares set attributes per-request, and the sqlcommenter statement transformer reads them at compile time.
Functions#
- sqlspec.core.sqlcommenter.generate_comment(attrs)[source]#
Serialize attributes into a sqlcommenter comment body.
- sqlspec.core.sqlcommenter.append_comment(expression, attrs)[source]#
Add sqlcommenter attributes as a comment on a parsed expression.
Uses sqlglot's
add_comments()API so the comment coexists with existing comments and optimizer hints.
- sqlspec.core.sqlcommenter.parse_comment(expression)[source]#
Extract sqlcommenter attributes from a parsed expression's comments.
Identifies sqlcommenter comments by their
key='value'structure, extracts the attributes, and removes the sqlcommenter comment from the expression while preserving other comments.
- sqlspec.core.sqlcommenter.create_sqlcommenter_statement_transformer(*, attributes=None, enable_traceparent=False, enable_context=False)[source]#
Create a
statement_transformerthat adds sqlcommenter comments to the AST.Static attributes are pre-serialized at creation time. When
enable_traceparentorenable_contextis True, dynamic attributes are resolved per invocation.- Parameters:
attributes¶ (
dict[str,str|None] |None) -- Static key-value pairs to include in every comment.enable_traceparent¶ (
bool) -- If True, auto-populatetraceparentfrom the current OpenTelemetry span context on each invocation.enable_context¶ (
bool) -- If True, read request-scoped attributes fromSQLCommenterContextand merge them with static attributes.
- Return type:
- Returns:
A callable suitable for
StatementConfig(statement_transformers=[...]).