pythonpostgresqlpsycopg2psycopg3

psycopg3 mogrify: AttributeError: 'Connection' object has no attribute 'mogrify'


Im using psycopg3 and would like to see what the actual sql with the parameters is so i can execute it using dbweaver...

         with psycopg.connect(self.connect_str, autocommit=True) as conn:
            if self.log.level == logging.DEBUG:
                  cur = conn.cursor()
                  sql_mogr = cur.mogrify(sql, params)
                  self.log.debug(sql_mogr)
            else:
               self.log.info(f'sql: {sql}, params:{params}')

            df = pd.read_sql(sql, con = conn, params = params)

The results of the mogrify line is:

AttributeError: 'Cursor' object has no attribute 'mogrify'

Does psycopg3 not support this method? if not, what is an alternate solution?

version of psycopg:

psycopg==3.1.18
psycopg-binary==3.1.18
psycopg-pool==3.2.1

Solution

  • The mogrify method is only available on the ClientCursor class.

    >>> conn = psycopg.connect(dbname='test', cursor_factory=psycopg.ClientCursor)
    >>> cur = conn.cursor()
    >>> q = """select * from users"""
    
    >>> cur.mogrify(q)
    'select * from users'