Import/execute sql file

767 views
Skip to first unread message

David

unread,
Oct 10, 2011, 11:21:46 AM10/10/11
to web2py-users
Until now i did all my db queries with the DAL from web2py.
But first the first i now got a raw sql file that needs to be execute
at a certain point.
In the terminal i use the '\i' command to import and execute a sql
script.

If i try to use this with db.executesql("\i /path/to/file.sql") i get
an error: => CESTERROR: syntax error at or near "\" at character 1
.
Escaping the character "\\i" doesn't help, still got the same error.
Using psql from the system() call doesn't help (i don't have i
currently installed =] ).

Does someone ever came across this problem before?

Mathew Grabau

unread,
Oct 10, 2011, 11:33:37 AM10/10/11
to web...@googlegroups.com
Calls are not executed with the psql command, they are done with psycopg2. 

You could try a subprocess.POpen call:

import subprocess

...

sp = subprocess.POpen("psql {insert remainder of command line here}", shell=True)

For more on the options of the subprocess module: http://docs.python.org/library/subprocess.html



Brian M

unread,
Oct 10, 2011, 11:32:32 PM10/10/11
to web...@googlegroups.com
Try opening your file, reading its contents and then having db.executesql() execute what was read. Should work assuming the file's contents can be run by psycopg2 (i.e some special psql stuff might not work)

#untested code
f = open('/path/to/file.sql', 'r')
db.executesql(f.read())

Bruno Rocha

unread,
Oct 11, 2011, 12:06:16 AM10/11/11
to web...@googlegroups.com
 
That works, but prefer to run inside a context:

with open("/path/to/file,sql", "r") as sql:
    code = sql.read()
    # here you can do some parsing, remove spaces, replace things
    db.executesql(code)
Reply all
Reply to author
Forward
0 new messages