我正在使用 Flask-SQLAlchemy,我的表/模型结构如下
class TableName (db.Model):
columnname = db.Column(db.String)
如何在那里插入 Postgres 自定义函数以便 SQLAlchemy 知道它?
我的意思是像这样的函数
create function canonicalize (text) returns text as $$
select $1;
$$ language sql;
您可以使用 sqlalchemy 中的 text() 生成 Postgresql 函数(又名存储过程)。
我用 postgresql 14 和 python 库 psycopg2==2.9.6 进行了测试 和 psycopg2-二进制==2.9.6
from sqlalchemy import create_engine, text
engine = create_engine('/path/to/db...')
create_procedure = text("""
CREATE OR REPLACE FUNCTION calculate_sum(a integer, b integer)
RETURNS integer AS $$
BEGIN
RETURN a + b;
END;
$$ LANGUAGE plpgsql;
""")
with engine.connect() as connection:
connection.execute(create_procedure)
connection.commit()