|
| 1 | +Advanced Usage |
| 2 | +============== |
| 3 | + |
| 4 | +This section describes advanced configuration options of the YDB SQLAlchemy dialect. |
| 5 | + |
| 6 | +YQL Statement Prefixes |
| 7 | +---------------------- |
| 8 | + |
| 9 | +You can prepend one or more YQL fragments (for example, ``PRAGMA`` directives) to every executed query. This is useful to set session-level behavior such as ``PRAGMA DistinctOverKeys;`` or other YQL pragmas without modifying application SQL. |
| 10 | + |
| 11 | +The dialect option ``_statement_prefixes_list`` accepts a list of strings. Each string is prepended to the statement on a separate line, in order. Pass it to :func:`sqlalchemy.create_engine`; the argument is forwarded to the dialect. |
| 12 | + |
| 13 | +.. code-block:: python |
| 14 | +
|
| 15 | + import sqlalchemy as sa |
| 16 | +
|
| 17 | + engine = sa.create_engine( |
| 18 | + "yql+ydb://localhost:2136/local", |
| 19 | + _statement_prefixes_list=["PRAGMA DistinctOverKeys;", "PRAGMA Bar;"], |
| 20 | + ) |
| 21 | + with engine.connect() as conn: |
| 22 | + conn.execute(sa.text("SELECT 1 AS value")) # runs with prefixes prepended |
| 23 | +
|
| 24 | +When ``_statement_prefixes_list`` is omitted or empty, statements are executed unchanged. |
| 25 | + |
| 26 | +Explicit DECLARE for query parameters |
| 27 | +------------------------------------ |
| 28 | + |
| 29 | +The dialect option ``_add_declare_for_yql_stmt_vars`` (default ``False``) prepends explicit ``DECLARE`` statements for each bound parameter at the beginning of the query, e.g. ``DECLARE `$id` as Int64;``. Many YDB installations still require this form; without it, parameterized queries may fail. |
| 30 | + |
| 31 | +Pass ``_add_declare_for_yql_stmt_vars=True`` to :func:`sqlalchemy.create_engine`: |
| 32 | + |
| 33 | +.. code-block:: python |
| 34 | +
|
| 35 | + import sqlalchemy as sa |
| 36 | +
|
| 37 | + engine = sa.create_engine( |
| 38 | + "yql+ydb://localhost:2136/local", |
| 39 | + _add_declare_for_yql_stmt_vars=True, |
| 40 | + ) |
| 41 | + with engine.connect() as conn: |
| 42 | + conn.execute(sa.text("SELECT :id"), {"id": 1}) # runs as "DECLARE `$id` as Int64;\nSELECT $id" with param |
0 commit comments