Merge branch 'master' of git://git.assembla.com/fpdb-sql

This commit is contained in:
Ray 2009-06-23 10:23:05 -04:00
commit 24b7af5703
6 changed files with 144 additions and 113 deletions

View File

@ -39,7 +39,7 @@ import SQL
import Card import Card
class Database: class Database:
def __init__(self, c, db_name, game): def __init__(self, c, db_name = None, game = None): # db_name and game not used any more
self.fdb = fpdb_db.fpdb_db() # sets self.fdb.db self.fdb.cursor and self.fdb.sql self.fdb = fpdb_db.fpdb_db() # sets self.fdb.db self.fdb.cursor and self.fdb.sql
self.fdb.do_connect(c) self.fdb.do_connect(c)
self.connection = self.fdb.db self.connection = self.fdb.db
@ -48,7 +48,7 @@ class Database:
self.import_options = c.get_import_parameters() self.import_options = c.get_import_parameters()
self.type = db_params['db-type'] self.type = db_params['db-type']
self.backend = db_params['db-backend'] self.backend = db_params['db-backend']
self.sql = SQL.Sql(game = game, type = self.type, db_server = db_params['db-server']) self.sql = SQL.Sql(type = self.type, db_server = db_params['db-server'])
self.connection.rollback() self.connection.rollback()
# To add to config: # To add to config:

View File

@ -30,12 +30,11 @@ import fpdb_db
import FpdbSQLQueries import FpdbSQLQueries
class Filters(threading.Thread): class Filters(threading.Thread):
def __init__(self, db, settings, config, qdict, display = {},debug=True): def __init__(self, db, config, qdict, display = {}, debug=True):
self.debug=debug self.debug=debug
#print "start of GraphViewer constructor" #print "start of GraphViewer constructor"
self.db=db self.db=db
self.cursor=db.cursor self.cursor=db.cursor
self.settings=settings
self.sql=qdict self.sql=qdict
self.conf = config self.conf = config
self.display = display self.display = display
@ -235,7 +234,7 @@ class Filters(threading.Thread):
def __set_hero_name(self, w, site): def __set_hero_name(self, w, site):
self.heroes[site] = w.get_text() self.heroes[site] = w.get_text()
# print "DEBUG: settings heroes[%s]: %s"%(site, self.heroes[site]) # print "DEBUG: setting heroes[%s]: %s"%(site, self.heroes[site])
def createSiteLine(self, hbox, site): def createSiteLine(self, hbox, site):
cb = gtk.CheckButton(site) cb = gtk.CheckButton(site)
@ -556,23 +555,12 @@ def main(argv=None):
config = Configuration.Config() config = Configuration.Config()
db = None db = None
settings = {}
settings.update(config.get_db_parameters())
settings.update(config.get_tv_parameters())
settings.update(config.get_import_parameters())
settings.update(config.get_default_paths())
db = fpdb_db.fpdb_db() db = fpdb_db.fpdb_db()
db.connect(settings['db-backend'], db.do_connect(config)
settings['db-host'],
settings['db-databaseName'],
settings['db-user'],
settings['db-password'])
qdict = FpdbSQLQueries.FpdbSQLQueries(db.get_backend_name()) qdict = FpdbSQLQueries.FpdbSQLQueries(db.get_backend_name())
i = Filters(db, settings, config, qdict) i = Filters(db, config, qdict)
main_window = gtk.Window() main_window = gtk.Window()
main_window.connect('destroy', destroy) main_window.connect('destroy', destroy)
main_window.add(i.get_vbox()) main_window.add(i.get_vbox())

View File

@ -43,13 +43,13 @@ import Filters
class GuiGraphViewer (threading.Thread): class GuiGraphViewer (threading.Thread):
def __init__(self, db, settings, querylist, config, debug=True): def __init__(self, querylist, config, debug=True):
"""Constructor for GraphViewer""" """Constructor for GraphViewer"""
self.debug=debug self.debug=debug
#print "start of GraphViewer constructor" #print "start of GraphViewer constructor"
self.db=db self.db = fpdb_db.fpdb_db() # sets self.fdb.db self.fdb.cursor and self.fdb.sql
self.cursor=db.cursor self.db.do_connect(config)
self.settings=settings
self.sql = querylist self.sql = querylist
self.conf = config self.conf = config
@ -63,7 +63,7 @@ class GuiGraphViewer (threading.Thread):
"Button2" : True "Button2" : True
} }
self.filters = Filters.Filters(db, settings, config, querylist, display = filters_display) self.filters = Filters.Filters(self.db, config, querylist, display = filters_display)
self.filters.registerButton1Name("Refresh Graph") self.filters.registerButton1Name("Refresh Graph")
self.filters.registerButton1Callback(self.generateGraph) self.filters.registerButton1Callback(self.generateGraph)
self.filters.registerButton2Name("Export to File") self.filters.registerButton2Name("Export to File")
@ -146,7 +146,7 @@ class GuiGraphViewer (threading.Thread):
for site in sites: for site in sites:
if sites[site] == True: if sites[site] == True:
sitenos.append(siteids[site]) sitenos.append(siteids[site])
self.cursor.execute(self.sql.query['getPlayerId'], (heroes[site],)) self.db.cursor.execute(self.sql.query['getPlayerId'], (heroes[site],))
result = self.db.cursor.fetchall() result = self.db.cursor.fetchall()
if len(result) == 1: if len(result) == 1:
playerids.append(result[0][0]) playerids.append(result[0][0])
@ -226,7 +226,7 @@ class GuiGraphViewer (threading.Thread):
#print "DEBUG: sql query:" #print "DEBUG: sql query:"
#print tmp #print tmp
self.cursor.execute(tmp) self.db.cursor.execute(tmp)
#returns (HandId,Winnings,Costs,Profit) #returns (HandId,Winnings,Costs,Profit)
winnings = self.db.cursor.fetchall() winnings = self.db.cursor.fetchall()
self.db.db.rollback() self.db.db.rollback()

View File

@ -66,7 +66,7 @@ class GuiPlayerStats (threading.Thread):
"Button2" : True "Button2" : True
} }
self.filters = Filters.Filters(self.db, settings, config, querylist, display = filters_display) self.filters = Filters.Filters(self.db, config, querylist, display = filters_display)
self.filters.registerButton1Name("_Filters") self.filters.registerButton1Name("_Filters")
self.filters.registerButton1Callback(self.showDetailFilter) self.filters.registerButton1Callback(self.showDetailFilter)
self.filters.registerButton2Name("_Refresh") self.filters.registerButton2Name("_Refresh")
@ -227,11 +227,6 @@ class GuiPlayerStats (threading.Thread):
if not flags: holecards = False if not flags: holecards = False
else: holecards = flags[0] else: holecards = flags[0]
self.stats_table = gtk.Table(1, 1, False)
self.stats_table.set_col_spacings(4)
self.stats_table.show()
tmp = self.sql.query[query] tmp = self.sql.query[query]
tmp = self.refineQuery(tmp, flags, playerids, sitenos, limits, seats, groups, dates) tmp = self.refineQuery(tmp, flags, playerids, sitenos, limits, seats, groups, dates)
self.cursor.execute(tmp) self.cursor.execute(tmp)
@ -279,10 +274,6 @@ class GuiPlayerStats (threading.Thread):
while sqlrow < rows: while sqlrow < rows:
treerow = [] treerow = []
if(row%2 == 0):
bgcolor = "white"
else:
bgcolor = "lightgrey"
for col,column in enumerate(cols_to_show): for col,column in enumerate(cols_to_show):
if column[colalias] in colnames: if column[colalias] in colnames:
value = result[sqlrow][colnames.index(column[colalias])] value = result[sqlrow][colnames.index(column[colalias])]

View File

@ -20,6 +20,7 @@ import pygtk
pygtk.require('2.0') pygtk.require('2.0')
import gtk import gtk
import os import os
from time import time, strftime
import fpdb_import import fpdb_import
import fpdb_db import fpdb_db
@ -58,21 +59,50 @@ class GuiPositionalStats (threading.Thread):
"Button2" : False "Button2" : False
} }
self.filters = Filters.Filters(self.db, settings, config, querylist, display = filters_display) self.filters = Filters.Filters(self.db, config, querylist, display = filters_display)
self.filters.registerButton1Name("Refresh") self.filters.registerButton1Name("Refresh")
self.filters.registerButton1Callback(self.refreshStats) self.filters.registerButton1Callback(self.refreshStats)
# ToDo: store in config
# ToDo: create popup to adjust column config
# columns to display, keys match column name returned by sql, values in tuple are:
# is column displayed, column heading, xalignment, formatting
self.columns = [ ["game", True, "Game", 0.0, "%s"]
, ["hand", False, "Hand", 0.0, "%s"] # true not allowed for this line
, ["plposition", False, "Posn", 1.0, "%s"] # true not allowed for this line (set in code)
, ["n", True, "Hds", 1.0, "%d"]
, ["avgseats", True, "Seats", 1.0, "%3.1f"]
, ["vpip", True, "VPIP", 1.0, "%3.1f"]
, ["pfr", True, "PFR", 1.0, "%3.1f"]
, ["pf3", True, "PF3", 1.0, "%3.1f"]
, ["steals", True, "Steals", 1.0, "%3.1f"]
, ["saw_f", True, "Saw_F", 1.0, "%3.1f"]
, ["sawsd", True, "SawSD", 1.0, "%3.1f"]
, ["wtsdwsf", True, "WtSDwsF", 1.0, "%3.1f"]
, ["wmsd", True, "W$SD", 1.0, "%3.1f"]
, ["flafq", True, "FlAFq", 1.0, "%3.1f"]
, ["tuafq", True, "TuAFq", 1.0, "%3.1f"]
, ["rvafq", True, "RvAFq", 1.0, "%3.1f"]
, ["pofafq", False, "PoFAFq", 1.0, "%3.1f"]
, ["net", True, "Net($)", 1.0, "%6.2f"]
, ["bbper100", True, "bb/100", 1.0, "%4.2f"]
, ["rake", True, "Rake($)", 1.0, "%6.2f"]
, ["bb100xr", True, "bbxr/100", 1.0, "%4.2f"]
, ["variance", True, "Variance", 1.0, "%5.2f"]
]
self.stat_table = None self.stat_table = None
self.stats_frame = None self.stats_frame = None
self.stats_vbox = None
self.main_hbox = gtk.HBox(False, 0) self.main_hbox = gtk.HBox(False, 0)
self.main_hbox.show() self.main_hbox.show()
statsFrame = gtk.Frame("Stats:") self.stats_frame = gtk.Frame()
statsFrame.set_label_align(0.0, 0.0) self.stats_frame.set_label_align(0.0, 0.0)
statsFrame.show()
self.stats_frame = gtk.VBox(False, 0)
self.stats_frame.show() self.stats_frame.show()
self.stats_vbox = gtk.VBox(False, 0)
self.stats_vbox.show()
# This could be stored in config eventually, or maybe configured in this window somehow. # This could be stored in config eventually, or maybe configured in this window somehow.
# Each posncols element is the name of a column returned by the sql # Each posncols element is the name of a column returned by the sql
@ -90,11 +120,11 @@ class GuiPositionalStats (threading.Thread):
, "PoFAFq", "Net($)", "bb/100", "$/hand", "Variance", "Hds" , "PoFAFq", "Net($)", "bb/100", "$/hand", "Variance", "Hds"
) )
self.fillStatsFrame(self.stats_frame) self.fillStatsFrame(self.stats_vbox)
statsFrame.add(self.stats_frame) self.stats_frame.add(self.stats_vbox)
self.main_hbox.pack_start(self.filters.get_vbox()) self.main_hbox.pack_start(self.filters.get_vbox())
self.main_hbox.pack_start(statsFrame) self.main_hbox.pack_start(self.stats_frame)
def get_vbox(self): def get_vbox(self):
@ -107,9 +137,12 @@ class GuiPositionalStats (threading.Thread):
print "DEBUG: activesite set to %s" %(self.activesite) print "DEBUG: activesite set to %s" %(self.activesite)
def refreshStats(self, widget, data): def refreshStats(self, widget, data):
try: self.stats_table.destroy() try: self.stats_vbox.destroy()
except AttributeError: pass except AttributeError: pass
self.fillStatsFrame(self.stats_frame) self.stats_vbox = gtk.VBox(False, 0)
self.stats_vbox.show()
self.stats_frame.add(self.stats_vbox)
self.fillStatsFrame(self.stats_vbox)
def fillStatsFrame(self, vbox): def fillStatsFrame(self, vbox):
sites = self.filters.getSites() sites = self.filters.getSites()
@ -144,66 +177,104 @@ class GuiPositionalStats (threading.Thread):
self.createStatsTable(vbox, playerids, sitenos, limits, seats, dates) self.createStatsTable(vbox, playerids, sitenos, limits, seats, dates)
def createStatsTable(self, vbox, playerids, sitenos, limits, seats, dates): def createStatsTable(self, vbox, playerids, sitenos, limits, seats, dates):
self.stats_table = gtk.Table(1, 1, False) # gtk table expands as required
self.stats_table.set_col_spacings(4)
self.stats_table.show()
vbox.add(self.stats_table)
starttime = time()
colalias,colshow,colheading,colxalign,colformat = 0,1,2,3,4
row = 0 row = 0
col = 0 col = 0
for t in self.posnheads:
l = gtk.Label(self.posnheads[col])
l.show()
self.stats_table.attach(l, col, col+1, row, row+1, yoptions=gtk.SHRINK)
col +=1
tmp = self.sql.query['playerStatsByPosition'] tmp = self.sql.query['playerStatsByPosition']
tmp = self.refineQuery(tmp, playerids, sitenos, limits, seats, dates) tmp = self.refineQuery(tmp, playerids, sitenos, limits, seats, dates)
self.cursor.execute(tmp) self.cursor.execute(tmp)
result = self.cursor.fetchall() result = self.cursor.fetchall()
colnames = [desc[0].lower() for desc in self.cursor.description]
liststore = gtk.ListStore(*([str] * len(colnames)))
view = gtk.TreeView(model=liststore)
view.set_grid_lines(gtk.TREE_VIEW_GRID_LINES_BOTH)
vbox.pack_start(view, expand=False, padding=3)
# left-aligned cells:
textcell = gtk.CellRendererText()
# centred cells:
textcell50 = gtk.CellRendererText()
textcell50.set_property('xalign', 0.5)
# right-aligned cells:
numcell = gtk.CellRendererText()
numcell.set_property('xalign', 1.0)
listcols = []
for t in self.posnheads:
listcols.append(gtk.TreeViewColumn(self.posnheads[col]))
view.append_column(listcols[col])
if col == 0:
listcols[col].pack_start(textcell, expand=True)
listcols[col].add_attribute(textcell, 'text', col)
listcols[col].set_expand(True)
elif col in (1, 2):
listcols[col].pack_start(textcell50, expand=True)
listcols[col].add_attribute(textcell50, 'text', col)
listcols[col].set_expand(True)
else:
listcols[col].pack_start(numcell, expand=True)
listcols[col].add_attribute(numcell, 'text', col)
listcols[col].set_expand(True)
col +=1
# Code below to be used when full column data structures implemented like in player stats:
# Create header row eg column: ("game", True, "Game", 0.0, "%s")
#for col, column in enumerate(cols_to_show):
# if column[colalias] == 'game' and holecards:
# s = [x for x in self.columns if x[colalias] == 'hand'][0][colheading]
# else:
# s = column[colheading]
# listcols.append(gtk.TreeViewColumn(s))
# view.append_column(listcols[col])
# if column[colformat] == '%s':
# if column[colxalign] == 0.0:
# listcols[col].pack_start(textcell, expand=True)
# listcols[col].add_attribute(textcell, 'text', col)
# else:
# listcols[col].pack_start(textcell50, expand=True)
# listcols[col].add_attribute(textcell50, 'text', col)
# listcols[col].set_expand(True)
# else:
# listcols[col].pack_start(numcell, expand=True)
# listcols[col].add_attribute(numcell, 'text', col)
# listcols[col].set_expand(True)
# #listcols[col].set_alignment(column[colxalign]) # no effect?
rows = len(result) rows = len(result)
colnames = [desc[0].lower() for desc in self.cursor.description]
last_game,last_seats,sqlrow = "","",0 last_game,last_seats,sqlrow = "","",0
while sqlrow < rows: while sqlrow < rows:
if(row%2 == 0):
bgcolor = "white"
else:
bgcolor = "lightgrey"
rowprinted=0 rowprinted=0
treerow = []
avgcol = colnames.index('avgseats') avgcol = colnames.index('avgseats')
for col,colname in enumerate(self.posncols): for col,colname in enumerate(self.posncols):
if colname in colnames: if colname in colnames:
sqlcol = colnames.index(colname) sqlcol = colnames.index(colname)
else: else:
continue continue
eb = gtk.EventBox()
eb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse(bgcolor))
# print blank row between levels:
if result[sqlrow][sqlcol]: if result[sqlrow][sqlcol]:
if sqlrow == 0: if sqlrow == 0:
l = gtk.Label(result[sqlrow][sqlcol]) value = result[sqlrow][sqlcol]
rowprinted=1 rowprinted=1
elif result[sqlrow][0] != last_game: elif result[sqlrow][0] != last_game:
l = gtk.Label(' ') value = ' '
elif 'show' in seats and seats['show'] and result[sqlrow][avgcol] != last_seats: elif 'show' in seats and seats['show'] and result[sqlrow][avgcol] != last_seats:
l = gtk.Label(' ') value = ' '
else: else:
l = gtk.Label(result[sqlrow][sqlcol]) value = result[sqlrow][sqlcol]
rowprinted=1 rowprinted=1
else: else:
l = gtk.Label(' ') l = gtk.Label(' ')
if col == 0: value = ' '
l.set_alignment(xalign=0.0, yalign=0.5) if value and value != -999:
elif col == 1: treerow.append(value)
l.set_alignment(xalign=0.5, yalign=0.5)
else: else:
l.set_alignment(xalign=1.0, yalign=0.5) treerow.append(' ')
eb.add(l) iter = liststore.append(treerow)
self.stats_table.attach(eb, col, col+1, row+1, row+2, yoptions=gtk.SHRINK)
l.show()
eb.show()
last_game = result[sqlrow][0] last_game = result[sqlrow][0]
last_seats = result[sqlrow][avgcol] last_seats = result[sqlrow][avgcol]
if rowprinted: if rowprinted:
@ -220,50 +291,36 @@ class GuiPositionalStats (threading.Thread):
# blank row between main stats and totals: # blank row between main stats and totals:
col = 0 col = 0
if(row%2 == 0): treerow = [' ' for x in self.posncols]
bgcolor = "white" iter = liststore.append(treerow)
else:
bgcolor = "lightgrey"
eb = gtk.EventBox()
eb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse(bgcolor))
l = gtk.Label(' ')
eb.add(l)
self.stats_table.attach(eb, col, col+1, row+1, row+2, yoptions=gtk.SHRINK)
l.show()
eb.show()
row = row + 1 row = row + 1
for sqlrow in range(rows): for sqlrow in range(rows):
if(row%2 == 0): treerow = []
bgcolor = "white"
else:
bgcolor = "lightgrey"
for col,colname in enumerate(self.posncols): for col,colname in enumerate(self.posncols):
if colname in colnames: if colname in colnames:
sqlcol = colnames.index(colname) sqlcol = colnames.index(colname)
elif colname != "plposition": elif colname != "plposition":
continue continue
eb = gtk.EventBox()
eb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse(bgcolor))
if colname == 'plposition': if colname == 'plposition':
l = gtk.Label('Totals') l = gtk.Label('Totals')
value = 'Totals'
elif result[sqlrow][sqlcol]: elif result[sqlrow][sqlcol]:
l = gtk.Label(result[sqlrow][sqlcol]) l = gtk.Label(result[sqlrow][sqlcol])
value = result[sqlrow][sqlcol]
else: else:
l = gtk.Label(' ') l = gtk.Label(' ')
if col == 0: value = ' '
l.set_alignment(xalign=0.0, yalign=0.5) if value and value != -999:
elif col == 1: treerow.append(value)
l.set_alignment(xalign=0.5, yalign=0.5)
else: else:
l.set_alignment(xalign=1.0, yalign=0.5) treerow.append(' ')
eb.add(l) iter = liststore.append(treerow)
self.stats_table.attach(eb, col, col+1, row+1, row+2, yoptions=gtk.SHRINK)
l.show()
eb.show()
row = row + 1 row = row + 1
vbox.show_all()
self.db.db.rollback() self.db.db.rollback()
print "Positional Stats page displayed in %4.2f seconds" % (time() - starttime)
#end def fillStatsFrame(self, vbox): #end def fillStatsFrame(self, vbox):
def refineQuery(self, query, playerids, sitenos, limits, seats, dates): def refineQuery(self, query, playerids, sitenos, limits, seats, dates):

View File

@ -41,6 +41,7 @@ import GuiTableViewer
import GuiAutoImport import GuiAutoImport
import GuiGraphViewer import GuiGraphViewer
import GuiSessionViewer import GuiSessionViewer
import Database
import FpdbSQLQueries import FpdbSQLQueries
import Configuration import Configuration
@ -363,11 +364,7 @@ class fpdb:
self.db = fpdb_db.fpdb_db() self.db = fpdb_db.fpdb_db()
#print "end of fpdb.load_profile, databaseName:",self.settings['db-databaseName'] #print "end of fpdb.load_profile, databaseName:",self.settings['db-databaseName']
self.db.connect(self.settings['db-backend'], self.db.do_connect(self.config)
self.settings['db-host'],
self.settings['db-databaseName'],
self.settings['db-user'],
self.settings['db-password'])
if self.db.wrongDbVersion: if self.db.wrongDbVersion:
diaDbVersionWarning = gtk.Dialog(title="Strong Warning - Invalid database version", parent=None, flags=0, buttons=(gtk.STOCK_OK,gtk.RESPONSE_OK)) diaDbVersionWarning = gtk.Dialog(title="Strong Warning - Invalid database version", parent=None, flags=0, buttons=(gtk.STOCK_OK,gtk.RESPONSE_OK))
@ -388,6 +385,8 @@ class fpdb:
# Database connected to successfully, load queries to pass on to other classes # Database connected to successfully, load queries to pass on to other classes
self.querydict = FpdbSQLQueries.FpdbSQLQueries(self.db.get_backend_name()) self.querydict = FpdbSQLQueries.FpdbSQLQueries(self.db.get_backend_name())
self.dbi = Database.Database(self.config) # dbi for db interface and to avoid clashes with db/database/etc
# can rename later if required
self.db.db.rollback() self.db.db.rollback()
#end def load_profile #end def load_profile
@ -398,11 +397,7 @@ class fpdb:
def obtain_global_lock(self): def obtain_global_lock(self):
print "\nTaking global lock ..." print "\nTaking global lock ..."
self.fdb_lock = fpdb_db.fpdb_db() self.fdb_lock = fpdb_db.fpdb_db()
self.fdb_lock.connect(self.settings['db-backend'], self.fdb_lock.do_connect(self.config)
self.settings['db-host'],
self.settings['db-databaseName'],
self.settings['db-user'],
self.settings['db-password'])
return self.fdb_lock.get_global_lock() return self.fdb_lock.get_global_lock()
#end def obtain_global_lock #end def obtain_global_lock
@ -474,7 +469,7 @@ This program is licensed under the AGPL3, see docs"""+os.sep+"agpl-3.0.txt")
def tabGraphViewer(self, widget, data=None): def tabGraphViewer(self, widget, data=None):
"""opens a graph viewer tab""" """opens a graph viewer tab"""
#print "start of tabGraphViewer" #print "start of tabGraphViewer"
new_gv_thread=GuiGraphViewer.GuiGraphViewer(self.db, self.settings, self.querydict, self.config) new_gv_thread = GuiGraphViewer.GuiGraphViewer(self.querydict, self.config)
self.threads.append(new_gv_thread) self.threads.append(new_gv_thread)
gv_tab=new_gv_thread.get_vbox() gv_tab=new_gv_thread.get_vbox()
self.add_and_display_tab(gv_tab, "Graphs") self.add_and_display_tab(gv_tab, "Graphs")