--- /dev/null
+"""
+Initialize and populate SQLite database based on SQL script.
+
+2011, Razvan Deaconescu, razvan.deaconescu@cs.pub.ro
+"""
+
+import sys
+import os.path
+import getopt
+import logging
+import sqlite3
+
+#
+# Logging code heavily inspired by Logging HOWTO documentation:
+# http://docs.python.org/dev/howto/logging.html#configuring-logging
+#
+
+# Create logger; default logging level is DEBUG.
+logger = logging.getLogger(__name__)
+logger.setLevel(logging.DEBUG)
+
+# Create console handler and set level to ERROR.
+ch = logging.StreamHandler()
+ch.setLevel(logging.DEBUG)
+
+# Create formatter.
+formatter = logging.Formatter('%(filename)s:%(lineno)s - %(levelname)s: %(message)s')
+
+# Add formatter to console handler.
+ch.setFormatter(formatter)
+
+# Add console handler to logger.
+logger.addHandler(ch)
+
+
+DEFAULT_SQL_SCRIPT = "../sql/p2p-log-sqlite.sql"
+
+def init_database(sql, database):
+ """ Create database file and instantiate objects. """
+ p = os.path.join(os.path.dirname(__file__), sql)
+ logger.debug("SQL script path is %s." %(p))
+ f = open(p, 'r')
+
+ # FIXME: Dangerous code. In case file is huge, all of it is read
+ # into memory.
+ stmts = f.read()
+
+ conn = sqlite3.connect(database)
+ cursor = conn.cursor()
+ cursor.executescript(stmts)
+ cursor.close()
+ conn.close()
+
+def usage():
+ print """Usage: python %s [-s|--sql sql_script] database_file
+
+\t--sql
+\t-s\t\tpath to SQL script
+\t\t\t\tdefault is %s
+
+\tdatabase_file\tSQLite database file
+\t--help
+\t-h\t\tprint this help screen""" %(sys.argv[0], DEFAULT_SQL_SCRIPT)
+
+def main():
+ """
+ Create and populate initial database file.
+ """
+
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], "hs:", ["help", "sql="])
+ except getopt.GetoptError, err:
+ logger.error(str(err))
+ usage()
+ sys.exit(2)
+
+ sql = None
+
+ for o, a in opts:
+ if o in ("-h", "--help"):
+ usage()
+ sys.exit(0)
+ elif o in ("-s", "--sep"):
+ sql = a
+ else:
+ assert False, "unhandled option"
+
+ # No database file passed as argument.
+ if len(args) != 1:
+ logger.error("Error: no database file passed as argument.")
+ sys.exit(2)
+ database = args[0]
+ logger.debug("Using database file %s." %(database))
+
+ if sql == None:
+ sql = DEFAULT_SQL_SCRIPT
+ logger.debug("Using SQL script %s." %(sql))
+
+ init_database(sql, database)
+
+
+if __name__ == "__main__":
+ sys.exit(main())