Home:ALL Converter>How can I insert column comments in PostgreSQL via Python?

How can I insert column comments in PostgreSQL via Python?

Ask Time:2020-02-13T22:58:25         Author:Saaru Lindestøkke

Json Formatter

Problem

I want to add a comment to a number of columns from Python in a PostgreSQL database. If I run the statement that my Python script produces in a database client manually everything works as it should. If I let Python run the statement via an sqlalchemy engine, nothing is updated.

Details

I have a dictionary in Python of the form { 'column name': 'column comment with some text'}.

I want to add this comments to an existing table in a Postgres database.

Manually I would run the following command in Postgres:

comment on column schema.table."column name" is 'column comment with some text'

Now in Python I want to run the same, but then looping over the dictionary. This is the code I use:

from sqlalchemy import create_engine, text

db = create_engine(f"postgresql://PGUSER:PGPASSWORD@PGHOST/PGDATABASE")

coldict = {'col1': 'col1 contains this data, etc... some more comments', 'col2': 'col2 shows something.'}

with db.connect() as con:
        for key in coldict:
            colname = key
            # Convert a single quote to two single quotes as that is what SQL likes.
            colcomm = coldict[key].translate(str.maketrans({"'": "''"}))
            stmt = f"comment on column schema.table.\"{colname}\" is '{colcomm}';"
            # print the statement that will be run for debugging
            print(stmt)
            # execute statement in database
            con.execute(text(stmt))

This prints out:

comment on column schema.table."col1" is 'col1 contains this data, etc... some more comments';
comment on column schema.table."col2" is 'col2 shows something.';

When I check the column comments with the query from this answer no comments are actually set.

If I copy-paste what is printed out into a database client and run it there, the column comment is updated as it should.

How can I update the column comment via a loop in Python?

Author:Saaru Lindestøkke,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/60210704/how-can-i-insert-column-comments-in-postgresql-via-python
yy