本文整理匯總了Python中sqlalchemy.sql.expression.text方法的典型用法代碼示例。如果您正苦於以下問題:Python expression.text方法的具體用法?Python expression.text怎麽用?Python expression.text使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類sqlalchemy.sql.expression
的用法示例。
在下文中一共展示了expression.text方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: series_list
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import text [as 別名]
def series_list():
if current_user.check_visibility(constants.SIDEBAR_SERIES):
if current_user.series_view == 'list':
entries = calibre_db.session.query(db.Series, func.count('books_series_link.book').label('count')) \
.join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters()) \
.group_by(text('books_series_link.series')).order_by(db.Series.sort).all()
charlist = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('char')) \
.join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters()) \
.group_by(func.upper(func.substr(db.Series.sort, 1, 1))).all()
return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist,
title=_(u"Series"), page="serieslist", data="series")
else:
entries = calibre_db.session.query(db.Books, func.count('books_series_link').label('count')) \
.join(db.books_series_link).join(db.Series).filter(calibre_db.common_filters()) \
.group_by(text('books_series_link.series')).order_by(db.Series.sort).all()
charlist = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('char')) \
.join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters()) \
.group_by(func.upper(func.substr(db.Series.sort, 1, 1))).all()
return render_title_template('grid.html', entries=entries, folder='web.books_list', charlist=charlist,
title=_(u"Series"), page="serieslist", data="series", bodyClass="grid-view")
else:
abort(404)
示例2: language_overview
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import text [as 別名]
def language_overview():
if current_user.check_visibility(constants.SIDEBAR_LANGUAGE):
charlist = list()
if current_user.filter_language() == u"all":
languages = calibre_db.speaking_language()
# ToDo: generate first character list for languages
else:
try:
cur_l = LC.parse(current_user.filter_language())
except UnknownLocaleError:
cur_l = None
languages = calibre_db.session.query(db.Languages).filter(
db.Languages.lang_code == current_user.filter_language()).all()
if cur_l:
languages[0].name = cur_l.get_language_name(get_locale())
else:
languages[0].name = _(isoLanguages.get(part3=languages[0].lang_code).name)
lang_counter = calibre_db.session.query(db.books_languages_link,
func.count('books_languages_link.book').label('bookcount')).group_by(
text('books_languages_link.lang_code')).all()
return render_title_template('languages.html', languages=languages, lang_counter=lang_counter,
charlist=charlist, title=_(u"Languages"), page="langlist",
data="language")
else:
abort(404)
示例3: speaking_language
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import text [as 別名]
def speaking_language(self, languages=None):
from . import get_locale
if not languages:
languages = self.session.query(Languages) \
.join(books_languages_link) \
.join(Books) \
.filter(self.common_filters()) \
.group_by(text('books_languages_link.lang_code')).all()
for lang in languages:
try:
cur_l = LC.parse(lang.lang_code)
lang.name = cur_l.get_language_name(get_locale())
except UnknownLocaleError:
lang.name = _(isoLanguages.get(part3=lang.lang_code).name)
return languages
示例4: get_db_time
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import text [as 別名]
def get_db_time():
""" Gives the utc time on the db. """
s = session.get_session()
try:
storage_date_format = None
if s.bind.dialect.name == 'oracle':
query = select([text("sys_extract_utc(systimestamp)")])
elif s.bind.dialect.name == 'mysql':
query = select([text("utc_timestamp()")])
elif s.bind.dialect.name == 'sqlite':
query = select([text("datetime('now', 'utc')")])
storage_date_format = '%Y-%m-%d %H:%M:%S'
else:
query = select([func.current_date()])
for now, in s.execute(query):
if storage_date_format:
return datetime.strptime(now, storage_date_format)
return now
finally:
s.remove()
示例5: filter_thread_work
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import text [as 別名]
def filter_thread_work(session, query, total_threads, thread_id, hash_variable=None):
""" Filters a query to partition thread workloads based on the thread id and total number of threads """
if thread_id is not None and total_threads is not None and (total_threads - 1) > 0:
if session.bind.dialect.name == 'oracle':
bindparams = [bindparam('thread_id', thread_id), bindparam('total_threads', total_threads - 1)]
if not hash_variable:
query = query.filter(text('ORA_HASH(id, :total_threads) = :thread_id', bindparams=bindparams))
else:
query = query.filter(text('ORA_HASH(%s, :total_threads) = :thread_id' % (hash_variable), bindparams=bindparams))
elif session.bind.dialect.name == 'mysql':
if not hash_variable:
query = query.filter(text('mod(md5(id), %s) = %s' % (total_threads, thread_id)))
else:
query = query.filter(text('mod(md5(%s), %s) = %s' % (hash_variable, total_threads, thread_id)))
elif session.bind.dialect.name == 'postgresql':
if not hash_variable:
query = query.filter(text('mod(abs((\'x\'||md5(id::text))::bit(32)::int), %s) = %s' % (total_threads, thread_id)))
else:
query = query.filter(text('mod(abs((\'x\'||md5(%s::text))::bit(32)::int), %s) = %s' % (hash_variable, total_threads, thread_id)))
return query
示例6: test_indexes_table
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import text [as 別名]
def test_indexes_table(metadata):
simple_items = Table("simple_items", metadata, Column("id", INTEGER), Column("number", INTEGER), Column("text", VARCHAR))
simple_items.indexes.add(Index("idx_number", simple_items.c.number))
simple_items.indexes.add(Index("idx_text_number", simple_items.c.text, simple_items.c.number, unique=True))
simple_items.indexes.add(Index("idx_text", simple_items.c.text, unique=True))
assert (
generate_code(metadata)
== """\
# coding: utf-8
from sqlalchemy import Column, Index, Integer, MetaData, String, Table
metadata = MetaData()
t_simple_items = Table(
'simple_items', metadata,
Column('id', Integer),
Column('number', Integer, index=True),
Column('text', String, unique=True),
Index('idx_text_number', 'text', 'number', unique=True)
)
"""
)
示例7: test_pk_default
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import text [as 別名]
def test_pk_default(metadata):
Table("simple_items", metadata, Column("id", INTEGER, primary_key=True, server_default=text("uuid_generate_v4()")))
assert (
generate_code(metadata)
== """\
# coding: utf-8
from sqlalchemy import Column, Integer, text
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
class SimpleItem(Base):
__tablename__ = 'simple_items'
id = Column(Integer, primary_key=True, server_default=text("uuid_generate_v4()"))
"""
)
示例8: test_server_default_double_quotes
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import text [as 別名]
def test_server_default_double_quotes(metadata):
Table("simple", metadata, Column("id", INTEGER, primary_key=True, server_default=text('nextval("foo")')))
assert (
generate_code(metadata)
== """\
# coding: utf-8
from sqlalchemy import Column, Integer, text
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
class Simple(Base):
__tablename__ = 'simple'
id = Column(Integer, primary_key=True, server_default=text("nextval(\\"foo\\")"))
"""
)
示例9: append
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import text [as 別名]
def append(self,obj):
with self.obj.backend.transaction(implicit = True):
#if the object is not yet in a DB, we save it first.
if obj.pk is None:
self.obj.backend.save(obj)
relationship_table = self.params['relationship_table']
condition = and_(relationship_table.c[self.params['related_pk_field_name']] == obj.pk,
relationship_table.c[self.params['pk_field_name']] == self.obj.pk)
s = select([func.count(text('*'))]).where(condition)
result = self.obj.backend.connection.execute(s)
cnt = result.first()[0]
if cnt:
return #the object is already inside
values = {
self.params['pk_field_name'] : self.obj.pk,
self.params['related_pk_field_name'] : obj.pk
}
insert = relationship_table.insert().values(**values)
self.obj.backend.connection.execute(insert)
self._queryset = None
示例10: GetRolesForUser
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import text [as 別名]
def GetRolesForUser(self, userName):
'''
Get all the roles that the user, with the given username, belongs to.
'''
#Create string builder object
sb = []
sb.append("select rolname from pg_user ")
sb.append("join pg_auth_members on (pg_user.usesysid=pg_auth_members.member) ")
sb.append("join pg_roles on (pg_roles.oid=pg_auth_members.roleid) ")
sb.append("where pg_user.usename=:uname")
sql = ''.join(sb)
t = text(sql)
result = self._execute(t,uname = userName)
#Iterate through result proxy to get the rolenames
userRoles = []
for row in result:
userRoles.append(row["rolname"])
return userRoles
示例11: CreateRole
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import text [as 別名]
def CreateRole(self,roleName,description='',grantSchema = 'public'):
'''
Create a new role
'''
sql = []
sql.append("CREATE ROLE %s CREATEROLE;"%(roleName,))
if description != "":
sql.append("COMMENT ON ROLE %s is '%s';"%(roleName,description))
# Grant privileges to the new role so that users in this role can be able
# to access the tables and relations.
# The specified schema will have all the tables and relations granted with
# all privileges.
sql.append("GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA %s TO %s;" %
(grantSchema,roleName)
)
sequences = profile_sequences(self._current_profile.prefix)
for profile_sequence in sequences:
sql.append('GRANT ALL ON SEQUENCE {}.{} TO GROUP {} WITH GRANT OPTION;'.
format(grantSchema, profile_sequence, roleName))
sqlStr = ''.join(sql)
t = text(sqlStr)
self._execute(t)
示例12: getUser
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import text [as 別名]
def getUser(self,username):
'''
Gets the user object based on the username.
Returns 'None' if not found
'''
user = None
t = text("select valuntil from pg_user where usename = :uname")
conn = self._engine.connect()
result = conn.execute(t,uname = username).fetchone()
if result is not None:
user = User(username)
#Get the date component only - first ten characters
valDate = result["valuntil"]
if valDate is not None:
valDate = valDate[:10]
user.Validity = valDate
return user
示例13: getAllUsers
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import text [as 別名]
def getAllUsers(self):
'''
Returns the names of all user accounts in the cluster of the PostgreSQL server
'''
t = text("select usename from pg_user")
conn = self._engine.connect()
result = conn.execute(t)
users = []
for row in result:
username = row["usename"]
#Exclude the 'postres' account from this list
if username != 'postgres':
users.append(username)
return users
示例14: pg_views
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import text [as 別名]
def pg_views(schema="public"):
"""
Returns the views in the given schema minus the default PostGIS views.
"""
t = text("SELECT table_name FROM information_schema.tables WHERE table_schema = :tschema and table_type = :tbtype " \
"ORDER BY table_name ASC")
result = _execute(t, tschema = schema, tbtype = "VIEW")
pgViews = []
for r in result:
viewName = r["table_name"]
#Remove default PostGIS tables
viewIndex = getIndex(_postGISViews, viewName)
if viewIndex == -1:
pgViews.append(viewName)
return pgViews
示例15: view_details
# 需要導入模塊: from sqlalchemy.sql import expression [as 別名]
# 或者: from sqlalchemy.sql.expression import text [as 別名]
def view_details(self, view):
"""
Gets the view definition/query
used to create it.
:param view: The name of the view.
:type view: String
:return: The definition/query.
:rtype: String
"""
if view in pg_views():
t = text('SELECT definition '
'FROM pg_views '
'WHERE viewname=:view_name;'
)
result = _execute(t, view_name=view)
definition = []
for row in result:
definition.append(row[0])
return definition[0]