I have a python script that uses psycopg2 to make some SQL queries. When testing this locally on my mac everything works as expected. When running the script on a server (the intended destination) I get an error from psycopg2:
.local/lib/python2.7/site-packages/psycopg2-2.5.4-py2.7-linux-x86_64.egg/psycopg2/extras.py", line 120, in execute return super(DictCursor, self).execute(query, vars) psycopg2.ProgrammingError: syntax error at or near "0" LINE 4: ...ice) OVER (ORDER BY time_series DESC ROWS BETWEEN 0 FOLLOWIN...
The query works totally fine in pgadmin and on my local machine. In all cases I am using python 2.7. Here is the problem script:
def chart_files_price_movavg(itemname, hostname, port, dbname, username, pw):
"itemname, db credentials"
#creates a csv with average price per day with headers
query = ("""SELECT time_series,
avg_price AS daily_price,
CASE WHEN row_number() OVER (ORDER BY time_series) > 7
THEN avg(avg_price) OVER (ORDER BY time_series DESC ROWS BETWEEN 0 FOLLOWING AND 6 FOLLOWING)
ELSE NULL
END AS avg_price
FROM
(SELECT to_char(closing_date, 'YYYY/MM/DD') AS time_series, SUM(price) / COUNT(itemname) AS avg_price
FROM auction_prices
WHERE itemname = 'iphone6_16gb' AND price < 1000
GROUP BY time_series)
AS foo""") % locals()
filename = itemname + '_price_movavg.csv'
filepath = '/home5/easypea9/public_html/downloads/' + filename
#filepath = '/Users/Ali Mac Pro/Google Drive/Auto-Stock-Analysis/Python/Web Scraping/eBay/chartdata/' + filename
copy_select(query, filepath, hostname, port, dbname, username, pw)
Updating psycopg2 didnt solve the issue, so I'm looking for new ideas.
[edit] and here is the copy_select() function
def copy_select(query, filename, hostname, port, dbname, user, password):
'query, outputfile, hostname, port, dbname, user, password'
#global cur
try:
connection = psycopg2.connect(
database=dbname,
user=user,
host=hostname,
password=password)
connection.autocommit = True
cur = connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
except:
print 'database connection FAIL'
ticquery = datetime.now()
cur.execute(query)
rows = cur.fetchall()
tocquery = datetime.now()
querytime = tocquery - ticquery
#write the csv
openfile = open(filename, 'wb')
csvwriter = csv.writer(openfile)
csvwriter.writerows(rows)
openfile.close()
return rows
<value> FOLLOWING
syntax was added in 9.0. Compare 8.4 docs and 9.0 docs. – univerio May 5 '15 at 22:08PRECEDING
/FOLLOWING
syntax. You can try posting a separate question about it. Alternatively, you can try to implement the moving average in Python, but that's out of the scope of this question. – univerio May 6 '15 at 21:40