在SQLAlchemy中通过一定的抽象使用复杂SQL(SQLAlchemy官方文档节选)

Using More Specific Text with table(), literal_column(), andcolumn()

在SQLAlchemy中通过table()、literal_column()和column()使用更加复杂的SQL

(笔者备注:补充一下背景,下面这一段前面是讲text() 的,text()可以用在select(…).where(…).select_from中,通过输入表名、条件,甚至是完整的sql直接去执行,而不用使用类似于Table()、Column()等MetaData对象。但是,这种方法其实是绕过了SQLAlchemy的抽象,和直接使用sql类似,笔者是建议除非迫不得已sql非常特殊,可以使用这种方法,一般情况下还是遵循SQLAlchemy Core的抽象较为合理,代码在不同数据库之间的可移植性也较强。SQLAlchemy的设计是较为合理的,较好的兼顾了不同层次的抽象要求,所以下面这段原文其实是给出了一个更好的折衷用法)

We can move our level of structure back in the other direction too, by using column(), literal_column(), and table() for some of the key elements of our statement. Using these constructs, we can get some more expression capabilities than if we used text() directly, as they provide to the Core more information about how the strings they store are to be used, but still without the need to get into full Table based metadata. Below, we also specify the String datatype for two of the key literal_column() objects, so that the string-specific concatenation operator becomes available. We also use literal_column() in order to use table-qualified expressions, e.g. users.fullname, that will be rendered as is; using column() implies an individual column name that may be quoted:

我们可以通过对我们sql语句的关键要素使用column()、literal_column()、table()等函数,使我们的sql整体结构向更好更合理的抽象层次发展。由于我们向SQLAlchemy Core提供了更多关于字符串所指的对象如何使用的信息,相对于直接使用text(),通过使用以上这些函数,我们能够得到更多的表达式功能,同时,也不需要完全使用基于metadata的Table()等对象的抽象。下面的代码中,我们对两个关键字字段的literal_column()对象,指定了字符串(String)数据类型,这样的话就可以使用python中的字符串连接运算符(+)。另外,我们为了指定特定表中的字段,也使用了literal_column()对象,例如:users.fullname,这个在后续解析执行中,会保留users前缀;而使用column()则意味着一个可以直接引用的单独列名。

>>> from sqlalchemy import select, and_, text, String
>>> from sqlalchemy.sql import table, literal_column
>>> s = select([
...    literal_column("users.fullname", String) +
...    ', ' +
...    literal_column("addresses.email_address").label("title")
... ]).\
...    where(
...        and_(
...            literal_column("users.id") == literal_column("addresses.user_id"),
...            text("users.name BETWEEN 'm' AND 'z'"),
...            text(
...                "(addresses.email_address LIKE :x OR "
...                "addresses.email_address LIKE :y)")
...        )
...    ).select_from(table('users')).select_from(table('addresses'))

SQL>>> conn.execute(s, x='%@aol.com', y='%@msn.com').fetchall()

相当于执行的SQL是:
SELECT users.fullname || ? || addresses.email_address AS anon_1
FROM users, addresses
WHERE users.id = addresses.user_id
AND users.name BETWEEN 'm' AND 'z'
AND (addresses.email_address LIKE ? OR addresses.email_address LIKE ?)
上面3个?参数分别代表:
(', ', '%@aol.com', '%@msn.com')

执行结果是:
[(u'Wendy Williams, wendy@aol.com',)]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值