# sqliteproxy
""" cheap way of getting values from the database for now
    also encapsulates our other configuration work

    sample invocation of sqlite via bash:
        CUEINT_MODID=`sqlite3 $HTCDB 'select id from modules where symbol = "CUEINT"'` >/dev/null

    Modified STE for use in apply_if.py

    SVN $WCREV$:$WCRANGE$ $WCMODS?M:$ Date:$WCDATE$

"""

import sys
import subprocess

# full pathname of sqlite3 admin binary
SQLITE3_BIN = "/usr/bin/sqlite3"

SQLITE3_FIELD_SEP = '|'

# a custom exception, just for convenience
class SqliteProxyException(Exception):
    """ A custom exception for runQuery()
    """
    def __init__(self, value):
        self.parameter = value
    def __str__(self):
        return repr(self.parameter)

#######################################
# utility to parse a complicated result
#######################################
def parseQueryResult(s):
    """ parse a result string and return as a proper list,
         or list of lists
    """
    rv = []
    if s is not None:
        for line in s.split('\n'):
            if line:
                rv.append(line.split(SQLITE3_FIELD_SEP))
    return rv


#####################################
# run a query
#####################################
def runQuery(query, dbasepath):
    """
        run a query, given a query string and a path to the database
    """
    q = "%s %s \"%s\"" % (SQLITE3_BIN, dbasepath, query)

    process = subprocess.Popen(q, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    op = process.communicate()
    if op[1]:    # stderr
        # NB: specific error messages differ ... ;-(
        raise SqliteProxyException("SQL Error: '%s'" % op[1])
    if op[0]:    # stdout
        return op[0].strip()
    else:
        return None

def main():
    """ allow ourself to be used simplistically
        to perform a query from the CLI
    """
    print(len(sys.argv))
    if len(sys.argv) != 3:
        print("bad no. of arguments")
        sys.exit(1)
    print("querying from %s" % sys.argv[2])
    rv = runQuery(sys.argv[1], sys.argv[2])
    print("rv: '%s'" % rv)
    pqr = parseQueryResult(rv.decode("utf-8"))
    print(pqr)

if __name__ == "__main__":
    main()

