Home:ALL Converter>How to create a postgresql function in SQLAchemy DDL

How to create a postgresql function in SQLAchemy DDL

Ask Time:2022-05-02T23:55:37         Author:Marcio Lino

Json Formatter

everyone!

I wondered how I could create a function in PostgreSQL every time I create or replace a table on my database. I can't find an example that works for my case. So I tried to pass a string with the create command like this:

from sqlalchemy import create_engine

engine = create_engine('/path/to/db...')
conn = engine.connect()

func = 'CREATE OR REPLACE FUNCTION my_func() RETURN SETOF....'
conn.execute(func)

I got a Syntax error running the above code just before the "RETURN SETOF...". So, I try to do something like this:

from sqlalchemy import create_engine

engine = create_engine('/path/to/db...')
conn = engine.connect()

func = DDL('CREATE OR REPLACE FUNCTION my_func()'
           'RETURN SETOF....')

func.execute_if(dialect='postgresql')

I know I'm missing something here, but I could not find out what's missing.

Author:Marcio Lino,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/72089265/how-to-create-a-postgresql-function-in-sqlachemy-ddl
yy