Mercurial Hosting > traffic-intelligence
diff python/storage.py @ 714:d6c69d3d09e5
developing python performance tests for SQLite
author | Nicolas Saunier <nicolas.saunier@polymtl.ca> |
---|---|
date | Fri, 24 Jul 2015 17:58:59 -0400 |
parents | 21aeadcfbabb |
children | 2cd245cb780d |
line wrap: on
line diff
--- a/python/storage.py Thu Jul 23 09:31:47 2015 -0400 +++ b/python/storage.py Fri Jul 24 17:58:59 2015 -0400 @@ -34,19 +34,47 @@ except sqlite3.OperationalError as error: printDBError(error) -def createIndex(filename, tableName, columnName, createAnyway = False): +def createIndex(connection, tableName, columnName, unique = False): '''Creates an index for the column in the table I will make querying with a condition on this column faster''' try: - connection = sqlite3.connect(filename) + #connection = sqlite3.connect(filename) cursor = connection.cursor() - if createAnyway: - notExists = "" + s = "CREATE " + if unique: + s += "UNIQUE " + cursor.execute(s+"INDEX IF NOT EXISTS "+tableName+"_"+columnName+"_index ON "+tableName+"("+columnName+")") + connection.commit() + #connection.close() + except sqlite3.OperationalError as error: + printDBError(error) + +def getNumberRowsTable(connection, tableName, columnName = None): + '''Returns the number of rows for the table + If columnName is not None, means we want the number of distinct values for that column + (otherwise, we can just count(*))''' + try: + cursor = connection.cursor() + if columnName is None: + cursor.execute("SELECT COUNT(*) from "+tableName) else: - notExists = "IF NOT EXISTS " - cursor.execute("CREATE INDEX "+notExists+tableName+"_"+columnName+"_index ON "+tableName+"("+columnName+")") - connection.commit() - connection.close() + cursor.execute("SELECT COUNT(DISTINCT "+columnName+") from "+tableName) + return cursor.fetchone()[0] + except sqlite3.OperationalError as error: + printDBError(error) + +def getMinMax(connection, tableName, columnName, minmax): + '''Returns max/min or both for given column in table + minmax must be string max, min or minmax''' + try: + cursor = connection.cursor() + if minmax == 'min' or minmax == 'max': + cursor.execute("SELECT "+minmax+"("+columnName+") from "+tableName) + elif minmax == 'minmax': + cursor.execute("SELECT MIN("+columnName+"), MAX("+columnName+") from "+tableName) + else: + print("Argument minmax unknown: {}".format(minmax)) + return cursor.fetchone()[0] except sqlite3.OperationalError as error: printDBError(error)