1

I have the following code to insert data (detector_id, video_id, score) into the table score if it doesn't exist, and if it does exist, add the score to its existing value:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
db = SQLAlchemy(app)

query = "DO $$ BEGIN UPDATE "+table_score+" SET score = score + \'"+ concept_score +"\' " + \
        "WHERE detector_id = \'"+ detector_id +"\' AND video_id = \'"+video_id+"\'; " + \
        "IF NOT FOUND THEN INSERT INTO "+table_score+" VALUES (\'"+detector_id+"\', \'"+video_id+"\', "+concept_score+"); " + \
        "END IF; END $$;"
result = db.engine.execute(query)

This is equivalent to the following, which works when i execute it in pgAdmin:

DO $$ BEGIN 
    UPDATE score SET score = score + SCORE_VALUE
        WHERE detector_id = 'DETECTOR_ID' AND video_id = 'VIDEO_ID';
    IF NOT FOUND THEN 
        INSERT INTO score VALUES ('DETECTOR_ID', 'VIDEO_ID', SCORE_VALUE);
    END IF; 
END $$

However, it doesn't add anything if I try to execute the Python code. I also don't get any error messages. Other queries work fine so it is not a problem with my database connection. When I try to output list(result) it returns: This result object does not return rows.

If I do print query, and run the string in pgAdmin, it works. However, running it by db.engine.execute(query) does not. Other queries like SELECT * FROM score s WHERE s.detector_id ='DETECTOR_ID'; work fine with db.engine.execute(query). Does this have to do with the DO $$.. statement?

The following works fine, but seems undue:

query = "SELECT * FROM "+table_score+" s WHERE s.detector_id = \'"+ detector_id +"\' AND s.video_id = \'"+video_id+"\';"
result = db.engine.execute(query)
if len(list(result)) > 0:
    query = "UPDATE "+table_score+" SET score = score + \'"+ concept_score +"\' WHERE detector_id = \'"+ detector_id +"\' AND video_id = \'"+video_id+"\';"
else:
    query = "INSERT INTO "+table_score+" VALUES (\'"+detector_id+"\', \'"+video_id+"\', "+concept_score+");"
result = db.engine.execute(query)
2
  • 1
    Did you try to db.engine.commit()? Commented Dec 10, 2015 at 12:30
  • Try doing a commit in the end (or configuring the session to do autocommit). Also note that in later versions of Postgres you might prefer the on conflict syntax (insert into ... on conflict ... do update ...) Commented Dec 10, 2015 at 12:33

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.