SQLAlchemy 1.1 Documentation
Column Elements and Expressions¶
The most fundamental part of the SQL expression API are the “column elements”,
which allow for basic SQL expression support. The core of all SQL expression
constructs is the ClauseElement, which is the base for several
sub-branches. The ColumnElement class is the fundamental unit
used to construct any kind of typed SQL expression.
-
sqlalchemy.sql.expression.all_(expr)¶ Produce an ALL expression.
This may apply to an array type for some dialects (e.g. postgresql), or to a subquery for others (e.g. mysql). e.g.:
# postgresql '5 = ALL (somearray)' expr = 5 == all_(mytable.c.somearray) # mysql '5 = ALL (SELECT value FROM table)' expr = 5 == all_(select([table.c.value]))
버전 1.1에 추가.
더 보기
-
sqlalchemy.sql.expression.and_(*clauses)¶ Produce a conjunction of expressions joined by
AND.E.g.:
from sqlalchemy import and_ stmt = select([users_table]).where( and_( users_table.c.name == 'wendy', users_table.c.enrolled == True ) )
The
and_()conjunction is also available using the Python&operator (though note that compound expressions need to be parenthesized in order to function with Python operator precedence behavior):stmt = select([users_table]).where( (users_table.c.name == 'wendy') & (users_table.c.enrolled == True) )
The
and_()operation is also implicit in some cases; theSelect.where()method for example can be invoked multiple times against a statement, which will have the effect of each clause being combined usingand_():stmt = select([users_table]).\ where(users_table.c.name == 'wendy').\ where(users_table.c.enrolled == True)
더 보기
-
sqlalchemy.sql.expression.any_(expr)¶ Produce an ANY expression.
This may apply to an array type for some dialects (e.g. postgresql), or to a subquery for others (e.g. mysql). e.g.:
# postgresql '5 = ANY (somearray)' expr = 5 == any_(mytable.c.somearray) # mysql '5 = ANY (SELECT value FROM table)' expr = 5 == any_(select([table.c.value]))
버전 1.1에 추가.
더 보기
-
sqlalchemy.sql.expression.asc(column)¶ Produce an ascending
ORDER BYclause element.e.g.:
from sqlalchemy import asc stmt = select([users_table]).order_by(asc(users_table.c.name))
will produce SQL as:
SELECT id, name FROM user ORDER BY name ASC
The
asc()function is a standalone version of theColumnElement.asc()method available on all SQL expressions, e.g.:stmt = select([users_table]).order_by(users_table.c.name.asc())
매개 변수: column¶ – A ColumnElement(e.g. scalar SQL expression) with which to apply theasc()operation.
-
sqlalchemy.sql.expression.between(expr, lower_bound, upper_bound, symmetric=False)¶ Produce a
BETWEENpredicate clause.E.g.:
from sqlalchemy import between stmt = select([users_table]).where(between(users_table.c.id, 5, 7))
Would produce SQL resembling:
SELECT id, name FROM user WHERE id BETWEEN :id_1 AND :id_2
The
between()function is a standalone version of theColumnElement.between()method available on all SQL expressions, as in:stmt = select([users_table]).where(users_table.c.id.between(5, 7))
All arguments passed to
between(), including the left side column expression, are coerced from Python scalar values if a the value is not aColumnElementsubclass. For example, three fixed values can be compared as in:print(between(5, 3, 7))
Which would produce:
:param_1 BETWEEN :param_2 AND :param_3
매개 변수: - expr¶ – a column expression, typically a
ColumnElementinstance or alternatively a Python scalar expression to be coerced into a column expression, serving as the left side of theBETWEENexpression. - lower_bound¶ – a column or Python scalar expression serving as the
lower bound of the right side of the
BETWEENexpression. - upper_bound¶ – a column or Python scalar expression serving as the
upper bound of the right side of the
BETWEENexpression. - symmetric¶ –
if True, will render ” BETWEEN SYMMETRIC ”. Note that not all databases support this syntax.
버전 0.9.5에 추가.
- expr¶ – a column expression, typically a
-
sqlalchemy.sql.expression.bindparam(key, value=symbol('NO_ARG'), type_=None, unique=False, required=symbol('NO_ARG'), quote=None, callable_=None, isoutparam=False, _compared_to_operator=None, _compared_to_type=None)¶ Produce a “bound expression”.
The return value is an instance of
BindParameter; this is aColumnElementsubclass which represents a so-called “placeholder” value in a SQL expression, the value of which is supplied at the point at which the statement in executed against a database connection.In SQLAlchemy, the
bindparam()construct has the ability to carry along the actual value that will be ultimately used at expression time. In this way, it serves not just as a “placeholder” for eventual population, but also as a means of representing so-called “unsafe” values which should not be rendered directly in a SQL statement, but rather should be passed along to the DBAPI as values which need to be correctly escaped and potentially handled for type-safety.When using
bindparam()explicitly, the use case is typically one of traditional deferment of parameters; thebindparam()construct accepts a name which can then be referred to at execution time:from sqlalchemy import bindparam stmt = select([users_table]).\ where(users_table.c.name == bindparam('username'))
The above statement, when rendered, will produce SQL similar to:
SELECT id, name FROM user WHERE name = :username
In order to populate the value of
:usernameabove, the value would typically be applied at execution time to a method likeConnection.execute():result = connection.execute(stmt, username='wendy')
Explicit use of
bindparam()is also common when producing UPDATE or DELETE statements that are to be invoked multiple times, where the WHERE criterion of the statement is to change on each invocation, such as:stmt = (users_table.update(). where(user_table.c.name == bindparam('username')). values(fullname=bindparam('fullname')) ) connection.execute( stmt, [{"username": "wendy", "fullname": "Wendy Smith"}, {"username": "jack", "fullname": "Jack Jones"}, ] )
SQLAlchemy’s Core expression system makes wide use of
bindparam()in an implicit sense. It is typical that Python literal values passed to virtually all SQL expression functions are coerced into fixedbindparam()constructs. For example, given a comparison operation such as:expr = users_table.c.name == 'Wendy'
The above expression will produce a
BinaryExpressionconstruct, where the left side is theColumnobject representing thenamecolumn, and the right side is aBindParameterrepresenting the literal value:print(repr(expr.right)) BindParameter('%(4327771088 name)s', 'Wendy', type_=String())
The expression above will render SQL such as:
user.name = :name_1
Where the
:name_1parameter name is an anonymous name. The actual stringWendyis not in the rendered string, but is carried along where it is later used within statement execution. If we invoke a statement like the following:stmt = select([users_table]).where(users_table.c.name == 'Wendy') result = connection.execute(stmt)
We would see SQL logging output as:
SELECT "user".id, "user".name FROM "user" WHERE "user".name = %(name_1)s {'name_1': 'Wendy'}Above, we see that
Wendyis passed as a parameter to the database, while the placeholder:name_1is rendered in the appropriate form for the target database, in this case the Postgresql database.Similarly,
bindparam()is invoked automatically when working with CRUD statements as far as the “VALUES” portion is concerned. Theinsert()construct produces anINSERTexpression which will, at statement execution time, generate bound placeholders based on the arguments passed, as in:stmt = users_table.insert() result = connection.execute(stmt, name='Wendy')
The above will produce SQL output as:
INSERT INTO "user" (name) VALUES (%(name)s) {'name': 'Wendy'}The
Insertconstruct, at compilation/execution time, rendered a singlebindparam()mirroring the column namenameas a result of the singlenameparameter we passed to theConnection.execute()method.매개 변수: - key¶ – the key (e.g. the name) for this bind param.
Will be used in the generated
SQL statement for dialects that use named parameters. This
value may be modified when part of a compilation operation,
if other
BindParameterobjects exist with the same key, or if its length is too long and truncation is required. - value¶ – Initial value for this bind param. Will be used at statement
execution time as the value for this parameter passed to the
DBAPI, if no other value is indicated to the statement execution
method for this particular parameter name. Defaults to
None. - callable_¶ – A callable function that takes the place of “value”. The function will be called at statement execution time to determine the ultimate value. Used for scenarios where the actual bind value cannot be determined at the point at which the clause construct is created, but embedded bind values are still desirable.
- type_¶ –
A
TypeEngineclass or instance representing an optional datatype for thisbindparam(). If not passed, a type may be determined automatically for the bind, based on the given value; for example, trivial Python types such asstr,int,boolmay result in theString,IntegerorBooleantypes being autoamtically selected.The type of a
bindparam()is significant especially in that the type will apply pre-processing to the value before it is passed to the database. For example, abindparam()which refers to a datetime value, and is specified as holding theDateTimetype, may apply conversion needed to the value (such as stringification on SQLite) before passing the value to the database. - unique¶ – if True, the key name of this
BindParameterwill be modified if anotherBindParameterof the same name already has been located within the containing expression. This flag is used generally by the internals when producing so-called “anonymous” bound expressions, it isn’t generally applicable to explicitly-namedbindparam()constructs. - required¶ –
If
True, a value is required at execution time. If not passed, it defaults toTrueif neitherbindparam.valueorbindparam.callablewere passed. If either of these parameters are present, thenbindparam.requireddefaults toFalse.버전 0.8으로 변경: If the
requiredflag is not specified, it will be set automatically toTrueorFalsedepending on whether or not thevalueorcallableparameters were specified. - quote¶ – True if this parameter name requires quoting and is not currently known as a SQLAlchemy reserved word; this currently only applies to the Oracle backend, where bound names must sometimes be quoted.
- isoutparam¶ – if True, the parameter should be treated like a stored procedure “OUT” parameter. This applies to backends such as Oracle which support OUT parameters.
- key¶ – the key (e.g. the name) for this bind param.
Will be used in the generated
SQL statement for dialects that use named parameters. This
value may be modified when part of a compilation operation,
if other
-
sqlalchemy.sql.expression.case(whens, value=None, else_=None)¶ Produce a
CASEexpression.The
CASEconstruct in SQL is a conditional object that acts somewhat analogously to an “if/then” construct in other languages. It returns an instance ofCase.case()in its usual form is passed a list of “when” constructs, that is, a list of conditions and results as tuples:from sqlalchemy import case stmt = select([users_table]).\ where( case( [ (users_table.c.name == 'wendy', 'W'), (users_table.c.name == 'jack', 'J') ], else_='E' ) )
The above statement will produce SQL resembling:
SELECT id, name FROM user WHERE CASE WHEN (name = :name_1) THEN :param_1 WHEN (name = :name_2) THEN :param_2 ELSE :param_3 ENDWhen simple equality expressions of several values against a single parent column are needed,
case()also has a “shorthand” format used via thecase.valueparameter, which is passed a column expression to be compared. In this form, thecase.whensparameter is passed as a dictionary containing expressions to be compared against keyed to result expressions. The statement below is equivalent to the preceding statement:stmt = select([users_table]).\ where( case( {"wendy": "W", "jack": "J"}, value=users_table.c.name, else_='E' ) )
The values which are accepted as result values in
case.whensas well as withcase.else_are coerced from Python literals intobindparam()constructs. SQL expressions, e.g.ColumnElementconstructs, are accepted as well. To coerce a literal string expression into a constant expression rendered inline, use theliteral_column()construct, as in:from sqlalchemy import case, literal_column case( [ ( orderline.c.qty > 100, literal_column("'greaterthan100'") ), ( orderline.c.qty > 10, literal_column("'greaterthan10'") ) ], else_=literal_column("'lessthan10'") )
The above will render the given constants without using bound parameters for the result values (but still for the comparison values), as in:
CASE WHEN (orderline.qty > :qty_1) THEN 'greaterthan100' WHEN (orderline.qty > :qty_2) THEN 'greaterthan10' ELSE 'lessthan10' END매개 변수: - whens¶ –
The criteria to be compared against,
case.whensaccepts two different forms, based on whether or notcase.valueis used.In the first form, it accepts a list of 2-tuples; each 2-tuple consists of
(<sql expression>, <value>), where the SQL expression is a boolean expression and “value” is a resulting value, e.g.:case([ (users_table.c.name == 'wendy', 'W'), (users_table.c.name == 'jack', 'J') ])
In the second form, it accepts a Python dictionary of comparison values mapped to a resulting value; this form requires
case.valueto be present, and values will be compared using the==operator, e.g.:case( {"wendy": "W", "jack": "J"}, value=users_table.c.name )
- value¶ – An optional SQL expression which will be used as a
fixed “comparison point” for candidate values within a dictionary
passed to
case.whens. - else_¶ – An optional SQL expression which will be the evaluated
result of the
CASEconstruct if all expressions withincase.whensevaluate to false. When omitted, most databases will produce a result of NULL if none of the “when” expressions evaluate to true.
- whens¶ –
-
sqlalchemy.sql.expression.cast(expression, type_)¶ Produce a
CASTexpression.cast()returns an instance ofCast.E.g.:
from sqlalchemy import cast, Numeric stmt = select([ cast(product_table.c.unit_price, Numeric(10, 4)) ])
The above statement will produce SQL resembling:
SELECT CAST(unit_price AS NUMERIC(10, 4)) FROM product
The
cast()function performs two distinct functions when used. The first is that it renders theCASTexpression within the resulting SQL string. The second is that it associates the given type (e.g.TypeEngineclass or instance) with the column expression on the Python side, which means the expression will take on the expression operator behavior associated with that type, as well as the bound-value handling and result-row-handling behavior of the type.버전 0.9.0으로 변경:
cast()now applies the given type to the expression such that it takes effect on the bound-value, e.g. the Python-to-database direction, in addition to the result handling, e.g. database-to-Python, direction.An alternative to
cast()is thetype_coerce()function. This function performs the second task of associating an expression with a specific type, but does not render theCASTexpression in SQL.매개 변수: - expression¶ – A SQL expression, such as a
ColumnElementexpression or a Python string which will be coerced into a bound literal value. - type_¶ – A
TypeEngineclass or instance indicating the type to which theCASTshould apply.
더 보기
type_coerce()- Python-side type coercion without emitting CAST.- expression¶ – A SQL expression, such as a
-
sqlalchemy.sql.expression.column(text, type_=None, is_literal=False, _selectable=None)¶ Produce a
ColumnClauseobject.The
ColumnClauseis a lightweight analogue to theColumnclass. Thecolumn()function can be invoked with just a name alone, as in:from sqlalchemy import column id, name = column("id"), column("name") stmt = select([id, name]).select_from("user")
The above statement would produce SQL like:
SELECT id, name FROM user
Once constructed,
column()may be used like any other SQL expression element such as withinselect()constructs:from sqlalchemy.sql import column id, name = column("id"), column("name") stmt = select([id, name]).select_from("user")
The text handled by
column()is assumed to be handled like the name of a database column; if the string contains mixed case, special characters, or matches a known reserved word on the target backend, the column expression will render using the quoting behavior determined by the backend. To produce a textual SQL expression that is rendered exactly without any quoting, useliteral_column()instead, or passTrueas the value ofcolumn.is_literal. Additionally, full SQL statements are best handled using thetext()construct.column()can be used in a table-like fashion by combining it with thetable()function (which is the lightweight analogue toTable) to produce a working table construct with minimal boilerplate:from sqlalchemy import table, column, select user = table("user", column("id"), column("name"), column("description"), ) stmt = select([user.c.description]).where(user.c.name == 'wendy')
A
column()/table()construct like that illustrated above can be created in an ad-hoc fashion and is not associated with anyschema.MetaData, DDL, or events, unlike itsTablecounterpart.버전 1.0.0으로 변경:
expression.column()can now be imported from the plainsqlalchemynamespace like any other SQL element.매개 변수: - text¶ – the text of the element.
- type¶ –
types.TypeEngineobject which can associate thisColumnClausewith a type. - is_literal¶ – if True, the
ColumnClauseis assumed to be an exact expression that will be delivered to the output with no quoting rules applied regardless of case sensitive settings. theliteral_column()function essentially invokescolumn()while passingis_literal=True.
-
sqlalchemy.sql.expression.collate(expression, collation)¶ Return the clause
expression COLLATE collation.e.g.:
collate(mycolumn, 'utf8_bin')
produces:
mycolumn COLLATE utf8_bin
-
sqlalchemy.sql.expression.desc(column)¶ Produce a descending
ORDER BYclause element.e.g.:
from sqlalchemy import desc stmt = select([users_table]).order_by(desc(users_table.c.name))
will produce SQL as:
SELECT id, name FROM user ORDER BY name DESC
The
desc()function is a standalone version of theColumnElement.desc()method available on all SQL expressions, e.g.:stmt = select([users_table]).order_by(users_table.c.name.desc())
매개 변수: column¶ – A ColumnElement(e.g. scalar SQL expression) with which to apply thedesc()operation.
-
sqlalchemy.sql.expression.distinct(expr)¶ Produce an column-expression-level unary
DISTINCTclause.This applies the
DISTINCTkeyword to an individual column expression, and is typically contained within an aggregate function, as in:from sqlalchemy import distinct, func stmt = select([func.count(distinct(users_table.c.name))])
The above would produce an expression resembling:
SELECT COUNT(DISTINCT name) FROM user
The
distinct()function is also available as a column-level method, e.g.ColumnElement.distinct(), as in:stmt = select([func.count(users_table.c.name.distinct())])
The
distinct()operator is different from theSelect.distinct()method ofSelect, which produces aSELECTstatement withDISTINCTapplied to the result set as a whole, e.g. aSELECT DISTINCTexpression. See that method for further information.
-
sqlalchemy.sql.expression.extract(field, expr, **kwargs)¶ Return a
Extractconstruct.This is typically available as
extract()as well asfunc.extractfrom thefuncnamespace.
-
sqlalchemy.sql.expression.false()¶ Return a
False_construct.E.g.:
>>> from sqlalchemy import false >>> print select([t.c.x]).where(false()) SELECT x FROM t WHERE false
A backend which does not support true/false constants will render as an expression against 1 or 0:
>>> print select([t.c.x]).where(false()) SELECT x FROM t WHERE 0 = 1
The
true()andfalse()constants also feature “short circuit” operation within anand_()oror_()conjunction:>>> print select([t.c.x]).where(or_(t.c.x > 5, true())) SELECT x FROM t WHERE true >>> print select([t.c.x]).where(and_(t.c.x > 5, false())) SELECT x FROM t WHERE false
버전 0.9으로 변경:
true()andfalse()feature better integrated behavior within conjunctions and on dialects that don’t support true/false constants.더 보기
-
sqlalchemy.sql.expression.func= <sqlalchemy.sql.functions._FunctionGenerator object>¶ Generate SQL function expressions.
funcis a special object instance which generates SQL functions based on name-based attributes, e.g.:>>> print func.count(1) count(:param_1)
The element is a column-oriented SQL element like any other, and is used in that way:
>>> print select([func.count(table.c.id)]) SELECT count(sometable.id) FROM sometable
Any name can be given to
func. If the function name is unknown to SQLAlchemy, it will be rendered exactly as is. For common SQL functions which SQLAlchemy is aware of, the name may be interpreted as a generic function which will be compiled appropriately to the target database:>>> print func.current_timestamp() CURRENT_TIMESTAMP
To call functions which are present in dot-separated packages, specify them in the same manner:
>>> print func.stats.yield_curve(5, 10) stats.yield_curve(:yield_curve_1, :yield_curve_2)
SQLAlchemy can be made aware of the return type of functions to enable type-specific lexical and result-based behavior. For example, to ensure that a string-based function returns a Unicode value and is similarly treated as a string in expressions, specify
Unicodeas the type:>>> print func.my_string(u'hi', type_=Unicode) + ' ' + \ ... func.my_string(u'there', type_=Unicode) my_string(:my_string_1) || :my_string_2 || my_string(:my_string_3)
The object returned by a
funccall is usually an instance ofFunction. This object meets the “column” interface, including comparison and labeling functions. The object can also be passed theexecute()method of aConnectionorEngine, where it will be wrapped inside of a SELECT statement first:print connection.execute(func.current_timestamp()).scalar()
In a few exception cases, the
funcaccessor will redirect a name to a built-in expression such ascast()orextract(), as these names have well-known meaning but are not exactly the same as “functions” from a SQLAlchemy perspective.버전 0.8에 추가:
funccan return non-function expression constructs for common quasi-functional names likecast()andextract().Functions which are interpreted as “generic” functions know how to calculate their return type automatically. For a listing of known generic functions, see SQL and Generic Functions.
주석
The
funcconstruct has only limited support for calling standalone “stored procedures”, especially those with special parameterization concerns.See the section Calling Stored Procedures for details on how to use the DBAPI-level
callproc()method for fully traditional stored procedures.
-
sqlalchemy.sql.expression.funcfilter(func, *criterion)¶ Produce a
FunctionFilterobject against a function.Used against aggregate and window functions, for database backends that support the “FILTER” clause.
E.g.:
from sqlalchemy import funcfilter funcfilter(func.count(1), MyClass.name == 'some name')
Would produce “COUNT(1) FILTER (WHERE myclass.name = ‘some name’)”.
This function is also available from the
funcconstruct itself via theFunctionElement.filter()method.버전 1.0.0에 추가.
-
sqlalchemy.sql.expression.label(name, element, type_=None)¶ Return a
Labelobject for the givenColumnElement.A label changes the name of an element in the columns clause of a
SELECTstatement, typically via theASSQL keyword.This functionality is more conveniently available via the
ColumnElement.label()method onColumnElement.매개 변수: - name¶ – label name
- obj¶ – a
ColumnElement.
-
sqlalchemy.sql.expression.literal(value, type_=None)¶ Return a literal clause, bound to a bind parameter.
Literal clauses are created automatically when non-
ClauseElementobjects (such as strings, ints, dates, etc.) are used in a comparison operation with aColumnElementsubclass, such as aColumnobject. Use this function to force the generation of a literal clause, which will be created as aBindParameterwith a bound value.매개 변수: - value¶ – the value to be bound. Can be any Python object supported by the underlying DB-API, or is translatable via the given type argument.
- type_¶ – an optional
TypeEnginewhich will provide bind-parameter translation for this literal.
-
sqlalchemy.sql.expression.literal_column(text, type_=None)¶ Produce a
ColumnClauseobject that has thecolumn.is_literalflag set to True.literal_column()is similar tocolumn(), except that it is more often used as a “standalone” column expression that renders exactly as stated; whilecolumn()stores a string name that will be assumed to be part of a table and may be quoted as such,literal_column()can be that, or any other arbitrary column-oriented expression.매개 변수: - text¶ – the text of the expression; can be any SQL expression.
Quoting rules will not be applied. To specify a column-name expression
which should be subject to quoting rules, use the
column()function. - type_¶ – an optional
TypeEngineobject which will provide result-set translation and additional expression semantics for this column. If left as None the type will be NullType.
- text¶ – the text of the expression; can be any SQL expression.
Quoting rules will not be applied. To specify a column-name expression
which should be subject to quoting rules, use the
-
sqlalchemy.sql.expression.not_(clause)¶ Return a negation of the given clause, i.e.
NOT(clause).The
~operator is also overloaded on allColumnElementsubclasses to produce the same result.
-
sqlalchemy.sql.expression.nullsfirst(column)¶ Produce the
NULLS FIRSTmodifier for anORDER BYexpression.nullsfirst()is intended to modify the expression produced byasc()ordesc(), and indicates how NULL values should be handled when they are encountered during ordering:from sqlalchemy import desc, nullsfirst stmt = select([users_table]).\ order_by(nullsfirst(desc(users_table.c.name)))
The SQL expression from the above would resemble:
SELECT id, name FROM user ORDER BY name DESC NULLS FIRST
Like
asc()anddesc(),nullsfirst()is typically invoked from the column expression itself usingColumnElement.nullsfirst(), rather than as its standalone function version, as in:stmt = (select([users_table]). order_by(users_table.c.name.desc().nullsfirst()) )
-
sqlalchemy.sql.expression.nullslast(column)¶ Produce the
NULLS LASTmodifier for anORDER BYexpression.nullslast()is intended to modify the expression produced byasc()ordesc(), and indicates how NULL values should be handled when they are encountered during ordering:from sqlalchemy import desc, nullslast stmt = select([users_table]).\ order_by(nullslast(desc(users_table.c.name)))
The SQL expression from the above would resemble:
SELECT id, name FROM user ORDER BY name DESC NULLS LAST
Like
asc()anddesc(),nullslast()is typically invoked from the column expression itself usingColumnElement.nullslast(), rather than as its standalone function version, as in:stmt = select([users_table]).\ order_by(users_table.c.name.desc().nullslast())
-
sqlalchemy.sql.expression.or_(*clauses)¶ Produce a conjunction of expressions joined by
OR.E.g.:
from sqlalchemy import or_ stmt = select([users_table]).where( or_( users_table.c.name == 'wendy', users_table.c.name == 'jack' ) )
The
or_()conjunction is also available using the Python|operator (though note that compound expressions need to be parenthesized in order to function with Python operator precedence behavior):stmt = select([users_table]).where( (users_table.c.name == 'wendy') | (users_table.c.name == 'jack') )
더 보기
-
sqlalchemy.sql.expression.outparam(key, type_=None)¶ Create an ‘OUT’ parameter for usage in functions (stored procedures), for databases which support them.
The
outparamcan be used like a regular function parameter. The “output” value will be available from theResultProxyobject via itsout_parametersattribute, which returns a dictionary containing the values.
-
sqlalchemy.sql.expression.over(element, partition_by=None, order_by=None)¶ Produce an
Overobject against a function.Used against aggregate or so-called “window” functions, for database backends that support window functions.
over()is usually called using theFunctionElement.over()method, e.g.:func.row_number().over(order_by='x')
Would produce
ROW_NUMBER() OVER(ORDER BY x).매개 변수: - element¶ – a
FunctionElement,WithinGroup, or other compatible construct. - partition_by¶ – a column element or string, or a list of such, that will be used as the PARTITION BY clause of the OVER construct.
- order_by¶ – a column element or string, or a list of such, that will be used as the ORDER BY clause of the OVER construct.
This function is also available from the
funcconstruct itself via theFunctionElement.over()method.버전 0.7에 추가.
- element¶ – a
-
sqlalchemy.sql.expression.text(text, bind=None, bindparams=None, typemap=None, autocommit=None)¶ Construct a new
TextClauseclause, representing a textual SQL string directly.E.g.:
from sqlalchemy import text t = text("SELECT * FROM users") result = connection.execute(t)
The advantages
text()provides over a plain string are backend-neutral support for bind parameters, per-statement execution options, as well as bind parameter and result-column typing behavior, allowing SQLAlchemy type constructs to play a role when executing a statement that is specified literally. The construct can also be provided with a.ccollection of column elements, allowing it to be embedded in other SQL expression constructs as a subquery.Bind parameters are specified by name, using the format
:name. E.g.:t = text("SELECT * FROM users WHERE id=:user_id") result = connection.execute(t, user_id=12)
For SQL statements where a colon is required verbatim, as within an inline string, use a backslash to escape:
t = text("SELECT * FROM users WHERE name='\:username'")
The
TextClauseconstruct includes methods which can provide information about the bound parameters as well as the column values which would be returned from the textual statement, assuming it’s an executable SELECT type of statement. TheTextClause.bindparams()method is used to provide bound parameter detail, andTextClause.columns()method allows specification of return columns including names and types:t = text("SELECT * FROM users WHERE id=:user_id").\ bindparams(user_id=7).\ columns(id=Integer, name=String) for id, name in connection.execute(t): print(id, name)
The
text()construct is used in cases when a literal string SQL fragment is specified as part of a larger query, such as for the WHERE clause of a SELECT statement:s = select([users.c.id, users.c.name]).where(text("id=:user_id")) result = connection.execute(s, user_id=12)
text()is also used for the construction of a full, standalone statement using plain text. As such, SQLAlchemy refers to it as anExecutableobject, and it supports theExecutable.execution_options()method. For example, atext()construct that should be subject to “autocommit” can be set explicitly so using theConnection.execution_options.autocommitoption:t = text("EXEC my_procedural_thing()").\ execution_options(autocommit=True)
Note that SQLAlchemy’s usual “autocommit” behavior applies to
text()constructs implicitly - that is, statements which begin with a phrase such asINSERT,UPDATE,DELETE, or a variety of other phrases specific to certain backends, will be eligible for autocommit if no transaction is in progress.매개 변수: - text¶ – the text of the SQL statement to be created. use
:<param>to specify bind parameters; they will be compiled to their engine-specific format. - autocommit¶ – Deprecated. Use .execution_options(autocommit=<True|False>) to set the autocommit option.
- bind¶ – an optional connection or engine to be used for this text query.
- bindparams¶ –
Deprecated. A list of
bindparam()instances used to provide information about parameters embedded in the statement. This argument now invokes theTextClause.bindparams()method on the construct before returning it. E.g.:stmt = text("SELECT * FROM table WHERE id=:id", bindparams=[bindparam('id', value=5, type_=Integer)])
Is equivalent to:
stmt = text("SELECT * FROM table WHERE id=:id").\ bindparams(bindparam('id', value=5, type_=Integer))
버전 0.9.0 폐지: the
TextClause.bindparams()method supersedes thebindparamsargument totext(). - typemap¶ –
Deprecated. A dictionary mapping the names of columns represented in the columns clause of a
SELECTstatement to type objects, which will be used to perform post-processing on columns within the result set. This parameter now invokes theTextClause.columns()method, which returns aTextAsFromconstruct that gains a.ccollection and can be embedded in other expressions. E.g.:stmt = text("SELECT * FROM table", typemap={'id': Integer, 'name': String}, )
Is equivalent to:
stmt = text("SELECT * FROM table").columns(id=Integer, name=String)
Or alternatively:
from sqlalchemy.sql import column stmt = text("SELECT * FROM table").columns( column('id', Integer), column('name', String) )
버전 0.9.0 폐지: the
TextClause.columns()method supersedes thetypemapargument totext().
- text¶ – the text of the SQL statement to be created. use
-
sqlalchemy.sql.expression.true()¶ Return a constant
True_construct.E.g.:
>>> from sqlalchemy import true >>> print select([t.c.x]).where(true()) SELECT x FROM t WHERE true
A backend which does not support true/false constants will render as an expression against 1 or 0:
>>> print select([t.c.x]).where(true()) SELECT x FROM t WHERE 1 = 1
The
true()andfalse()constants also feature “short circuit” operation within anand_()oror_()conjunction:>>> print select([t.c.x]).where(or_(t.c.x > 5, true())) SELECT x FROM t WHERE true >>> print select([t.c.x]).where(and_(t.c.x > 5, false())) SELECT x FROM t WHERE false
버전 0.9으로 변경:
true()andfalse()feature better integrated behavior within conjunctions and on dialects that don’t support true/false constants.더 보기
-
sqlalchemy.sql.expression.tuple_(*clauses, **kw)¶ Return a
Tuple.Main usage is to produce a composite IN construct:
from sqlalchemy import tuple_ tuple_(table.c.col1, table.c.col2).in_( [(1, 2), (5, 12), (10, 19)] )
경고
The composite IN construct is not supported by all backends, and is currently known to work on Postgresql and MySQL, but not SQLite. Unsupported backends will raise a subclass of
DBAPIErrorwhen such an expression is invoked.
-
sqlalchemy.sql.expression.type_coerce(expression, type_)¶ Associate a SQL expression with a particular type, without rendering
CAST.E.g.:
from sqlalchemy import type_coerce stmt = select([ type_coerce(log_table.date_string, StringDateTime()) ])
The above construct will produce a
TypeCoerceobject, which renders SQL that labels the expression, but otherwise does not modify its value on the SQL side:SELECT date_string AS anon_1 FROM log
When result rows are fetched, the
StringDateTimetype will be applied to result rows on behalf of thedate_stringcolumn. The rationale for the “anon_1” label is so that the type-coerced column remains separate in the list of result columns vs. other type-coerced or direct values of the target column. In order to provide a named label for the expression, useColumnElement.label():stmt = select([ type_coerce( log_table.date_string, StringDateTime()).label('date') ])
A type that features bound-value handling will also have that behavior take effect when literal values or
bindparam()constructs are passed totype_coerce()as targets. For example, if a type implements theTypeEngine.bind_expression()method orTypeEngine.bind_processor()method or equivalent, these functions will take effect at statement compilation/execution time when a literal value is passed, as in:# bound-value handling of MyStringType will be applied to the # literal value "some string" stmt = select([type_coerce("some string", MyStringType)])
type_coerce()is similar to thecast()function, except that it does not render theCASTexpression in the resulting statement.매개 변수: - expression¶ – A SQL expression, such as a
ColumnElementexpression or a Python string which will be coerced into a bound literal value. - type_¶ – A
TypeEngineclass or instance indicating the type to which the expression is coerced.
더 보기
- expression¶ – A SQL expression, such as a
-
sqlalchemy.sql.expression.within_group(element, *order_by)¶ Produce a
WithinGroupobject against a function.Used against so-called “ordered set aggregate” and “hypothetical set aggregate” functions, including
percentile_cont,rank,dense_rank, etc.within_group()is usually called using theFunctionElement.within_group()method, e.g.:from sqlalchemy import within_group stmt = select([ department.c.id, func.percentile_cont(0.5).within_group( department.c.salary.desc() ) ])
The above statement would produce SQL similar to
SELECT department.id, percentile_cont(0.5) WITHIN GROUP (ORDER BY department.salary DESC).매개 변수: - element¶ – a
FunctionElementconstruct, typically generated byfunc. - *order_by¶ – one or more column elements that will be used as the ORDER BY clause of the WITHIN GROUP construct.
버전 1.1에 추가.
- element¶ – a
-
class
sqlalchemy.sql.expression.BinaryExpression(left, right, operator, type_=None, negate=None, modifiers=None)¶ Bases:
sqlalchemy.sql.expression.ColumnElementRepresent an expression that is
LEFT <operator> RIGHT.A
BinaryExpressionis generated automatically whenever two column expressions are used in a Python binary expression:>>> from sqlalchemy.sql import column >>> column('a') + column('b') <sqlalchemy.sql.expression.BinaryExpression object at 0x101029dd0> >>> print column('a') + column('b') a + b
-
compare(other, **kw)¶ Compare this
BinaryExpressionagainst the givenBinaryExpression.
-
-
class
sqlalchemy.sql.expression.BindParameter(key, value=symbol('NO_ARG'), type_=None, unique=False, required=symbol('NO_ARG'), quote=None, callable_=None, isoutparam=False, _compared_to_operator=None, _compared_to_type=None)¶ Bases:
sqlalchemy.sql.expression.ColumnElementRepresent a “bound expression”.
BindParameteris invoked explicitly using thebindparam()function, as in:from sqlalchemy import bindparam stmt = select([users_table]).\ where(users_table.c.name == bindparam('username'))
Detailed discussion of how
BindParameteris used is atbindparam().더 보기
-
__init__(key, value=symbol('NO_ARG'), type_=None, unique=False, required=symbol('NO_ARG'), quote=None, callable_=None, isoutparam=False, _compared_to_operator=None, _compared_to_type=None)¶ Construct a new
BindParameterobject.This constructor is mirrored as a public API function; see
bindparam()for a full usage and argument description.
-
compare(other, **kw)¶ Compare this
BindParameterto the given clause.
-
effective_value¶ Return the value of this bound parameter, taking into account if the
callableparameter was set.The
callablevalue will be evaluated and returned if present, elsevalue.
-
-
class
sqlalchemy.sql.expression.Case(whens, value=None, else_=None)¶ Bases:
sqlalchemy.sql.expression.ColumnElementRepresent a
CASEexpression.Caseis produced using thecase()factory function, as in:from sqlalchemy import case stmt = select([users_table]).\ where( case( [ (users_table.c.name == 'wendy', 'W'), (users_table.c.name == 'jack', 'J') ], else_='E' ) )
Details on
Caseusage is atcase().더 보기
-
class
sqlalchemy.sql.expression.Cast(expression, type_)¶ Bases:
sqlalchemy.sql.expression.ColumnElementRepresent a
CASTexpression.Castis produced using thecast()factory function, as in:from sqlalchemy import cast, Numeric stmt = select([ cast(product_table.c.unit_price, Numeric(10, 4)) ])
Details on
Castusage is atcast().더 보기
-
class
sqlalchemy.sql.expression.ClauseElement¶ Bases:
sqlalchemy.sql.visitors.VisitableBase class for elements of a programmatically constructed SQL expression.
-
compare(other, **kw)¶ Compare this ClauseElement to the given ClauseElement.
Subclasses should override the default behavior, which is a straight identity comparison.
**kw are arguments consumed by subclass compare() methods and may be used to modify the criteria for comparison. (see
ColumnElement)
-
compile(bind=None, dialect=None, **kw)¶ Compile this SQL expression.
The return value is a
Compiledobject. Callingstr()orunicode()on the returned value will yield a string representation of the result. TheCompiledobject also can return a dictionary of bind parameter names and values using theparamsaccessor.매개 변수: - bind¶ – An
EngineorConnectionfrom which aCompiledwill be acquired. This argument takes precedence over thisClauseElement‘s bound engine, if any. - column_keys¶ – Used for INSERT and UPDATE statements, a list of
column names which should be present in the VALUES clause of the
compiled statement. If
None, all columns from the target table object are rendered. - dialect¶ – A
Dialectinstance from which aCompiledwill be acquired. This argument takes precedence over the bind argument as well as thisClauseElement‘s bound engine, if any. - inline¶ – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
- compile_kwargs¶ –
optional dictionary of additional parameters that will be passed through to the compiler within all “visit” methods. This allows any custom flag to be passed through to a custom compilation construct, for example. It is also used for the case of passing the
literal_bindsflag through:from sqlalchemy.sql import table, column, select t = table('t', column('x')) s = select([t]).where(t.c.x == 5) print s.compile(compile_kwargs={"literal_binds": True})
버전 0.9.0에 추가.
- bind¶ – An
-
get_children(**kwargs)¶ Return immediate child elements of this
ClauseElement.This is used for visit traversal.
**kwargs may contain flags that change the collection that is returned, for example to return a subset of items in order to cut down on larger traversals, or to return child items from a different context (such as schema-level collections instead of clause-level).
-
params(*optionaldict, **kwargs)¶ Return a copy with
bindparam()elements replaced.Returns a copy of this ClauseElement with
bindparam()elements replaced with values taken from the given dictionary:>>> clause = column('x') + bindparam('foo') >>> print clause.compile().params {'foo':None} >>> print clause.params({'foo':7}).compile().params {'foo':7}
-
self_group(against=None)¶ Apply a ‘grouping’ to this
ClauseElement.This method is overridden by subclasses to return a “grouping” construct, i.e. parenthesis. In particular it’s used by “binary” expressions to provide a grouping around themselves when placed into a larger expression, as well as by
select()constructs when placed into the FROM clause of anotherselect(). (Note that subqueries should be normally created using theSelect.alias()method, as many platforms require nested SELECT statements to be named).As expressions are composed together, the application of
self_group()is automatic - end-user code should never need to use this method directly. Note that SQLAlchemy’s clause constructs take operator precedence into account - so parenthesis might not be needed, for example, in an expression likex OR (y AND z)- AND takes precedence over OR.The base
self_group()method ofClauseElementjust returns self.
-
unique_params(*optionaldict, **kwargs)¶ Return a copy with
bindparam()elements replaced.Same functionality as
params(), except adds unique=True to affected bind parameters so that multiple statements can be used.
-
-
class
sqlalchemy.sql.expression.ClauseList(*clauses, **kwargs)¶ Bases:
sqlalchemy.sql.expression.ClauseElementDescribe a list of clauses, separated by an operator.
By default, is comma-separated, such as a column listing.
-
compare(other, **kw)¶ Compare this
ClauseListto the givenClauseList, including a comparison of all the clause items.
-
-
class
sqlalchemy.sql.expression.ColumnClause(text, type_=None, is_literal=False, _selectable=None)¶ Bases:
sqlalchemy.sql.expression.Immutable,sqlalchemy.sql.expression.ColumnElementRepresents a column expression from any textual string.
The
ColumnClause, a lightweight analogue to theColumnclass, is typically invoked using thecolumn()function, as in:from sqlalchemy import column id, name = column("id"), column("name") stmt = select([id, name]).select_from("user")
The above statement would produce SQL like:
SELECT id, name FROM user
ColumnClauseis the immediate superclass of the schema-specificColumnobject. While theColumnclass has all the same capabilities asColumnClause, theColumnClauseclass is usable by itself in those cases where behavioral requirements are limited to simple SQL expression generation. The object has none of the associations with schema-level metadata or with execution-time behavior thatColumndoes, so in that sense is a “lightweight” version ofColumn.Full details on
ColumnClauseusage is atcolumn().-
__init__(text, type_=None, is_literal=False, _selectable=None)¶ Construct a new
ColumnClauseobject.This constructor is mirrored as a public API function; see
column()for a full usage and argument description.
-
-
class
sqlalchemy.sql.expression.ColumnCollection(*columns)¶ Bases:
sqlalchemy.util._collections.OrderedPropertiesAn ordered dictionary that stores a list of ColumnElement instances.
Overrides the
__eq__()method to produce SQL clauses between sets of correlated columns.-
add(column)¶ Add a column to this collection.
The key attribute of the column will be used as the hash key for this dictionary.
-
replace(column)¶ add the given column to this collection, removing unaliased versions of this column as well as existing columns with the same key.
e.g.:
t = Table('sometable', metadata, Column('col1', Integer)) t.columns.replace(Column('col1', Integer, key='columnone'))
will remove the original ‘col1’ from the collection, and add the new column under the name ‘columnname’.
Used by schema.Column to override columns during table reflection.
-
-
class
sqlalchemy.sql.expression.ColumnElement¶ Bases:
sqlalchemy.sql.operators.ColumnOperators,sqlalchemy.sql.expression.ClauseElementRepresent a column-oriented SQL expression suitable for usage in the “columns” clause, WHERE clause etc. of a statement.
While the most familiar kind of
ColumnElementis theColumnobject,ColumnElementserves as the basis for any unit that may be present in a SQL expression, including the expressions themselves, SQL functions, bound parameters, literal expressions, keywords such asNULL, etc.ColumnElementis the ultimate base class for all such elements.A wide variety of SQLAlchemy Core functions work at the SQL expression level, and are intended to accept instances of
ColumnElementas arguments. These functions will typically document that they accept a “SQL expression” as an argument. What this means in terms of SQLAlchemy usually refers to an input which is either already in the form of aColumnElementobject, or a value which can be coerced into one. The coercion rules followed by most, but not all, SQLAlchemy Core functions with regards to SQL expressions are as follows:- a literal Python value, such as a string, integer or floating
point value, boolean, datetime,
Decimalobject, or virtually any other Python object, will be coerced into a “literal bound value”. This generally means that abindparam()will be produced featuring the given value embedded into the construct; the resultingBindParameterobject is an instance ofColumnElement. The Python value will ultimately be sent to the DBAPI at execution time as a paramterized argument to theexecute()orexecutemany()methods, after SQLAlchemy type-specific converters (e.g. those provided by any associatedTypeEngineobjects) are applied to the value. - any special object value, typically ORM-level constructs, which
feature a method called
__clause_element__(). The Core expression system looks for this method when an object of otherwise unknown type is passed to a function that is looking to coerce the argument into aColumnElementexpression. The__clause_element__()method, if present, should return aColumnElementinstance. The primary use of__clause_element__()within SQLAlchemy is that of class-bound attributes on ORM-mapped classes; aUserclass which contains a mapped attribute named.namewill have a methodUser.name.__clause_element__()which when invoked returns theColumncallednameassociated with the mapped table. - The Python
Nonevalue is typically interpreted asNULL, which in SQLAlchemy Core produces an instance ofnull().
A
ColumnElementprovides the ability to generate newColumnElementobjects using Python expressions. This means that Python operators such as==,!=and<are overloaded to mimic SQL operations, and allow the instantiation of furtherColumnElementinstances which are composed from other, more fundamentalColumnElementobjects. For example, twoColumnClauseobjects can be added together with the addition operator+to produce aBinaryExpression. BothColumnClauseandBinaryExpressionare subclasses ofColumnElement:>>> from sqlalchemy.sql import column >>> column('a') + column('b') <sqlalchemy.sql.expression.BinaryExpression object at 0x101029dd0> >>> print column('a') + column('b') a + b
-
__eq__(other)¶ - inherited from the
__eq__()method ofColumnOperatorsImplement the
==operator.In a column context, produces the clause
a = b. If the target isNone, producesa IS NULL.
-
__init__¶ - inherited from the
__init__attribute ofobjectx.__init__(...) initializes x; see help(type(x)) for signature
-
__le__(other)¶ - inherited from the
__le__()method ofColumnOperatorsImplement the
<=operator.In a column context, produces the clause
a <= b.
-
__lt__(other)¶ - inherited from the
__lt__()method ofColumnOperatorsImplement the
<operator.In a column context, produces the clause
a < b.
-
__ne__(other)¶ - inherited from the
__ne__()method ofColumnOperatorsImplement the
!=operator.In a column context, produces the clause
a != b. If the target isNone, producesa IS NOT NULL.
-
all_()¶ - inherited from the
all_()method ofColumnOperatorsProduce a
all_()clause against the parent object.버전 1.1에 추가.
-
anon_label¶ provides a constant ‘anonymous label’ for this ColumnElement.
This is a label() expression which will be named at compile time. The same label() is returned each time anon_label is called so that expressions can reference anon_label multiple times, producing the same label name at compile time.
the compiler uses this function automatically at compile time for expressions that are known to be ‘unnamed’ like binary expressions and function calls.
-
any_()¶ - inherited from the
any_()method ofColumnOperatorsProduce a
any_()clause against the parent object.버전 1.1에 추가.
-
asc()¶ - inherited from the
asc()method ofColumnOperatorsProduce a
asc()clause against the parent object.
-
base_columns¶
-
between(cleft, cright, symmetric=False)¶ - inherited from the
between()method ofColumnOperatorsProduce a
between()clause against the parent object, given the lower and upper range.
-
bind= None¶
-
cast(type_)¶ Produce a type cast, i.e.
CAST(<expression> AS <type>).This is a shortcut to the
cast()function.버전 1.0.7에 추가.
-
collate(collation)¶ - inherited from the
collate()method ofColumnOperatorsProduce a
collate()clause against the parent object, given the collation string.
-
comparator¶
-
compare(other, use_proxies=False, equivalents=None, **kw)¶ Compare this ColumnElement to another.
Special arguments understood:
매개 변수: - use_proxies¶ – when True, consider two columns that share a common base column as equivalent (i.e. shares_lineage())
- equivalents¶ – a dictionary of columns as keys mapped to sets of columns. If the given “other” column is present in this dictionary, if any of the columns in the corresponding set() pass the comparison test, the result is True. This is used to expand the comparison to other columns that may be known to be equivalent to this one via foreign key or other criterion.
-
compile(bind=None, dialect=None, **kw)¶ - inherited from the
compile()method ofClauseElementCompile this SQL expression.
The return value is a
Compiledobject. Callingstr()orunicode()on the returned value will yield a string representation of the result. TheCompiledobject also can return a dictionary of bind parameter names and values using theparamsaccessor.매개 변수: - bind¶ – An
EngineorConnectionfrom which aCompiledwill be acquired. This argument takes precedence over thisClauseElement‘s bound engine, if any. - column_keys¶ – Used for INSERT and UPDATE statements, a list of
column names which should be present in the VALUES clause of the
compiled statement. If
None, all columns from the target table object are rendered. - dialect¶ – A
Dialectinstance from which aCompiledwill be acquired. This argument takes precedence over the bind argument as well as thisClauseElement‘s bound engine, if any. - inline¶ – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
- compile_kwargs¶ –
optional dictionary of additional parameters that will be passed through to the compiler within all “visit” methods. This allows any custom flag to be passed through to a custom compilation construct, for example. It is also used for the case of passing the
literal_bindsflag through:from sqlalchemy.sql import table, column, select t = table('t', column('x')) s = select([t]).where(t.c.x == 5) print s.compile(compile_kwargs={"literal_binds": True})
버전 0.9.0에 추가.
- bind¶ – An
-
concat(other)¶ - inherited from the
concat()method ofColumnOperatorsImplement the ‘concat’ operator.
In a column context, produces the clause
a || b, or uses theconcat()operator on MySQL.
-
contains(other, **kwargs)¶ - inherited from the
contains()method ofColumnOperatorsImplement the ‘contains’ operator.
In a column context, produces the clause
LIKE '%<other>%'
-
desc()¶ - inherited from the
desc()method ofColumnOperatorsProduce a
desc()clause against the parent object.
-
description= None¶
-
distinct()¶ - inherited from the
distinct()method ofColumnOperatorsProduce a
distinct()clause against the parent object.
-
endswith(other, **kwargs)¶ - inherited from the
endswith()method ofColumnOperatorsImplement the ‘endswith’ operator.
In a column context, produces the clause
LIKE '%<other>'
-
expression¶ Return a column expression.
Part of the inspection interface; returns self.
-
foreign_keys= []¶
-
get_children(**kwargs)¶ - inherited from the
get_children()method ofClauseElementReturn immediate child elements of this
ClauseElement.This is used for visit traversal.
**kwargs may contain flags that change the collection that is returned, for example to return a subset of items in order to cut down on larger traversals, or to return child items from a different context (such as schema-level collections instead of clause-level).
-
ilike(other, escape=None)¶ - inherited from the
ilike()method ofColumnOperatorsImplement the
ilikeoperator.In a column context, produces the clause
a ILIKE other.E.g.:
select([sometable]).where(sometable.c.column.ilike("%foobar%"))
매개 변수:
-
in_(other)¶ - inherited from the
in_()method ofColumnOperatorsImplement the
inoperator.In a column context, produces the clause
a IN other. “other” may be a tuple/list of column expressions, or aselect()construct.
-
is_(other)¶ - inherited from the
is_()method ofColumnOperatorsImplement the
ISoperator.Normally,
ISis generated automatically when comparing to a value ofNone, which resolves toNULL. However, explicit usage ofISmay be desirable if comparing to boolean values on certain platforms.버전 0.7.9에 추가.
-
is_clause_element= True¶
-
is_selectable= False¶
-
isnot(other)¶ - inherited from the
isnot()method ofColumnOperatorsImplement the
IS NOToperator.Normally,
IS NOTis generated automatically when comparing to a value ofNone, which resolves toNULL. However, explicit usage ofIS NOTmay be desirable if comparing to boolean values on certain platforms.버전 0.7.9에 추가.
-
key= None¶ the ‘key’ that in some circumstances refers to this object in a Python namespace.
This typically refers to the “key” of the column as present in the
.ccollection of a selectable, e.g. sometable.c[“somekey”] would return a Column with a .key of “somekey”.
-
label(name)¶ Produce a column label, i.e.
<columnname> AS <name>.This is a shortcut to the
label()function.if ‘name’ is None, an anonymous label name will be generated.
-
like(other, escape=None)¶ - inherited from the
like()method ofColumnOperatorsImplement the
likeoperator.In a column context, produces the clause
a LIKE other.E.g.:
select([sometable]).where(sometable.c.column.like("%foobar%"))
매개 변수:
-
match(other, **kwargs)¶ - inherited from the
match()method ofColumnOperatorsImplements a database-specific ‘match’ operator.
match()attempts to resolve to a MATCH-like function or operator provided by the backend. Examples include:- Postgresql - renders
x @@ to_tsquery(y) - MySQL - renders
MATCH (x) AGAINST (y IN BOOLEAN MODE) - Oracle - renders
CONTAINS(x, y) - other backends may provide special implementations.
- Backends without any special implementation will emit the operator as “MATCH”. This is compatible with SQlite, for example.
- Postgresql - renders
-
notilike(other, escape=None)¶ - inherited from the
notilike()method ofColumnOperatorsimplement the
NOT ILIKEoperator.This is equivalent to using negation with
ColumnOperators.ilike(), i.e.~x.ilike(y).버전 0.8에 추가.
-
notin_(other)¶ - inherited from the
notin_()method ofColumnOperatorsimplement the
NOT INoperator.This is equivalent to using negation with
ColumnOperators.in_(), i.e.~x.in_(y).버전 0.8에 추가.
-
notlike(other, escape=None)¶ - inherited from the
notlike()method ofColumnOperatorsimplement the
NOT LIKEoperator.This is equivalent to using negation with
ColumnOperators.like(), i.e.~x.like(y).버전 0.8에 추가.
-
nullsfirst()¶ - inherited from the
nullsfirst()method ofColumnOperatorsProduce a
nullsfirst()clause against the parent object.
-
nullslast()¶ - inherited from the
nullslast()method ofColumnOperatorsProduce a
nullslast()clause against the parent object.
-
op(opstring, precedence=0, is_comparison=False)¶ -
produce a generic operator function.
e.g.:
somecolumn.op("*")(5)
produces:
somecolumn * 5
This function can also be used to make bitwise operators explicit. For example:
somecolumn.op('&')(0xff)
is a bitwise AND of the value in
somecolumn.매개 변수: - operator¶ – a string which will be output as the infix operator between this element and the expression passed to the generated function.
- precedence¶ –
precedence to apply to the operator, when parenthesizing expressions. A lower number will cause the expression to be parenthesized when applied against another operator with higher precedence. The default value of
0is lower than all operators except for the comma (,) andASoperators. A value of 100 will be higher or equal to all operators, and -100 will be lower than or equal to all operators.버전 0.8에 추가: - added the ‘precedence’ argument.
- is_comparison¶ –
if True, the operator will be considered as a “comparison” operator, that is which evaluates to a boolean true/false value, like
==,>, etc. This flag should be set so that ORM relationships can establish that the operator is a comparison operator when used in a custom join condition.버전 0.9.2에 추가: - added the
Operators.op.is_comparisonflag.
-
operate(op, *other, **kwargs)¶
-
params(*optionaldict, **kwargs)¶ - inherited from the
params()method ofClauseElementReturn a copy with
bindparam()elements replaced.Returns a copy of this ClauseElement with
bindparam()elements replaced with values taken from the given dictionary:>>> clause = column('x') + bindparam('foo') >>> print clause.compile().params {'foo':None} >>> print clause.params({'foo':7}).compile().params {'foo':7}
-
primary_key= False¶
-
proxy_set¶
-
reverse_operate(op, other, **kwargs)¶
-
self_group(against=None)¶
-
shares_lineage(othercolumn)¶ Return True if the given
ColumnElementhas a common ancestor to thisColumnElement.
-
startswith(other, **kwargs)¶ - inherited from the
startswith()method ofColumnOperatorsImplement the
startwithoperator.In a column context, produces the clause
LIKE '<other>%'
-
supports_execution= False¶
-
timetuple= None¶
-
type¶
-
unique_params(*optionaldict, **kwargs)¶ - inherited from the
unique_params()method ofClauseElementReturn a copy with
bindparam()elements replaced.Same functionality as
params(), except adds unique=True to affected bind parameters so that multiple statements can be used.
- a literal Python value, such as a string, integer or floating
point value, boolean, datetime,
-
class
sqlalchemy.sql.operators.ColumnOperators¶ Bases:
sqlalchemy.sql.operators.OperatorsDefines boolean, comparison, and other operators for
ColumnElementexpressions.By default, all methods call down to
operate()orreverse_operate(), passing in the appropriate operator function from the Python builtinoperatormodule or a SQLAlchemy-specific operator function fromsqlalchemy.expression.operators. For example the__eq__function:def __eq__(self, other): return self.operate(operators.eq, other)
Where
operators.eqis essentially:def eq(a, b): return a == b
The core column expression unit
ColumnElementoverridesOperators.operate()and others to return furtherColumnElementconstructs, so that the==operation above is replaced by a clause construct.See also:
Redefining and Creating New Operators
-
__add__(other)¶ Implement the
+operator.In a column context, produces the clause
a + bif the parent object has non-string affinity. If the parent object has a string affinity, produces the concatenation operator,a || b- seeColumnOperators.concat().
-
__and__(other)¶ -
Implement the
&operator.When used with SQL expressions, results in an AND operation, equivalent to
and_(), that is:a & b
is equivalent to:
from sqlalchemy import and_ and_(a, b)
Care should be taken when using
®arding operator precedence; the&operator has the highest precedence. The operands should be enclosed in parenthesis if they contain further sub expressions:(a == 2) & (b == 4)
-
__delattr__¶ - inherited from the
__delattr__attribute ofobjectx.__delattr__(‘name’) <==> del x.name
-
__div__(other)¶ Implement the
/operator.In a column context, produces the clause
a / b.
-
__eq__(other)¶ Implement the
==operator.In a column context, produces the clause
a = b. If the target isNone, producesa IS NULL.
-
__format__()¶ - inherited from the
__format__()method ofobjectdefault object formatter
-
__ge__(other)¶ Implement the
>=operator.In a column context, produces the clause
a >= b.
-
__getattribute__¶ - inherited from the
__getattribute__attribute ofobjectx.__getattribute__(‘name’) <==> x.name
-
__getitem__(index)¶ Implement the [] operator.
This can be used by some database-specific types such as Postgresql ARRAY and HSTORE.
-
__gt__(other)¶ Implement the
>operator.In a column context, produces the clause
a > b.
-
__hash__¶
-
__init__¶ - inherited from the
__init__attribute ofobjectx.__init__(...) initializes x; see help(type(x)) for signature
-
__invert__()¶ - inherited from the
__invert__()method ofOperatorsImplement the
~operator.When used with SQL expressions, results in a NOT operation, equivalent to
not_(), that is:~a
is equivalent to:
from sqlalchemy import not_ not_(a)
-
__le__(other)¶ Implement the
<=operator.In a column context, produces the clause
a <= b.
-
__lshift__(other)¶ implement the << operator.
Not used by SQLAlchemy core, this is provided for custom operator systems which want to use << as an extension point.
-
__lt__(other)¶ Implement the
<operator.In a column context, produces the clause
a < b.
-
__mod__(other)¶ Implement the
%operator.In a column context, produces the clause
a % b.
-
__mul__(other)¶ Implement the
*operator.In a column context, produces the clause
a * b.
-
__ne__(other)¶ Implement the
!=operator.In a column context, produces the clause
a != b. If the target isNone, producesa IS NOT NULL.
-
__neg__()¶ Implement the
-operator.In a column context, produces the clause
-a.
-
__new__(S, ...) → a new object with type S, a subtype of T¶ - inherited from the
__new__()method ofobject
-
__or__(other)¶ -
Implement the
|operator.When used with SQL expressions, results in an OR operation, equivalent to
or_(), that is:a | b
is equivalent to:
from sqlalchemy import or_ or_(a, b)
Care should be taken when using
|regarding operator precedence; the|operator has the highest precedence. The operands should be enclosed in parenthesis if they contain further sub expressions:(a == 2) | (b == 4)
-
__radd__(other)¶ Implement the
+operator in reverse.
-
__rdiv__(other)¶ Implement the
/operator in reverse.
-
__reduce__()¶ - inherited from the
__reduce__()method ofobjecthelper for pickle
-
__reduce_ex__()¶ - inherited from the
__reduce_ex__()method ofobjecthelper for pickle
-
__repr__¶ - inherited from the
__repr__attribute ofobject
-
__rmod__(other)¶ Implement the
%operator in reverse.
-
__rmul__(other)¶ Implement the
*operator in reverse.
-
__rshift__(other)¶ implement the >> operator.
Not used by SQLAlchemy core, this is provided for custom operator systems which want to use >> as an extension point.
-
__rsub__(other)¶ Implement the
-operator in reverse.
-
__rtruediv__(other)¶ Implement the
//operator in reverse.
-
__setattr__¶ - inherited from the
__setattr__attribute ofobjectx.__setattr__(‘name’, value) <==> x.name = value
-
__sizeof__() → int¶ - inherited from the
__sizeof__()method ofobjectsize of object in memory, in bytes
-
__str__¶ - inherited from the
__str__attribute ofobject
-
__sub__(other)¶ Implement the
-operator.In a column context, produces the clause
a - b.
-
__subclasshook__()¶ - inherited from the
__subclasshook__()method ofobjectAbstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).
-
__truediv__(other)¶ Implement the
//operator.In a column context, produces the clause
a / b.
-
between(cleft, cright, symmetric=False)¶ Produce a
between()clause against the parent object, given the lower and upper range.
-
collate(collation)¶ Produce a
collate()clause against the parent object, given the collation string.
-
concat(other)¶ Implement the ‘concat’ operator.
In a column context, produces the clause
a || b, or uses theconcat()operator on MySQL.
-
contains(other, **kwargs)¶ Implement the ‘contains’ operator.
In a column context, produces the clause
LIKE '%<other>%'
-
distinct()¶ Produce a
distinct()clause against the parent object.
-
endswith(other, **kwargs)¶ Implement the ‘endswith’ operator.
In a column context, produces the clause
LIKE '%<other>'
-
ilike(other, escape=None)¶ Implement the
ilikeoperator.In a column context, produces the clause
a ILIKE other.E.g.:
select([sometable]).where(sometable.c.column.ilike("%foobar%"))
매개 변수:
-
in_(other)¶ Implement the
inoperator.In a column context, produces the clause
a IN other. “other” may be a tuple/list of column expressions, or aselect()construct.
-
is_(other)¶ Implement the
ISoperator.Normally,
ISis generated automatically when comparing to a value ofNone, which resolves toNULL. However, explicit usage ofISmay be desirable if comparing to boolean values on certain platforms.버전 0.7.9에 추가.
-
isnot(other)¶ Implement the
IS NOToperator.Normally,
IS NOTis generated automatically when comparing to a value ofNone, which resolves toNULL. However, explicit usage ofIS NOTmay be desirable if comparing to boolean values on certain platforms.버전 0.7.9에 추가.
-
like(other, escape=None)¶ Implement the
likeoperator.In a column context, produces the clause
a LIKE other.E.g.:
select([sometable]).where(sometable.c.column.like("%foobar%"))
매개 변수:
-
match(other, **kwargs)¶ Implements a database-specific ‘match’ operator.
match()attempts to resolve to a MATCH-like function or operator provided by the backend. Examples include:- Postgresql - renders
x @@ to_tsquery(y) - MySQL - renders
MATCH (x) AGAINST (y IN BOOLEAN MODE) - Oracle - renders
CONTAINS(x, y) - other backends may provide special implementations.
- Backends without any special implementation will emit the operator as “MATCH”. This is compatible with SQlite, for example.
- Postgresql - renders
-
notilike(other, escape=None)¶ implement the
NOT ILIKEoperator.This is equivalent to using negation with
ColumnOperators.ilike(), i.e.~x.ilike(y).버전 0.8에 추가.
-
notin_(other)¶ implement the
NOT INoperator.This is equivalent to using negation with
ColumnOperators.in_(), i.e.~x.in_(y).버전 0.8에 추가.
-
notlike(other, escape=None)¶ implement the
NOT LIKEoperator.This is equivalent to using negation with
ColumnOperators.like(), i.e.~x.like(y).버전 0.8에 추가.
-
nullsfirst()¶ Produce a
nullsfirst()clause against the parent object.
-
nullslast()¶ Produce a
nullslast()clause against the parent object.
-
op(opstring, precedence=0, is_comparison=False)¶ -
produce a generic operator function.
e.g.:
somecolumn.op("*")(5)
produces:
somecolumn * 5
This function can also be used to make bitwise operators explicit. For example:
somecolumn.op('&')(0xff)
is a bitwise AND of the value in
somecolumn.매개 변수: - operator¶ – a string which will be output as the infix operator between this element and the expression passed to the generated function.
- precedence¶ –
precedence to apply to the operator, when parenthesizing expressions. A lower number will cause the expression to be parenthesized when applied against another operator with higher precedence. The default value of
0is lower than all operators except for the comma (,) andASoperators. A value of 100 will be higher or equal to all operators, and -100 will be lower than or equal to all operators.버전 0.8에 추가: - added the ‘precedence’ argument.
- is_comparison¶ –
if True, the operator will be considered as a “comparison” operator, that is which evaluates to a boolean true/false value, like
==,>, etc. This flag should be set so that ORM relationships can establish that the operator is a comparison operator when used in a custom join condition.버전 0.9.2에 추가: - added the
Operators.op.is_comparisonflag.
-
operate(op, *other, **kwargs)¶ -
Operate on an argument.
This is the lowest level of operation, raises
NotImplementedErrorby default.Overriding this on a subclass can allow common behavior to be applied to all operations. For example, overriding
ColumnOperatorsto applyfunc.lower()to the left and right side:class MyComparator(ColumnOperators): def operate(self, op, other): return op(func.lower(self), func.lower(other))
매개 변수:
-
reverse_operate(op, other, **kwargs)¶ - inherited from the
reverse_operate()method ofOperatorsReverse operate on an argument.
Usage is the same as
operate().
-
startswith(other, **kwargs)¶ Implement the
startwithoperator.In a column context, produces the clause
LIKE '<other>%'
-
timetuple= None¶ Hack, allows datetime objects to be compared on the LHS.
-
-
class
sqlalchemy.sql.base.DialectKWArgs¶ Establish the ability for a class to have dialect-specific arguments with defaults and constructor validation.
The
DialectKWArgsinteracts with theDefaultDialect.construct_argumentspresent on a dialect.-
classmethod
argument_for(dialect_name, argument_name, default)¶ Add a new kind of dialect-specific keyword argument for this class.
E.g.:
Index.argument_for("mydialect", "length", None) some_index = Index('a', 'b', mydialect_length=5)
The
DialectKWArgs.argument_for()method is a per-argument way adding extra arguments to theDefaultDialect.construct_argumentsdictionary. This dictionary provides a list of argument names accepted by various schema-level constructs on behalf of a dialect.New dialects should typically specify this dictionary all at once as a data member of the dialect class. The use case for ad-hoc addition of argument names is typically for end-user code that is also using a custom compilation scheme which consumes the additional arguments.
매개 변수: - dialect_name¶ – name of a dialect. The dialect must be
locatable, else a
NoSuchModuleErroris raised. The dialect must also include an existingDefaultDialect.construct_argumentscollection, indicating that it participates in the keyword-argument validation and default system, elseArgumentErroris raised. If the dialect does not include this collection, then any keyword argument can be specified on behalf of this dialect already. All dialects packaged within SQLAlchemy include this collection, however for third party dialects, support may vary. - argument_name¶ – name of the parameter.
- default¶ – default value of the parameter.
버전 0.9.4에 추가.
- dialect_name¶ – name of a dialect. The dialect must be
locatable, else a
-
dialect_kwargs¶ A collection of keyword arguments specified as dialect-specific options to this construct.
The arguments are present here in their original
<dialect>_<kwarg>format. Only arguments that were actually passed are included; unlike theDialectKWArgs.dialect_optionscollection, which contains all options known by this dialect including defaults.The collection is also writable; keys are accepted of the form
<dialect>_<kwarg>where the value will be assembled into the list of options.버전 0.9.2에 추가.
버전 0.9.4으로 변경: The
DialectKWArgs.dialect_kwargscollection is now writable.더 보기
DialectKWArgs.dialect_options- nested dictionary form
-
dialect_options¶ A collection of keyword arguments specified as dialect-specific options to this construct.
This is a two-level nested registry, keyed to
<dialect_name>and<argument_name>. For example, thepostgresql_whereargument would be locatable as:arg = my_object.dialect_options['postgresql']['where']
버전 0.9.2에 추가.
더 보기
DialectKWArgs.dialect_kwargs- flat dictionary form
-
kwargs¶ A synonym for
DialectKWArgs.dialect_kwargs.
-
classmethod
-
class
sqlalchemy.sql.expression.Extract(field, expr, **kwargs)¶ Bases:
sqlalchemy.sql.expression.ColumnElementRepresent a SQL EXTRACT clause,
extract(field FROM expr).
-
class
sqlalchemy.sql.elements.False_¶ Bases:
sqlalchemy.sql.expression.ColumnElementRepresent the
falsekeyword, or equivalent, in a SQL statement.
-
class
sqlalchemy.sql.expression.FunctionFilter(func, *criterion)¶ Bases:
sqlalchemy.sql.expression.ColumnElementRepresent a function FILTER clause.
This is a special operator against aggregate and window functions, which controls which rows are passed to it. It’s supported only by certain database backends.
Invocation of
FunctionFilteris viaFunctionElement.filter():func.count(1).filter(True)
버전 1.0.0에 추가.
-
__init__(func, *criterion)¶ Construct a new
FunctionFilterobject.This constructor is mirrored as a public API function; see
funcfilter()for a full usage and argument description.
-
filter(*criterion)¶ Produce an additional FILTER against the function.
This method adds additional criteria to the initial criteria set up by
FunctionElement.filter().Multiple criteria are joined together at SQL render time via
AND.
-
over(partition_by=None, order_by=None)¶ Produce an OVER clause against this filtered function.
Used against aggregate or so-called “window” functions, for database backends that support window functions.
The expression:
func.rank().filter(MyClass.y > 5).over(order_by='x')
is shorthand for:
from sqlalchemy import over, funcfilter over(funcfilter(func.rank(), MyClass.y > 5), order_by='x')
See
over()for a full description.
-
-
class
sqlalchemy.sql.expression.Label(name, element, type_=None)¶ Bases:
sqlalchemy.sql.expression.ColumnElementRepresents a column label (AS).
Represent a label, as typically applied to any column-level element using the
ASsql keyword.
-
class
sqlalchemy.sql.elements.Null¶ Bases:
sqlalchemy.sql.expression.ColumnElementRepresent the NULL keyword in a SQL statement.
-
class
sqlalchemy.sql.expression.Over(element, partition_by=None, order_by=None)¶ Bases:
sqlalchemy.sql.expression.ColumnElementRepresent an OVER clause.
This is a special operator against a so-called “window” function, as well as any aggregate function, which produces results relative to the result set itself. It’s supported only by certain database backends.
-
class
sqlalchemy.sql.expression.TextClause(text, bind=None)¶ Bases:
sqlalchemy.sql.expression.Executable,sqlalchemy.sql.expression.ClauseElementRepresent a literal SQL text fragment.
E.g.:
from sqlalchemy import text t = text("SELECT * FROM users") result = connection.execute(t)
The
Textconstruct is produced using thetext()function; see that function for full documentation.더 보기
-
bindparams(*binds, **names_to_values)¶ Establish the values and/or types of bound parameters within this
TextClauseconstruct.Given a text construct such as:
from sqlalchemy import text stmt = text("SELECT id, name FROM user WHERE name=:name " "AND timestamp=:timestamp")
the
TextClause.bindparams()method can be used to establish the initial value of:nameand:timestamp, using simple keyword arguments:stmt = stmt.bindparams(name='jack', timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5))
Where above, new
BindParameterobjects will be generated with the namesnameandtimestamp, and values ofjackanddatetime.datetime(2012, 10, 8, 15, 12, 5), respectively. The types will be inferred from the values given, in this caseStringandDateTime.When specific typing behavior is needed, the positional
*bindsargument can be used in which to specifybindparam()constructs directly. These constructs must include at least thekeyargument, then an optional value and type:from sqlalchemy import bindparam stmt = stmt.bindparams( bindparam('name', value='jack', type_=String), bindparam('timestamp', type_=DateTime) )
Above, we specified the type of
DateTimefor thetimestampbind, and the type ofStringfor thenamebind. In the case ofnamewe also set the default value of"jack".Additional bound parameters can be supplied at statement execution time, e.g.:
result = connection.execute(stmt, timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5))
The
TextClause.bindparams()method can be called repeatedly, where it will re-use existingBindParameterobjects to add new information. For example, we can callTextClause.bindparams()first with typing information, and a second time with value information, and it will be combined:stmt = text("SELECT id, name FROM user WHERE name=:name " "AND timestamp=:timestamp") stmt = stmt.bindparams( bindparam('name', type_=String), bindparam('timestamp', type_=DateTime) ) stmt = stmt.bindparams( name='jack', timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5) )
버전 0.9.0에 추가: The
TextClause.bindparams()method supersedes the argumentbindparamspassed totext().
-
columns(*cols, **types)¶ Turn this
TextClauseobject into aTextAsFromobject that can be embedded into another statement.This function essentially bridges the gap between an entirely textual SELECT statement and the SQL expression language concept of a “selectable”:
from sqlalchemy.sql import column, text stmt = text("SELECT id, name FROM some_table") stmt = stmt.columns(column('id'), column('name')).alias('st') stmt = select([mytable]).\ select_from( mytable.join(stmt, mytable.c.name == stmt.c.name) ).where(stmt.c.id > 5)
Above, we pass a series of
column()elements to theTextClause.columns()method positionally. Thesecolumn()elements now become first class elements upon theTextAsFrom.ccolumn collection, just like any other selectable.The column expressions we pass to
TextClause.columns()may also be typed; when we do so, theseTypeEngineobjects become the effective return type of the column, so that SQLAlchemy’s result-set-processing systems may be used on the return values. This is often needed for types such as date or boolean types, as well as for unicode processing on some dialect configurations:stmt = text("SELECT id, name, timestamp FROM some_table") stmt = stmt.columns( column('id', Integer), column('name', Unicode), column('timestamp', DateTime) ) for id, name, timestamp in connection.execute(stmt): print(id, name, timestamp)
As a shortcut to the above syntax, keyword arguments referring to types alone may be used, if only type conversion is needed:
stmt = text("SELECT id, name, timestamp FROM some_table") stmt = stmt.columns( id=Integer, name=Unicode, timestamp=DateTime ) for id, name, timestamp in connection.execute(stmt): print(id, name, timestamp)
The positional form of
TextClause.columns()also provides the unique feature of positional column targeting, which is particularly useful when using the ORM with complex textual queries. If we specify the columns from our model toTextClause.columns(), the result set will match to those columns positionally, meaning the name or origin of the column in the textual SQL doesn’t matter:stmt = text("SELECT users.id, addresses.id, users.id, " "users.name, addresses.email_address AS email " "FROM users JOIN addresses ON users.id=addresses.user_id " "WHERE users.id = 1").columns( User.id, Address.id, Address.user_id, User.name, Address.email_address ) query = session.query(User).from_statement(stmt).options( contains_eager(User.addresses))
버전 1.1에 추가: the
TextClause.columns()method now offers positional column targeting in the result set when the column expressions are passed purely positionally.The
TextClause.columns()method provides a direct route to callingFromClause.alias()as well asSelectBase.cte()against a textual SELECT statement:stmt = stmt.columns(id=Integer, name=String).cte('st') stmt = select([sometable]).where(sometable.c.id == stmt.c.id)
버전 0.9.0에 추가:
text()can now be converted into a fully featured “selectable” construct using theTextClause.columns()method. This method supersedes thetypemapargument totext().
-
-
class
sqlalchemy.sql.expression.Tuple(*clauses, **kw)¶ Bases:
sqlalchemy.sql.expression.ClauseList,sqlalchemy.sql.expression.ColumnElementRepresent a SQL tuple.
-
class
sqlalchemy.sql.expression.WithinGroup(element, *order_by)¶ Bases:
sqlalchemy.sql.expression.ColumnElementRepresent a WITHIN GROUP (ORDER BY) clause.
This is a special operator against so-called so-called “ordered set aggregate” and “hypothetical set aggregate” functions, including
percentile_cont(),rank(),dense_rank(), etc.It’s supported only by certain database backends, such as PostgreSQL, Oracle and MS SQL Server.
The
WithinGroupconsturct extracts its type from the methodFunctionElement.within_group_type(). If this returnsNone, the function’s.typeis used.-
__init__(element, *order_by)¶ Construct a new
WithinGroupobject.This constructor is mirrored as a public API function; see
within_group()for a full usage and argument description.
-
over(partition_by=None, order_by=None)¶ Produce an OVER clause against this
WithinGroupconstruct.This function has the same signature as that of
FunctionElement.over().
-
-
class
sqlalchemy.sql.elements.True_¶ Bases:
sqlalchemy.sql.expression.ColumnElementRepresent the
truekeyword, or equivalent, in a SQL statement.
-
class
sqlalchemy.sql.expression.TypeCoerce(expression, type_)¶ Bases:
sqlalchemy.sql.expression.ColumnElementRepresent a Python-side type-coercion wrapper.
TypeCoercesupplies theexpression.type_coerce()function; see that function for usage details.버전 1.1으로 변경: The
type_coerce()function now produces a persistentTypeCoercewrapper object rather than translating the given object in place.-
__init__(expression, type_)¶ Construct a new
TypeCoerceobject.This constructor is mirrored as a public API function; see
type_coerce()for a full usage and argument description.
-
-
class
sqlalchemy.sql.operators.custom_op(opstring, precedence=0, is_comparison=False, natural_self_precedent=False)¶ Represent a ‘custom’ operator.
custom_opis normally instantitated when theColumnOperators.op()method is used to create a custom operator callable. The class can also be used directly when programmatically constructing expressions. E.g. to represent the “factorial” operation:from sqlalchemy.sql import UnaryExpression from sqlalchemy.sql import operators from sqlalchemy import Numeric unary = UnaryExpression(table.c.somecolumn, modifier=operators.custom_op("!"), type_=Numeric)
-
class
sqlalchemy.sql.operators.Operators¶ Base of comparison and logical operators.
Implements base methods
operate()andreverse_operate(), as well as__and__(),__or__(),__invert__().Usually is used via its most common subclass
ColumnOperators.-
__and__(other)¶ Implement the
&operator.When used with SQL expressions, results in an AND operation, equivalent to
and_(), that is:a & b
is equivalent to:
from sqlalchemy import and_ and_(a, b)
Care should be taken when using
®arding operator precedence; the&operator has the highest precedence. The operands should be enclosed in parenthesis if they contain further sub expressions:(a == 2) & (b == 4)
-
__invert__()¶ Implement the
~operator.When used with SQL expressions, results in a NOT operation, equivalent to
not_(), that is:~a
is equivalent to:
from sqlalchemy import not_ not_(a)
-
__or__(other)¶ Implement the
|operator.When used with SQL expressions, results in an OR operation, equivalent to
or_(), that is:a | b
is equivalent to:
from sqlalchemy import or_ or_(a, b)
Care should be taken when using
|regarding operator precedence; the|operator has the highest precedence. The operands should be enclosed in parenthesis if they contain further sub expressions:(a == 2) | (b == 4)
-
op(opstring, precedence=0, is_comparison=False)¶ produce a generic operator function.
e.g.:
somecolumn.op("*")(5)
produces:
somecolumn * 5
This function can also be used to make bitwise operators explicit. For example:
somecolumn.op('&')(0xff)
is a bitwise AND of the value in
somecolumn.매개 변수: - operator¶ – a string which will be output as the infix operator between this element and the expression passed to the generated function.
- precedence¶ –
precedence to apply to the operator, when parenthesizing expressions. A lower number will cause the expression to be parenthesized when applied against another operator with higher precedence. The default value of
0is lower than all operators except for the comma (,) andASoperators. A value of 100 will be higher or equal to all operators, and -100 will be lower than or equal to all operators.버전 0.8에 추가: - added the ‘precedence’ argument.
- is_comparison¶ –
if True, the operator will be considered as a “comparison” operator, that is which evaluates to a boolean true/false value, like
==,>, etc. This flag should be set so that ORM relationships can establish that the operator is a comparison operator when used in a custom join condition.버전 0.9.2에 추가: - added the
Operators.op.is_comparisonflag.
-
operate(op, *other, **kwargs)¶ Operate on an argument.
This is the lowest level of operation, raises
NotImplementedErrorby default.Overriding this on a subclass can allow common behavior to be applied to all operations. For example, overriding
ColumnOperatorsto applyfunc.lower()to the left and right side:class MyComparator(ColumnOperators): def operate(self, op, other): return op(func.lower(self), func.lower(other))
매개 변수:
-
reverse_operate(op, other, **kwargs)¶ Reverse operate on an argument.
Usage is the same as
operate().
-
-
class
sqlalchemy.sql.elements.quoted_name¶ Bases:
sqlalchemy.util.langhelpers.MemoizedSlots,__builtin__.unicodeRepresent a SQL identifier combined with quoting preferences.
quoted_nameis a Python unicode/str subclass which represents a particular identifier name along with aquoteflag. Thisquoteflag, when set toTrueorFalse, overrides automatic quoting behavior for this identifier in order to either unconditionally quote or to not quote the name. If left at its default ofNone, quoting behavior is applied to the identifier on a per-backend basis based on an examination of the token itself.A
quoted_nameobject withquote=Trueis also prevented from being modified in the case of a so-called “name normalize” option. Certain database backends, such as Oracle, Firebird, and DB2 “normalize” case-insensitive names as uppercase. The SQLAlchemy dialects for these backends convert from SQLAlchemy’s lower-case-means-insensitive convention to the upper-case-means-insensitive conventions of those backends. Thequote=Trueflag here will prevent this conversion from occurring to support an identifier that’s quoted as all lower case against such a backend.The
quoted_nameobject is normally created automatically when specifying the name for key schema constructs such asTable,Column, and others. The class can also be passed explicitly as the name to any function that receives a name which can be quoted. Such as to use theEngine.has_table()method with an unconditionally quoted name:from sqlaclchemy import create_engine from sqlalchemy.sql.elements import quoted_name engine = create_engine("oracle+cx_oracle://some_dsn") engine.has_table(quoted_name("some_table", True))
The above logic will run the “has table” logic against the Oracle backend, passing the name exactly as
"some_table"without converting to upper case.버전 0.9.0에 추가.
-
class
sqlalchemy.sql.expression.UnaryExpression(element, operator=None, modifier=None, type_=None, negate=None, wraps_column_expression=False)¶ Bases:
sqlalchemy.sql.expression.ColumnElementDefine a ‘unary’ expression.
A unary expression has a single column expression and an operator. The operator can be placed on the left (where it is called the ‘operator’) or right (where it is called the ‘modifier’) of the column expression.
UnaryExpressionis the basis for several unary operators including those used bydesc(),asc(),distinct(),nullsfirst()andnullslast().-
compare(other, **kw)¶ Compare this
UnaryExpressionagainst the givenClauseElement.
-
