compiler
Turns SQLAlchemy statements into SQL text plus positional arguments that a native async driver can run directly, skipping SQLAlchemy's execution layer.
SQLAlchemy still builds and compiles every statement; this module reuses its compiled output. A compiled statement holds its SQL with the driver's placeholders and the names of its bind parameters in placeholder order, so running it natively means looking each value up by name in that order::
| Text Only | |
|---|---|
1 2 3 4 | |
Compiling is the expensive part, so compiled statements are cached per statement shape and only the values are bound on each call.
BoundBatch
Bases: NamedTuple
One statement ready to run once per row with the driver's
executemany: the shared SQL and one argument list per row::
| Text Only | |
|---|---|
1 2 | |
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
162 163 164 165 166 167 168 169 170 171 172 173 | |
BoundStatement
Bases: NamedTuple
One statement ready to send to the driver: the plan of its shape, the final SQL, the positional arguments, and the named parameters they came from (kept so a primary key the caller bound can be returned as is)::
| Text Only | |
|---|---|
1 2 3 | |
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | |
DefaultContext
Stand-in for SQLAlchemy's execution context, passed to Python column defaults that take a context argument.
SQLAlchemy calls such defaults with its execution context; the native path has none, so this offers what those defaults use, the statement's current parameters and the column::
| Text Only | |
|---|---|
1 2 3 4 5 | |
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | |
__init__(params, column)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
MutableMapping[str, Any]
|
bound parameters of the statement being executed |
required |
column
|
Any
|
column whose default is being computed |
required |
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
192 193 194 195 196 197 198 199 200 | |
get_current_parameters(isolate_multiinsert_groups=True)
Return the parameters of the statement being executed, like
SQLAlchemy's DefaultExecutionContext.get_current_parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
isolate_multiinsert_groups
|
bool
|
kept for signature compatibility |
True
|
Returns:
| Type | Description |
|---|---|
MutableMapping[str, Any]
|
bound parameters keyed by column key |
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
202 203 204 205 206 207 208 209 210 211 212 213 214 | |
NativeCompiler
Turns statements into BoundStatement / BoundBatch objects for one
database dialect.
Compiling is the costly step, so plans are kept in an LRU cache keyed by SQLAlchemy's statement cache key, which is equal for all statements of one shape whatever their values. On a hit only the new values are bound::
| Text Only | |
|---|---|
1 2 | |
Statements SQLAlchemy cannot cache (no cache key, e.g. every INSERT with
ON CONFLICT / ON DUPLICATE KEY) are compiled every time, except
ormar's write templates (marked with the TEMPLATE_OPTION execution
option): they are the same object on every call, so they keep their plan
per statement object in a second LRU cache of the same size.
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 | |
__init__(dialect, max_plans=2048)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dialect
|
Dialect
|
dialect of the database the statements run on |
required |
max_plans
|
int
|
number of compiled statement shapes kept in memory |
2048
|
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
241 242 243 244 245 246 247 248 249 250 251 252 253 254 | |
bind(stmt, params=None)
Compile the statement, or reuse the plan of its shape, and bind its values into SQL and positional driver arguments.
The values come from the statement's own cache key, which carries the bound values of this particular statement::
| Text Only | |
|---|---|
1 2 | |
params supplies values by bind name instead. ormar's cached query
templates use it: one statement built once with named slots, and only
the values passed on each call::
| Text Only | |
|---|---|
1 2 | |
When binds_directly allows it, those values go to the driver
without SQLAlchemy's binding steps (see direct_args).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stmt
|
Executable
|
statement to execute |
required |
params
|
Optional[Mapping[str, Any]]
|
values for named bind parameters, by name |
None
|
Returns:
| Type | Description |
|---|---|
BoundStatement
|
plan, SQL string and positional driver arguments |
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 | |
bind_many(stmt, rows)
Compile a statement with named bindparam placeholders, or reuse its
plan, and bind one set of values per row for executemany::
| Text Only | |
|---|---|
1 2 3 | |
Like bind, rows that binds_directly accepts skip SQLAlchemy's
binding steps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stmt
|
Executable
|
statement with |
required |
rows
|
Sequence[Mapping[str, Any]]
|
parameter values per row, keyed by bind parameter name |
required |
Returns:
| Type | Description |
|---|---|
BoundBatch
|
plan, SQL string and positional driver arguments per row |
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 | |
NativeRow
Bases: dict
A result row of native execution: a dict keyed by result label, which is how ormar reads rows.
It also accepts the selected column objects as keys, like SQLAlchemy's
RowMapping does, so code indexing rows that way keeps working::
| Text Only | |
|---|---|
1 2 | |
Each plan builds its own subclass (row_class_for) whose
object_keys maps the selected column objects to their labels.
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | |
__missing__(key)
Called by dict lookup when the key is not a label: treat the key as a
selected column object (row[users.c.name]) and return its value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Any
|
column object (or unknown key) |
required |
Returns:
| Type | Description |
|---|---|
Any
|
value of the matching result column |
Raises:
| Type | Description |
|---|---|
KeyError
|
when the key is not a selected column |
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | |
StatementPlan
Everything needed to run one statement shape natively, worked out once when the shape is first compiled and reused by every later execution.
select(users.c.id).where(users.c.id == 5) and the same query with 7
have one shape, so they share one plan; only their bound values differ.
It holds the compiled statement, the result labels and types used to build
rows, and fallback: True for statements that must run through
SQLAlchemy instead (plain text without result columns, duplicate result
labels, or column defaults that have to run in the database first).
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | |
__init__(compiled)
Build the plan from a statement compiled with its cache key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compiled
|
SQLCompiler
|
statement compiled for the target dialect |
required |
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | |
apply_prefetch_defaults(compiled, params)
Fill the values of execution-time column defaults into the bound parameters, which SQLAlchemy's execution context does on its own path.
Constants are copied, callables are called (with a DefaultContext)::
| Text Only | |
|---|---|
1 2 3 | |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compiled
|
SQLCompiler
|
compiled statement |
required |
params
|
MutableMapping[str, Any]
|
bound parameters, updated in place |
required |
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 | |
binds_directly(compiled, row)
Return whether values given by bind name can go to the driver as they
are, skipping SQLAlchemy's construct_params and expand.
Binding attaches the values to the placeholders of the compiled SQL. The SQL and the values travel to the driver separately, which keeps values out of the SQL text and lets the database reuse one prepared statement::
| Text Only | |
|---|---|
1 2 3 | |
SQLAlchemy's binding (construct_params plus expand) does five
things:
- collects the values by bind name, e.g.
{"id_1": 7} - fills in column defaults run at execution time (
default=) - expands
INlists, rewriting the SQL:IN ($1)with[1, 2, 3]becomesIN ($1, $2, $3) - converts each value with its type's bind processor, e.g. a dict for a JSON column becomes a JSON string on SQLite
- orders the values by placeholder position (
positiontup):["name", "id_1"]gives["a", 1]
Those steps cost more than the query itself for small statements. When
steps 2 and 3 have nothing to do and no names are escaped, the compiled
SQL is already final and binding is only steps 4 and 5, which
direct_args does in one pass with the same result. That is not the
case with:
INlists and other post-compile parameters (placeholders added per value) and literal-execute parameters (value rendered into the SQL)- column defaults SQLAlchemy fills in at execution time
- escaped bind names (the row is keyed by the original name)
-
a bind the row does not supply::
stmt = select(users.c.id).where(users.c.id == bindparam("ormar_p0")) binds_directly(compiled, {"ormar_p0": 7}) # -> True stmt = select(users.c.id).where(users.c.id.in_(bindparam("ormar_p0"))) binds_directly(compiled, {"ormar_p0": [1, 2]}) # -> False
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compiled
|
SQLCompiler
|
compiled statement |
required |
row
|
Mapping[str, Any]
|
first row of the batch, keyed by bind parameter name |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True when |
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 | |
direct_args(plan, rows)
Build the positional driver arguments of each row straight from its
values, for statements binds_directly accepts. Values are taken in
placeholder order and converted by their bind processors, which gives the
same arguments as construct_params plus expand::
| Text Only | |
|---|---|
1 2 | |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plan
|
StatementPlan
|
plan of the statement |
required |
rows
|
Sequence[Mapping[str, Any]]
|
parameter values per row, keyed by bind parameter name |
required |
Returns:
| Type | Description |
|---|---|
List[List[Any]]
|
positional arguments per row |
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 | |
expand(compiled, params)
Produce the final SQL and positional driver arguments from named parameters.
SQLAlchemy lists the bind names in placeholder order (positiontup), so
the arguments are the values looked up in that order. Each value goes
through its type's bind processor when it has one, the reverse of a result
processor (e.g. a dict to a JSON string on SQLite). IN lists get one
placeholder per value::
| Text Only | |
|---|---|
1 2 3 | |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compiled
|
SQLCompiler
|
compiled statement |
required |
params
|
MutableMapping[str, Any]
|
bound parameters |
required |
Returns:
| Type | Description |
|---|---|
Tuple[str, List[Any]]
|
SQL string and positional arguments |
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 | |
is_plannable(stmt)
Return whether the statement can go through the native compiler at all.
DDL (CREATE TABLE and similar) is compiled by a different compiler
without cache keys, and raw SQL strings have nothing to compile, so both
always run through SQLAlchemy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stmt
|
Any
|
statement to execute |
required |
Returns:
| Type | Description |
|---|---|
TypeGuard[Executable]
|
False for DDL statements and raw SQL strings |
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
417 418 419 420 421 422 423 424 425 426 427 428 429 430 | |
pk_param_key(compiled)
Return the parameter name the INSERT binds the primary key under, or None when the INSERT does not set it.
A primary key provided by the caller is returned as the inserted key instead of asking the database, which cannot always report it::
| Text Only | |
|---|---|
1 2 | |
ormar's cached INSERT templates bind the primary key under their own parameter name, which is returned instead of the column key::
| Text Only | |
|---|---|
1 | |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compiled
|
SQLCompiler
|
compiled insert statement |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
bind parameter key of the primary key, or None |
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 | |
prefetch_defaults(compiled)
Return the column defaults SQLAlchemy fills in at execution time because the statement does not set those columns itself.
SQLAlchemy calls these columns "prefetch": insert_prefetch for
default= on INSERT and update_prefetch for onupdate= on
UPDATE::
| Text Only | |
|---|---|
1 2 | |
StatementPlan falls back to SQLAlchemy when one of them is neither a
constant nor a Python callable (a SQL expression run before the statement).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compiled
|
SQLCompiler
|
compiled statement |
required |
Returns:
| Type | Description |
|---|---|
List[Any]
|
column defaults (or onupdates) of prefetched columns |
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 | |
resolve_result_processors(plan, dialect, coltypes)
Look up, once per plan, the result processor of each result column.
A result processor is the function a SQLAlchemy type uses to turn the raw value a driver returns into the Python value of that type. Drivers return what the database stores, which is not always what the column type promises, e.g. on SQLite::
| Text Only | |
|---|---|
1 2 3 4 5 | |
SQLAlchemy runs them on its own path; the native path must run the same
ones, or rows would hold driver values. Some types pick their processor by
the column type the driver reports (a PostgreSQL NUMERIC read into a
Numeric(asdecimal=False) column needs a float conversion), so this runs
on the first execution, when the driver has reported them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plan
|
StatementPlan
|
plan to resolve processors for |
required |
dialect
|
Dialect
|
dialect of the database |
required |
coltypes
|
Sequence[Any]
|
driver-reported column types (or None per column) |
required |
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 | |
row_class_for(result_columns)
Build the NativeRow subclass of one plan, so its rows can be indexed by
the selected column objects as well as by label.
Column objects are matched by id(), because == on a column builds a
SQL expression instead of comparing. Each entry of SQLAlchemy's
_result_columns lists the objects a result column was selected as::
| Text Only | |
|---|---|
1 2 | |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result_columns
|
Sequence[Any]
|
SQLAlchemy |
required |
Returns:
| Type | Description |
|---|---|
type
|
|
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | |
row_to_dict(plan, values)
Convert one driver row into a NativeRow keyed by result label, running
each value through its result processor::
| Text Only | |
|---|---|
1 | |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plan
|
StatementPlan
|
plan of the executed statement, with resolved processors |
required |
values
|
Sequence[Any]
|
row values in result column order |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
row keyed by result label |
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 | |
row_to_tuple(plan, values)
Convert one driver row into a tuple of values in select order, running
each value through the same result processor row_to_dict uses::
| Text Only | |
|---|---|
1 | |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plan
|
StatementPlan
|
plan of the executed statement, with resolved processors |
required |
values
|
Sequence[Any]
|
row values in result column order |
required |
Returns:
| Type | Description |
|---|---|
Tuple[Any, ...]
|
row values in result column order |
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 | |
unescaped_view(compiled, params)
Return the parameters keyed by the original bind names, as SQLAlchemy
shows them to column defaults reading get_current_parameters().
SQLAlchemy escapes bind names with characters a driver cannot take in a parameter name, and bound parameters use the escaped form::
| Text Only | |
|---|---|
1 2 | |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compiled
|
SQLCompiler
|
compiled statement |
required |
params
|
MutableMapping[str, Any]
|
parameters keyed by escaped bind names |
required |
Returns:
| Type | Description |
|---|---|
MutableMapping[str, Any]
|
parameters keyed by original bind names |
Source code in ormar/databases/native/compiler.py
| Python | |
|---|---|
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 | |