SQLALchemy新手,这是我尝试重新创建此查询:
SELECT
database_server_id || 'dr' database_server_id
, CASE
WHEN database_server_id LIKE 'cluster1' AND name IS NULL THEN 'canvas'
WHEN database_server_id LIKE 'cluster4' AND name IS NULL THEN 'canvas'
WHEN name IS NULL THEN database_server_id
ELSE name
END AS database_name
,SUBSTRING(database_server_id FROM '\d+$')::INT cluster_id
,CASE
WHEN name IS NULL THEN SUBSTRING(database_server_id FROM '\d+$')::INT
ELSE SUBSTRING(name FROM '\d+$')::INT
END AS shard_id
FROM canvas.switchman_shards
WHERE database_server_id LIKE 'cluster%'
ORDER BY cluster_id, shard_id
我使用声明来创建类,然后使用hybrid_properties
来处理其他逻辑。让我知道我犯了什么错误!
class SwitchmanShards(Base):
__tablename__ = 'switchman_shards'
id = Column(Integer, primary_key=True)
database_server_id = Column(String)
name = Column(String, nullable=True)
default = Column(Boolean)
settings = Column(String)
delayed_jobs_shard_id = Column(Integer, nullable=True)
def __init__(self,
id,
db_server_id,
name,
default,
settings,
del_job_shard_id):
self.id = id
self.database_server_id = db_server_id
self.name = name
self.default = default
self.settings = settings
self.delayed_jobs_shard_id = del_job_shard_id
@hybrid_property
def cluster_id(self):
# Clusters that do not use their cluster name as the schema and need to
# be recast.
cluster_list = ('cluster1dr', 'cluster4dr')
if self.database_server_id in cluster_list and self.name is None:
return 'canvas'
elif self.name is None:
return self.database_server_id
else:
return self.name
@hybrid_property
def shard_id(self):
shard_regex = re.compile(r'(\d+$)')
if self.name is None:
res = shard_regex.search(self.database_server_id)
return res.group(1)
else:
res = shard_regex.search(self.name)
return res.group(1)
def return_shards():
Session = sessionmaker(bind=engine)
session = Session()
shards = session.query(SwitchmanShards).filter(
SwitchmanShards.database_server_id.like('cluster%')
).all()
return shards
作为旁注,我试图弄清楚SQLALchemy的价值,因为我花了大约3倍的行来编写相同的代码。可以说它更具可读性,这是我能看到的最大优点。
编辑:我注意到这比原始SQL查询少了10个记录,不知道为什么会这样。