Running simple SQL commands on the command line

08 January 2005   2 comments   Python

Powered by Fusion×

In my Zope usage I use a lot of SQL stored on the filesystem. These files contain DTML syntax and parameters like ZSQL Method objects inside the ZODB. Sometimes, to test the SQL code I have in these files I want to run it on the command line. To be able to do that I've written this little Python script which is placed in my ~/bin directory in Linux. It only works with PostgreSQL at the moment but people who like the idea and prefer Oracle or MySQL could probably find where to make their changes. (The psql -f command is the ticket)

Example foo.sql:

FROM sometable
WHERE id = <dtml-sqlvar id type="int">
AND   name = <dtml-sqlvar name type="string">

Which is run like this:

peterbe@trillian:~ $ -U peterbe testdb foo.sql

If you run the command:

peterbe@trillian:~ $ -h

then you'll hopefully understand how it works. If you have specified the database connection string once you won't have to do it again unless you're changing database. If you want to test your SQL but without committing anything for real to the database you can run it like this:

peterbe@trillian:~ $ --test delete_everything.sql

It will wrap the SQL in a BEGIN and ROLLBACK command.

Have a play with it if you might find it useful. Please let me know of any problems or ideas you have. The DTML "rendering" is dead-stupid. It's NOT using the real Zope DTML rendering engine; rather, it's using some simple regular expressions.


mysql already does this:
mysql -u uname dbname < file.sql
Peter Bengtsson
What if the file has DTML in it? With conditionals and parameters?
I think it's the same syntax for postgres but again it does have the same amount of magic :)
Thank you for posting a comment

Your email will never ever be published

Related posts

Previous: is out! 04 January 2005
My favorite CSS Zen Garden design 10 January 2005
Related by keywords:
Fastest database for Tornado 09 October 2013
Integer division in programming languages 04 August 2004
Optimization of getting random rows out of a PostgreSQL in Django 23 February 2011
Connecting with psycopg2 without a username and password 24 February 2011
Adding a year in PostgreSQL 04 February 2004
pg_class to check if table exists 20 April 2005
To sub-select or not sub-select in PostgreSQL 31 August 2009
Speed test between django_mongokit and postgresql_psycopg2 09 March 2010
UPPER vs. ILIKE 19 April 2010
Date formatting in python or in PostgreSQL 20 July 2004
PostgreSQL, MySQL or SQLite 04 April 2004
Postgres collation errors on CITEXT fields when upgrading to 9.1 21 May 2012