Showing posts with label jython. Show all posts
Showing posts with label jython. Show all posts

Saturday, February 21, 2009

Python SQL Runner

Recently, I have been working quite a bit with our taxonomy database, using the data in it as input to some data mining programs I am working on. Initially, I built in the database call into the programs themselves, but this approach turned out to be inconvenient for a number of reasons. One of these reasons is that the program is harder to restart in case of failures. Having these programs work with input files instead of a database query also results in cleaner and more extensible design, since now they can work with inputs other than SQL.

The databases I work with are MySQL and Oracle. The last time I needed this sort of stuff, I would whip up a Python script on-demand using either the MySQLdb or cx-oracle packages. One crashed hard disk and a couple of OS re-installs later, these scripts no longer work because the packages need to be re-installed as well. I have mostly gotten by since the crash using the MyEclipse Database Explorer and cut-n-paste, since the datasets I was working with were smaller, but the size of the data (~ 100K plus rows) I am dealing with now are likely to cause Eclipse to clutch its throat and do a crash-n-burn, taking my other unsaved code along with it, so I needed something that I could use from the command line.

This time around, I planned to do things a bit smarter than I did in the past, so I thought of building a generic script that would dump out rows given any SQL, something similar to my fledgling attempt many, many years ago. Funny how things come full circle from time to time. This time around, I also wanted to make sure its usage survives disk crashes and OS re-installs, so rather than have a script that requires extra dependencies, I wanted to use the JDBC drivers that I was going to install anyway. So my choices boiled down to either Jython or Scala.

I ended up writing it using Jython because my other scripts are all written in Python, and because writing database code in Python is slightly less verbose than in Java (or Scala, since that would have been the same thing). The name of the script is db2csv.py, and the code is shown below:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
#!/usr/bin/env /opt/jython-2.2.1/jython
import sys
import getopt
import os.path
import traceback
from com.ziclix.python.sql import zxJDBC

class SqlRunner:
  """
  Class to run the SQL and print it out into the output file as a CSV
  """
  def __init__(self, dbconfig, sqlfile, outputfile, sepchar):
    """
    @param dbconfig the database configuration file name
    @param sqlfile the name of the file containing the SQL to be executed
    @param outputfile the name of the file where output will be written
    @param sepchar the separator character (or string) to use
    """
    self.dbconfig = dbconfig
    self.sqlfile = sqlfile
    self.outputfile = outputfile
    self.sepchar = sepchar

  def getDbProps(self):
    """
    Return the database properties as a map of name value pairs.
    @return a map of name value pairs
    """
    if (not os.path.exists(self.dbconfig)):
      raise Exception("File not found: %s" % (self.dbconfig))
    props = {}
    pfile = open(self.dbconfig, 'rb')
    for pline in pfile:
      (name, value) = pline[:-1].split("=")
      props[name] = value
    pfile.close()
    return props

  def getSql(self):
    """
    Validate the sql file name, and parse out the SQL to be run. The
    method will skip SQL single-line comments. Blocks enclosed by free
    standing multi-line comments are also skipped.
    @return the SQL as a string
    """
    if (not os.path.exists(self.sqlfile)):
      raise Exception("File not found: %s" % (self.sqlfile))
    sql = []
    sfile = open(self.sqlfile, 'rb')
    incomment = False
    for sline in sfile:
      sline = sline.rstrip('\n')
      if (sline.startswith("--") or len(sline.rstrip()) == 0):
        # SQL Comment line, skip
        continue
      if (sline.rstrip() == "/*"):
        # start of SQL comment block
        incomment = True
        continue
      if (sline.rstrip() == "*/"):
        # end of SQL comment block
        incomment = False
        continue
      if (not incomment):
        sql.append(sline)
    sfile.close()
    return " ".join(sql)

  def runSql(self):
    """
    Runs the SQL and prints it out into the specified output file as a CSV
    file delimited by sepchar.
    """
    props = self.getDbProps()
    sql = self.getSql()
    print "Running SQL: %s" % (sql)
    ofile = open(self.outputfile, 'wb')
    db = zxJDBC.connect(props["url"], props["user"], props["password"],
      props["driver"])
    cur = db.cursor(True)
    cur.execute(sql)
    # print the header
    meta = cur.description
    print "Writing output to: %s" % (self.outputfile)
    ofile.write(self.sepchar.join(map(lambda x: x[0], meta)) + "\n")
    for row in cur.fetchall():
      strrow = map(lambda x: str(x), row)
      ofile.write(self.sepchar.join(strrow) + "\n")
    ofile.close()
    cur.close()
    db.close()
    
def usage(error=""):
  """
  Print the usage information. If an error message is supplied, print that
  on top of the usage information.
  """
  if (len(str(error)) > 0):
    print "ERROR: %s" % (error)
    print "STACK TRACE:"
    traceback.print_exc()
  print "USAGE:"
  print "%s -d dbconfig -q queryfile -s sepchar -o outputfile" % (sys.argv[0])
  print "OR: %s -h" % (sys.argv[0])
  print "OPTIONS:"
  print "--dbconfig | -d  : database configuration file"
  print "  configuration file must be in properties format, with the following"
  print "  keys defined: driver, url, user and password"
  print "--queryfile | -q : name of file containing SQL to be run"
  print "--outputfile | -o: name of file where results should be written"
  print "--sep | -s       : the separator character to use in output"
  print "--help | -h      : print this information"
  sys.exit(2)

def extractOptions(argv):
  """
  Extract command line options and return a tuple
  @param argv the sys.argv object
  @return a tuple containing the information for running the SQL
  """
  try:
    (opts, args) = getopt.getopt(argv[1:], "d:q:s:o:h",
      ["dbconfig=", "queryfile=", "sep=", "outputfile=", "help"])
  except getopt.GetoptError:
    usage()
  if (len(filter(lambda x: x[0] in ("-h", "--help"), opts)) == 1):
    usage()
  if (len(opts) != 4):
    usage()
  for opt in opts:
    (key, value) = opt
    if (key in ("-d", "--dbconfig")):
      dbconfig = value
    elif (key in ("-q", "--queryfile")):
      sqlfile = value
    elif (key in ("-o", "--outputfile")):
      outputfile = value
    elif (key in ("-s", "--sep")):
      sepchar = value
    else:
      usage()
  return (dbconfig, sqlfile, outputfile, sepchar)
  
def main():
  """
  This is how we are called
  """
  (dbconfig, sqlfile, outputfile, sepchar) = extractOptions(sys.argv)
  sqlrunner = SqlRunner(dbconfig, sqlfile, outputfile, sepchar)
  try:
    sqlrunner.runSql()
  except Exception, e:
    usage(e)

if __name__ == "__main__":
  main()

As you can see, there is nothing really new here, you can get most of this from the relevant section of the Jython User Guide. I did start to use a bit of Python lambdas, which ironically, I learned on my recent foray into Scala-land.

In the spirit of not having to install anything but the base language, the zJDBC package comes standard with the Jython version (2.2.1) that I am using. Since I already use Java I will install it anyway, as well JDBC drivers for the different databases that I will talk to.

You can call the script using command line parameters as shown in the help output below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
sujit@sirocco:~$ ./db2csv.py -h
USAGE:
./db2csv.py -d dbconfig -q queryfile -s sepchar -o outputfile
OR: ./db2csv.py -h
OPTIONS:
--dbconfig | -d  : database configuration file
  configuration file must be in properties format, with the following
  keys defined: driver, url, user and password
--queryfile | -q : name of file containing SQL to be run
--outputfile | -o: name of file where results should be written
--sep | -s       : the separator character to use in output
--help | -h      : print this information

I had described in a previous post how one can add JAR files to the Jython classpath by appending the path names to sys.path in the code, but the approach didn't work for me here, perhaps because the appropriate Driver JAR class is being loaded explicitly by the code here. So I fell back to having it be loaded from the Java CLASSPATH instead. It's not such a bad thing, though - with this approach, one can use the script as is, for any database, as long as the JDBC driver exists on the CLASSPATH when the script is invoked. And if the driver is not in the CLASSPATH, the script tells you:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
sujit@sirocco:~$ ./db2csv.py -d /path/to/config/file -q /path/to/sql/file.sql \
  -o /path/to/report/file -s "|"
Running SQL: select foo from bar where baz = 'baz'
ERROR: driver [com.mysql.jdbc.Driver] not found
STACK TRACE:
Traceback (most recent call last):
  File "./db2csv.py", line 156, in main
    sqlrunner.runSql()
  File "./db2csv.py", line 83, in runSql
    db = zxJDBC.connect(props["url"], props["user"], props["password"],
DatabaseError: driver [com.mysql.jdbc.Driver] not found
USAGE:
./db2csv.py -d dbconfig -q queryfile -s sepchar -o outputfile
OR: ./db2csv.py -h
OPTIONS:
--dbconfig | -d  : database configuration file
  configuration file must be in properties format, with the following
  keys defined: driver, url, user and password
--queryfile | -q : name of file containing SQL to be run
--outputfile | -o: name of file where results should be written
--sep | -s       : the separator character to use in output
--help | -h      : print this information

I also had to increase the JVM heap size because Jython was running out of heap space when running the queries. I did this directly in the Jython script, by adding -Xmx2048m to the java call.

In spite of the simplicity of the script, I am already finding it immensely useful. If you have reached here looking for a similar script, I hope you will find it useful as well.

Saturday, September 29, 2007

Using Lucene with Jython

In a previous post, I had described a workaround to using Lucene BooleanQueries using PyLucene. Basically, all this involved was to build the Query programatically using AND and OR boolean operators supplied by Lucene's Query Parser syntax before passing it to the PyLucene.QueryParser object.

However, I faced a slightly different problem now. My task was to quality check an index built using a custom Lucene Analyzer (written in Java). The base queries the user was expected to type into our search page was available as a flat file. The quality check involved converting the input query into a custom Lucene Query object, then apply a set of standard facets to the Query using a QueryFilter, and write the results of each IndexSearcher.search(Query,QueryFilter) call into another flat file.

Of course, the most logical solution would have been to write a Java JUnit test that did this. But this was kind of a one-off, and writing Java code seemed kind of wasteful. I had experimented with Jython once before, where I was looking for a way to call some Java standalone programs from the command line. So I decided to try the same approach of adding the JAR files I needed to Jython's sys.path.

So here is my code, which should be pretty much self explanatory. The script takes as input arguments the path to the Lucene index, the path to the input file of query strings and the path to the file where the report should be written.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/opt/jython2.2/jython
import sys
import string

def usage():
  print " ".join([sys.argv[0], "/path/to/index/to/read", "/path/to/input/file", \
    "/path/to/output/file"])
  sys.exit(-1)

def main():
  # Command line processing
  if (len(sys.argv) != 4):
    usage()

  # Set up constants for reporting
  facetValues = ["value1", "value2", "value3", "value4", "value5"]

  # Add jars to classpath
  jars = [
    "/full/path/to/lucene.jar",
    "/full/path/to/our/custom/analyzer.jar"
    ... other dependency jars
    ]
  for jar in jars:
    sys.path.append(jar)

  # Import references
  from org.apache.lucene.index import Term
  from org.apache.lucene.queryParser import QueryParser
  from org.apache.lucene.search import IndexSearcher
  from org.apache.lucene.search import TermQuery
  from org.apache.lucene.search import QueryFilter
  from org.apache.lucene.store import FSDirectory
  from com.mycompany.analyzer import MyCustomAnalyzer

  # load up an array with the input query strings
  querystrings = []
  infile = open(sys.argv[2], 'r')
  outfile = open(sys.argv[3], 'w')
  while (True):
    line = infile.readline()[:-1]
    if (line == ''):
      break
    querystrings.append(line)
  
  # search for the query and facet
  dir = FSDirectory.getDirectory(sys.argv[1], False)
  analyzer = MyCustomAnalyzer()
  searcher = IndexSearcher(dir)
  for querystring in querystrings:
    for facetValue in facetValues:
      luceneQuery = buildCustomQuery(querystring)
      query = QueryParser("body", analyzer).parse(luceneQuery)
      queryfilter = QueryFilter(TermQuery(Term("facet", facetValue)))
      hits = searcher.search(query, queryfilter)
      numHits = hits.length()
      # if we found nothing for this query and facet, we report it
      if (numHits == 0):
        outfile.write("|".join([querystring, facetValue, 'No Title', 'No URL', '0.0']))
        continue
      # show upto the top 3 results for the query and facet
      for i in range(0, min(numHits, 3)):
        doc = hits.doc(i)
        score = hits.score(i)
        title = doc.get("title")
        url = doc.get("url")
        outfile.write("|".join([disease, facet, title, url, str(score)]))

  # clean up
  searcher.close()
  infile.close()
  outfile.close()

def buildCustomLuceneQuery(querystring):
  """ do some custom query building here """
  return query
  
if __name__ == "__main__":
  main()

Why is this so cool? As you can see, the Python code is quite simple. However, it allows me to access functionality embedded in our custom Lucene Analyzer written in Java, as well as access the newer features of Lucene 2.1 (PyLucene is based on Lucene 1.4) if I need them. So basically, I can now write what is essentially Java client code in the much more compact Python language. Also, if I had written a Java program, I would either have to call Java with a rather longish -classpath parameter, or build up a shell script or Ant target. With Jython, the script can be called directly from the command line.

There are some obvious downsides as well. Since I mostly use Python for scripting, I end up downloading and installing many custom modules for Python, that I don't necessarily install on my Jython installation. For example, for database access, I have modules installed for Oracle, MySQL and PostgreSQL. However, with Jython, we could probably just use JDBC for database access, as described in Andy Todd's blog post here. Overall, I think having access to Java code from within Python using Jython is quite useful.

Saturday, October 21, 2006

Using Jython to call Java

I have been writing standalone Java applications lately, which are run from within a shell script, something like the snippet below. Calling Java standalones in this way is a fairly standard approach. However, being a Python fan(atic?), I would like to write these shell scripts using Python. This article describes how to call Java programs using Jython, which is a Java port of the Python programming language.

1
2
3
#!/bin/bash
LIBDIR=/path/to/my/jar/repository
java -classpath $LIBDIR/commons-lang-2.1.jar:  $LIBDIR/com-mycompany-4.9.jar com.mycompany.mypackage.MyClass $*

In MyClass.java, I have a static main(String[] argv) method which gets invoked as a result of the call above. All it does is instantiate an instance of MyClass and pass some parameters to it, and then call a method on it that does the work. Here is an example, basically yet another implementation of HelloWorld.java, but it will do for illustrating the pattern.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.mycompany.mypackage;

import org.apache.commons.lang.StringUtils;

public class MyClass {

  private String name;

  public MyClass() {
    super();
  }

  public void setName(String name) {
    this.name = name;
  }

  public String greet() {
    if (StringUtils.isEmpty(name)) {
      return "Hi there";
    } else {
      return "Hi " + name;
    }
  }

  public static void main(String[] argv) {
    MyClass myclass = new MyClass();
    myclass.setName(argv[0]);
    System.out.println(myclass.greet());
  }
}

Arguably, classes in the real world have more code in their main() methods, but the approach I take when I see that I have more than one object being invoked in my main method, is to factor out the logic into private methods of that class, or into a Main.java class in that package if multiple classes are involved.

Anyway, the Jython script to call the main method of MyClass with a single string parameter that is passed in from the command line is shown below. Notice how the Jython script instantiates the MyClass object. The classpath is passed in to Jython using sys.path.append() calls. Resource files, such as .properties files or other XML configuration files need to be baked into the JAR file and should be accessible from within the Java code using getResourceAsStream().

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/usr/bin/env jython
import sys

def setClassPath():
  libDir = "/path/to/my/jar/files/"
  classPaths = [
    "commons-lang-2.1.jar",
    "com-mycompany-4.9.jar"
  ]
  for classPath in classPaths:
    sys.path.append(libDir + classPath)

def runJavaClass(name):
  from com.mycompany.mypackage import MyClass
  mc = MyClass()
  if (name != None):
    mc.setName(name)
  print mc.greet()

def main():
  if (len(sys.argv) < 2):
    name = None
  else:
    name = sys.argv[1]
  setClassPath()
  runJavaClass(name)

if __name__ == "__main__":
  main()

As you can see, invoking Java programs from Jython leads to cleaner but more verbose scripts, but does seem to be overkill in our case. However, this approach can really help when you have to design more complicated scripts that deal with a large number of classes. One approach, and my preferred one, is to put this logic in Java in another abstraction layer. However, sometimes, this is not the most practical approach, perhaps because the rules are rather fluid, and you would like to be able to change the rules without having to go through a big release cycle. In such cases, and depending on the complexity of the rules, I think I would be more productive using Python than Shell Scripts. Even if the rules were simple enough to be encoded within a Shell Script to start out with, it may still be more practical to use Jython, since the rules can get more complicated, and you may be faced with having to rewrite the script.

I don't think it is possible to set JVM parameters (such as minimum and maximum JVM sizes) to Jython from within the Jython script, something that is possible using a Shell Script. Jython itself is a shell script and calls the org.python.util.jython class, so these parameters can be passed into the Java invocation in the jython shell script, although this does not seem to be very clean. Running the class through Jython also seems a little slower than running it through a Shell Script, but I haven't done any benchmarks to say this conclusively.