我正在尝试 SELECT FOR SHARE 表中的一组行,以便它们被锁定直到事务结束。我正在使用 SQLAlchemy 0.7.9 在 PostgreSQL 9.1.6 数据库中执行此操作。这是有问题的python代码:
NUM_TERMS = 10
conn = engine.connect()
get_terms = select([search_terms.c.term_id, search_terms.c.term],
and_(search_terms.c.lock==False,
search_terms.c.status==False),
order_by=search_terms.c.term,
limit=NUM_TERMS, for_update="read")
trans = conn.begin()
try:
search_terms = conn.execute(get_terms).fetchall()
for term in search_terms:
lock_terms = update(search_terms).\
where(search_terms.c.term_id==term.term_id).\
values(lock=True)
conn.execute(lock_terms)
if trans.commit():
<do things with the search terms>
except:
trans.rollback()
问题是上面选择代码生成的SQL查询不是FOR SHARE,而是FOR UPDATE:
SELECT search_terms.term_id, search_terms.term
FROM search_terms
WHERE search_terms.lock = :lock_1 AND search_terms.status = :status_1
ORDER BY search_terms.term
LIMIT :param_1 FOR UPDATE
根据SQLAlchemy API docs,在“for_update”参数描述下:
对于 Postgresql 方言,值“read”和“read_nowait”分别转换为 FOR SHARE 和 FOR SHARE NOWAIT。
根据上面,编译出来的SQL语句应该是FOR SHARE,其实不是。我的代码中的错误在哪里?