A PostgreSQL ARRAY literal. This is used to produce ARRAY literals in SQL expressions, e.g.:: from sqlalchemy.dialects.postgresql import array from sqlalchemy.dialects import postgresql from sqlalchemy import select, func stmt = select(array([1, 2]) + array([3,
| 91 | |
| 92 | |
| 93 | class array(expression.ExpressionClauseList[_T]): |
| 94 | """A PostgreSQL ARRAY literal. |
| 95 | |
| 96 | This is used to produce ARRAY literals in SQL expressions, e.g.:: |
| 97 | |
| 98 | from sqlalchemy.dialects.postgresql import array |
| 99 | from sqlalchemy.dialects import postgresql |
| 100 | from sqlalchemy import select, func |
| 101 | |
| 102 | stmt = select(array([1, 2]) + array([3, 4, 5])) |
| 103 | |
| 104 | print(stmt.compile(dialect=postgresql.dialect())) |
| 105 | |
| 106 | Produces the SQL: |
| 107 | |
| 108 | .. sourcecode:: sql |
| 109 | |
| 110 | SELECT ARRAY[%(param_1)s, %(param_2)s] || |
| 111 | ARRAY[%(param_3)s, %(param_4)s, %(param_5)s]) AS anon_1 |
| 112 | |
| 113 | An instance of :class:`.array` will always have the datatype |
| 114 | :class:`_types.ARRAY`. The "inner" type of the array is inferred from the |
| 115 | values present, unless the :paramref:`_postgresql.array.type_` keyword |
| 116 | argument is passed:: |
| 117 | |
| 118 | array(["foo", "bar"], type_=CHAR) |
| 119 | |
| 120 | When constructing an empty array, the :paramref:`_postgresql.array.type_` |
| 121 | argument is particularly important as PostgreSQL server typically requires |
| 122 | a cast to be rendered for the inner type in order to render an empty array. |
| 123 | SQLAlchemy's compilation for the empty array will produce this cast so |
| 124 | that:: |
| 125 | |
| 126 | stmt = array([], type_=Integer) |
| 127 | print(stmt.compile(dialect=postgresql.dialect())) |
| 128 | |
| 129 | Produces: |
| 130 | |
| 131 | .. sourcecode:: sql |
| 132 | |
| 133 | ARRAY[]::INTEGER[] |
| 134 | |
| 135 | As required by PostgreSQL for empty arrays. |
| 136 | |
| 137 | .. versionadded:: 2.0.40 added support to render empty PostgreSQL array |
| 138 | literals with a required cast. |
| 139 | |
| 140 | Multidimensional arrays are produced by nesting :class:`.array` constructs. |
| 141 | The dimensionality of the final :class:`_types.ARRAY` |
| 142 | type is calculated by |
| 143 | recursively adding the dimensions of the inner :class:`_types.ARRAY` |
| 144 | type:: |
| 145 | |
| 146 | stmt = select( |
| 147 | array( |
| 148 | [array([1, 2]), array([3, 4]), array([column("q"), column("x")])] |
| 149 | ) |
| 150 | ) |
no outgoing calls