-1

I'm using python Flask and can't get my head around why i'm getting error:

ProgrammingError: syntax error at or near "IF"
LINE 1: IF SELECT count(*) FROM ProfilePicture WHERE userid =

Here is my code:

 > def updateProfilePicture(filename, image, userid):
    >     cursor = getCursor()
    >     binary = psycopg2.Binary(image)
    >     data = (userid, filename, binary, userid, filename, binary, userid)
    >     #SQL = """INSERT INTO ProfilePicture(id, image, userid)
    >      #                   VALUES    (%s, %s, %s)"""
    >     SQL = """IF SELECT count(*) FROM ProfilePicture WHERE userid = %s > 0 
    >     THEN
    >         UPDATE ProfilePicture SET id = %s, image = %s WHERE userid = %s
    >     ELSE
    >         INSERT INTO ProfilePicture(id, image, userid) VALUES (%s, %s, %s)
    >     END IF"""
    >     print cursor.mogrify(SQL, data)
    >     cursor.execute(SQL, data)
    >     cursor.connection.commit()
    >     cursor.close()
    >     return

A simple insert works well but not the if statement.

Appreciate your help!

2 Answers2

0

Since "ON CONFLICT" syntax is introduced in PostgreSQL 9.5, you have to test the existence of the row in python.

If you have a unique constraint on the userid you can use exceptions:

def updateProfilePicture(filename, image, userid):
    cursor = getCursor()
    binary = psycopg2.Binary(image)
    data = (userid, filename, binary, userid, filename, binary, userid)
    SQL = """INSERT INTO ProfilePicture(id, image, userid) VALUES    (%s, %s, %s)"""
    try:
        cursor.execute(SQL, data)
    except:
        cursor.rollback()
        SQL = """UPDATE ProfilePicture SET id = %s, image = %s WHERE userid = %s"""
        cursor.execute(SQL, data)
    cursor.connection.commit()
    cursor.close()
Daniel
  • 42,087
  • 4
  • 55
  • 81
0

That's not SQL syntax, it's the PL/pgSQL procedural language. It's primarily used to write functions. You can use it for a one-off command, but you need to put it in a DO block:

DO $$
BEGIN 
  IF (SELECT count(*) FROM ProfilePicture WHERE userid = %s) > 0 THEN
    UPDATE ProfilePicture SET id = %s, image = %s WHERE userid = %s;
  ELSE
    INSERT INTO ProfilePicture(id, image, userid) VALUES (%s, %s, %s);
  END IF;
END
$$

Note, however, that your logic will not work if someone else is inserting into/deleting from ProfilePicture at the same time; you risk either losing the update, or inserting multiple records for the same userid. Avoiding this is less than straightforward.

Community
  • 1
  • 1
Nick Barnes
  • 19,816
  • 3
  • 51
  • 63