我有一個不會經常更改的表,因此我希望將它快取在客戶端。那么是否有某種哈希值或上次更新時間可用于確定表是否已更新?如果沒有,那么如何創建觸發器來跟蹤表中的更改?
Python - SQL Alchemy、Fast API、Postgres SQL
class Country(Base):
__tablename__ = 'country'
id: int = Column(Integer, primary_key=True)
class State(Base):
__tablename__ = 'state'
id: int = Column(Integer, primary_key=True)
class Cache(Base):
__tablename__ = 'cache'
index: int = Column(Integer, primary_key=True)
table_name: str = Column(String(64), nullable=False, unique=True)
sync_token: str = Column(String(40), nullable=False)
# triggers
@event.listens_for(Country, 'after_update')
def after_update(mapper, connection, target):
pass '''on any change in this table update the timestamp in the cache table'''
uj5u.com熱心網友回復:
您可以在表中進行任何修改時添加更新時間戳的表列:
from datetime import datetime
from sqlalchemy import Column, DateTime, func
modified_at = Column(
DateTime,
server_default=func.timezone("UTC", func.now()),
onupdate=datetime.utcnow,
)
您還可以使用事件來跟蹤表中的更改。這是一個涵蓋它的主題:Tracking model changes in SQLAlchemy
from sqlalchemy.orm import sessionmaker
# triggers
@event.listens_for(Country, 'after_update')
def after_update(mapper, connection, target):
# target is your updated Country instance
connection.execute(f"update cache set index = {target.int} where table_name = 'country'")
# last_update_on will be modified automatically
uj5u.com熱心網友回復:
class Cache(Base):
__tablename__ = 'cache'
index: int = Column(Integer, primary_key=True)
table_name: str = Column(String(64), nullable=False, unique=True)
last_update_on: datetime = Column(DateTime, nullable=False, default=datetime.now)
# triggers
@event.listens_for(Country, 'after_update')
def run_after_update(mapper, connection, target):
dateTime: str = str(datetime.now())
tableName: str = Country.__tablename__
update_stmt = f"UPDATE cache SET last_update_on = '{dateTime}' WHERE table_name = '{tableName}'"
connection.execute(update_stmt)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/400185.html
標籤:Python 数据库 PostgreSQL的 sqlalchemy 快点
上一篇:MySQL-從約束名稱中查找表
