如何在Snowflake SQLAlchemy中创建含自动填充Timestamp字段的表?
问题
我正在使用Python的SqlAlchemy创建Snowflake表定义,已成功创建包含自增主键及其他字段的表,但未找到如何添加新增记录时自动填充的Timestamp字段的相关文档。
参考示例:在Snowflake工作表中直接创建该字段的SQL如下
CREATE OR REPLACE TABLE My_Table( TABLE_ID NUMBER NOT NULL PRIMARY KEY, ... Other fields TIME_ADDED TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
我的Python代码如下:
from sqlalchemy import Column, DateTime, Integer, Text, String from sqlalchemy.orm import declarative_base from sqlalchemy import create_engine Base = declarative_base() class My_Table(Base): __tablename__ = 'my_table' TABLE_ID = Column(Integer, primary_key=True, autoincrement=True) # .. other columns # .. Also need to create TIME_ADDED field engine = create_engine( 'snowflake://{user}:{password}@{account_identifier}/{database}/{schema}?warehouse={warehouse}'.format( account_identifier=account, user=username, password=password, database=database, warehouse=warehouse, schema=schema ) ) Base.metadata.create_all(engine)
请问有人实现过吗?若有,能否指明实现方向?
实现方案
要实现Snowflake端自动填充的Timestamp字段,你需要使用server_default参数结合SQLAlchemy的func.current_timestamp(),这样就能对应SQL中的DEFAULT CURRENT_TIMESTAMP逻辑,让Snowflake服务器在插入记录时自动填充时间。
具体步骤:
- 首先导入
func模块:
from sqlalchemy import func
- 在
My_Table类中添加TIME_ADDED字段:
TIME_ADDED = Column(DateTime, server_default=func.current_timestamp())
修改后的完整代码:
from sqlalchemy import Column, DateTime, Integer, Text, String, func from sqlalchemy.orm import declarative_base from sqlalchemy import create_engine Base = declarative_base() class My_Table(Base): __tablename__ = 'my_table' TABLE_ID = Column(Integer, primary_key=True, autoincrement=True) # 其他字段 TIME_ADDED = Column(DateTime, server_default=func.current_timestamp()) engine = create_engine( 'snowflake://{user}:{password}@{account_identifier}/{database}/{schema}?warehouse={warehouse}'.format( account_identifier=account, user=username, password=password, database=database, warehouse=warehouse, schema=schema ) ) Base.metadata.create_all(engine)
注意事项:
- 使用
server_default而非普通的default:default是在Python本地生成时间后传入,而server_default是让Snowflake服务器端生成时间,和你给出的SQL示例行为完全一致,避免本地时间与服务器时间不一致的问题。
内容的提问来源于stack exchange,提问作者MountainBiker
相关产品推荐
相关产品推荐

