I ll take the simplest of the SQL functions as an example:
CREATE OR REPLACE FUNCTION skater_name_match(INTEGER,VARCHAR)
RETURNS BOOL AS
$$
SELECT $1 IN (SELECT skaters_skater.competitor_ptr_id FROM skaters_skater
WHERE name|| ||surname ILIKE % ||$2|| %
OR surname|| ||name ILIKE % ||$2|| % );
$$ LANGUAGE SQL;
If I copy and paste this into psql (PostgreSQL s shell) then it executes without any problems.
If I write a piece of Python code like this (with a real database name and user of course):
import psycopg2
sql_function_above = CREATE OR REPLACE FUNCTION skater_name_match(INTEGER,VARCHAR)
RETURNS BOOL AS
$$
SELECT $1 IN (SELECT skaters_skater.competitor_ptr_id FROM skaters_skater
WHERE name|| ||surname ILIKE % ||$2|| %
OR surname|| ||name ILIKE % ||$2|| % );
$$ LANGUAGE SQL;
try:
connection = psycopg2.connect("dbname= x user= x host= localhost password= x ");
except:
print "I am unable to connect to the database"
cursor = connection.cursor()
cursor.execute(sql_function_above)
It seems to execute (it doesn t give me an error), but when I look into the database the function is not there.
When I try to execute the code in Django by putting it into an app/sql/model.sql file I get the following error during syncdb:
IndexError: tuple index out of range
When I try to write my own manage.py command that would execute the sql, I get the same error.
What s going on here? Would be very grateful to anyone who could shed some light on this :) I m still a newbie when it comes to Python and Django, so I may have overlooked something obvious.