From 2ae58f8947d787f978f7491492c4c9ecc5abfd88 Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Sat, 31 Oct 2009 12:12:17 +0100 Subject: [PATCH 01/54] databases can now be activated by user ++ refactoring Signed-off-by: fpdb-mme --- pyfpdb/DatabaseManager.py | 165 ++++++++++++++++++++++++++++++-------- 1 file changed, 133 insertions(+), 32 deletions(-) diff --git a/pyfpdb/DatabaseManager.py b/pyfpdb/DatabaseManager.py index ddaa6fcd..e584d7eb 100644 --- a/pyfpdb/DatabaseManager.py +++ b/pyfpdb/DatabaseManager.py @@ -3,9 +3,10 @@ import os import pygtk pygtk.require('2.0') import gtk +import gobject #******************************************************************************************************* -class DatabaseManager(object): +class DatabaseManager(gobject.GObject): DatabaseTypes = {} @classmethod @@ -19,10 +20,16 @@ class DatabaseManager(object): ) return klass(databases=databases, defaultDatabaseType=defaultDatabaseType) + def to_fpdb(self): + pass + def __init__(self, databases=None, defaultDatabaseType=None): + gobject.GObject.__init__(self) + self._defaultDatabaseType = defaultDatabaseType self._databases = [] if databases is None else list(databases) + self._activeDatabase = None def __iter__(self): return iter(self._databases) def set_default_database_type(self, databaseType): @@ -31,7 +38,7 @@ class DatabaseManager(object): return self._defaultDatabaseType def database_from_id(self, idDatabase): for database in self._databases: - if idDatabase == id(database): + if idDatabase == self.database_id(database): return database def database_id(self, database): return id(database) @@ -43,6 +50,25 @@ class DatabaseManager(object): self._databases.remove(database) def init_database(self, database): pass + def activate_database(self, database): + if self._activeDatabase is not None: + self._activeDatabase.status = self._activeDatabase.StatusInactive + #TODO: finalize database + self.emit('database-deactivated', self.database_id(self._activeDatabase) ) + + database.status = database.StatusActive + #TODO: activate database + self._activeDatabase = database + self.emit('database-activated', self.database_id(database) ) + + def active_database(self): + return self._activeDatabase + +# register DatabaseManager signals +gobject.type_register(DatabaseManager) +gobject.signal_new('database-activated', DatabaseManager, gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (int, )) +gobject.signal_new('database-deactivated', DatabaseManager, gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (int, )) + class DatabaseTypeMeta(type): def __new__(klass, name, bases, kws): @@ -56,8 +82,10 @@ class DatabaseTypeMeta(type): class DatabaseTypeBase(object): __metaclass__ = DatabaseTypeMeta Type = None - Params = () - + StatusActive = 'active' + StatusInactive = 'inactive' + StatusError = 'error' #TODO: not implemented + class DatabaseTypePostgres(DatabaseTypeBase): Type = 'postgres' @classmethod @@ -70,7 +98,8 @@ class DatabaseTypePostgres(DatabaseTypeBase): self.user = user self.password = password self.database = database - + self.status = self.StatusInactive + class DatabaseTypeMysql(DatabaseTypeBase): Type = 'mysql' @classmethod @@ -83,6 +112,7 @@ class DatabaseTypeMysql(DatabaseTypeBase): self.user = user self.password = password self.database = database + self.status = self.StatusInactive class DatabaseTypeSqLite(DatabaseTypeBase): Type = 'sqlite' @@ -93,6 +123,7 @@ class DatabaseTypeSqLite(DatabaseTypeBase): self.name = name self.file = file self.database = database + self.status = self.StatusInactive #TODO: how do we want to handle unsupported database types? # ..uncomment to remove unsupported database types @@ -375,8 +406,16 @@ class WidgetDatabaseManager(gtk.VBox): def __init__(self, databaseManager, parentWidget=None): gtk.VBox.__init__(self) - self.databaseManager = databaseManager self.parentWidget = parentWidget + self.databaseManager = databaseManager + self.databaseManager.connect('database-activated', self.on_database_activated) + self.databaseManager.connect('database-deactivated', self.on_database_deactivated) + self.databaseStatusNames = { + DatabaseTypeBase.StatusActive: 'Active', + DatabaseTypeBase.StatusInactive: 'Inactive', + DatabaseTypeBase.StatusError: 'Error', + } + #TODO: dono how to make word wrap work as expected self.labelInfo = gtk.Label('database management') @@ -389,6 +428,10 @@ class WidgetDatabaseManager(gtk.VBox): #TODO: bit messy the distinction New/Add/Edit. we'd have to pass three flags to DialogDatabaseProperties # to handle this. maybe drop Edit (is just a Remove + Add), to keep things simple + self.buttonDatabaseActivate = gtk.Button("Activate") + self.buttonDatabaseActivate.set_tooltip_text('activates the database') + self.buttonDatabaseActivate.connect('clicked', self.on_button_database_activate_clicked) + self.buttonDatabaseActivate.set_sensitive(False) self.buttonDatabaseNew = gtk.Button("New..") self.buttonDatabaseNew.set_tooltip_text('creates a new database') self.buttonDatabaseNew.connect('clicked', self.on_button_database_new_clicked) @@ -402,31 +445,30 @@ class WidgetDatabaseManager(gtk.VBox): self.buttonDatabaseRemove = gtk.Button("Remove") self.buttonDatabaseRemove.set_tooltip_text('removes the database from the list') self.buttonDatabaseRemove.set_sensitive(False) + self.buttonDatabaseRemove.connect('clicked', self.on_button_database_remove_clicked) #TODO: i dont think we should do any real database management here. maybe drop it - self.buttonDatabaseDelete = gtk.Button("Delete") - self.buttonDatabaseDelete.set_tooltip_text('removes the database from the list and deletes it') - self.buttonDatabaseDelete.set_sensitive(False) + #self.buttonDatabaseDelete = gtk.Button("Delete") + #self.buttonDatabaseDelete.set_tooltip_text('removes the database from the list and deletes it') + #self.buttonDatabaseDelete.set_sensitive(False) # init database tree self.treeDatabases = gtk.TreeView() - self.treeDatabaseColumns = ( #NOTE: column names starting with '_' will be hidden - 'Name', - 'Status', - 'Type', - '_id', + treeDatabaseColumns = ( # name, displayName, dataType + ('name', 'Name', str), + ('status', 'Status', str), + ('type', 'Type', str), + ('_id', '', int), ) - - store = gtk.ListStore(str, str, str, int) + self.treeDatabaseColumns = {} # name --> index + store = gtk.ListStore( *[i[2] for i in treeDatabaseColumns] ) self.treeDatabases.set_model(store) - columns = ('Name', 'Status', 'Type', '_id') - for i, column in enumerate(columns): - col = gtk.TreeViewColumn(column, gtk.CellRendererText(), text=i) + for i, (name, displayName, dataType) in enumerate(treeDatabaseColumns): + col = gtk.TreeViewColumn(displayName, gtk.CellRendererText(), text=i) self.treeDatabases.append_column(col) - if column.startswith('_'): + if name.startswith('_'): col.set_visible(False) - - self.treeDatabaseColumns = dict([(name, i) for (i, name) in enumerate(self.treeDatabaseColumns)]) + self.treeDatabaseColumns[name] = i self.treeDatabases.get_selection().connect('changed', self.on_tree_databases_selection_changed) # layout widgets @@ -438,11 +480,12 @@ class WidgetDatabaseManager(gtk.VBox): hbox.set_homogeneous(False) vbox = gtk.VBox() hbox.pack_start(vbox, False, False, 2) + vbox.pack_start(self.buttonDatabaseActivate, False, False, 2) vbox.pack_start(self.buttonDatabaseNew, False, False, 2) vbox.pack_start(self.buttonDatabaseAdd, False, False, 2) vbox.pack_start(self.buttonDatabaseEdit, False, False, 2) vbox.pack_start(self.buttonDatabaseRemove, False, False, 2) - vbox.pack_start(self.buttonDatabaseDelete, False, False, 2) + #vbox.pack_start(self.buttonDatabaseDelete, False, False, 2) box = gtk.VBox() vbox.pack_start(box, True, True, 0) @@ -452,9 +495,48 @@ class WidgetDatabaseManager(gtk.VBox): self.show_all() # init widget + model = self.treeDatabases.get_model() for database in self.databaseManager: - self.treeDatabases.get_model().append( (database.name, 'foo', database.Type, self.databaseManager.database_id(database)) ) + it = model.append() + model.set_value(it, self.treeDatabaseColumns['name'], database.name) + model.set_value(it, self.treeDatabaseColumns['status'], self.databaseStatusNames[database.status] ) + model.set_value(it, self.treeDatabaseColumns['type'], database.display_name() ) + model.set_value(it, self.treeDatabaseColumns['_id'], self.databaseManager.database_id(database)) + + def on_database_activated(self, databaseManager, idDatabase): + database = self.databaseManager.database_from_id(idDatabase) + model = self.treeDatabases.get_model() + for row in iter(model): + if row[self.treeDatabaseColumns['_id']] == idDatabase: + row[self.treeDatabaseColumns['status']] = self.databaseStatusNames[database.StatusActive] + break + else: + raise ValueError('database not found') + + + def on_database_deactivated(self, databaseManager, idDatabase): + database = self.databaseManager.database_from_id(idDatabase) + model = self.treeDatabases.get_model() + for row in iter(model): + if row[self.treeDatabaseColumns['_id']] == idDatabase: + row[self.treeDatabaseColumns['status']] = self.databaseStatusNames[database.StatusInactive] + break + else: + raise ValueError('database not found') + + + def on_button_database_activate_clicked(self, button): + selection = self.treeDatabases.get_selection() + if selection is None: + return + + model, it = selection.get_selected() + idDatabase = model.get_value(it, self.treeDatabaseColumns['_id']) + database = self.databaseManager.database_from_id(idDatabase) + self.databaseManager.activate_database(database) + + #TODO: for some reason i have to click OK/Cancel twice to close the dialog def on_button_database_new_clicked(self, button): databaseType = self.databaseManager.get_default_database_type() @@ -476,6 +558,7 @@ class WidgetDatabaseManager(gtk.VBox): self.treeDatabases.get_model().append( (database.name, 'foo', database.Type, self.databaseManager.database_id(database)) ) dlg.destroy() + def on_button_database_add_clicked(self, button): databaseType = self.databaseManager.get_default_database_type() if databaseType is None: @@ -493,7 +576,13 @@ class WidgetDatabaseManager(gtk.VBox): database = dlg.get_widget_database_properties().get_database() #TODO: sanity checks self.databaseManager.add_database(database) - self.treeDatabases.get_model().append( (database.name, 'foo', database.Type, self.databaseManager.database_id(database)) ) + model = self.treeDatabases.get_model() + it = model.append() + print database.name + model.set_value(it, self.treeDatabaseColumns['name'], database.name) + model.set_value(it, self.treeDatabaseColumns['status'], self.databaseStatusNames[database.status] ) + model.set_value(it, self.treeDatabaseColumns['type'], database.display_name() ) + model.set_value(it, self.treeDatabaseColumns['_id'], self.databaseManager.database_id(database)) dlg.destroy() def on_button_database_edit_clicked(self, button): @@ -501,12 +590,12 @@ class WidgetDatabaseManager(gtk.VBox): if selection is None: return - model, iter = selection.get_selected() - idDatabase = model.get_value(iter, self.treeDatabaseColumns['_id']) + model, it = selection.get_selected() + idDatabase = model.get_value(it, self.treeDatabaseColumns['_id']) database = self.databaseManager.database_from_id(idDatabase) dlg = DialogDatabaseProperties( self.databaseManager, - database=database, + database, parent=self.parentWidget, mode=WidgetDatabaseProperties.ModeEdit, title='[Edit database] - database properties' @@ -517,17 +606,29 @@ class WidgetDatabaseManager(gtk.VBox): database = dlg.get_database() selection = self.treeDatabases.get_selection() if selection is not None: - model, iter = selection.get_selected() - model.set_value(iter, 0, database.name) + model, it = selection.get_selected() + model.set_value(it, self.treeDatabaseColumns['name'], database.name) dlg.destroy() + + def on_button_database_remove_clicked(self, button): + selection = self.treeDatabases.get_selection() + if selection is None: + return + + model, it = selection.get_selected() + #TODO: finalize database + model.remove(it) + + def on_tree_databases_selection_changed(self, treeSelection): hasSelection = bool(treeSelection.count_selected_rows()) - # enable/disable selection dependend widgets + # enable/disable selection dependend widgets + self.buttonDatabaseActivate.set_sensitive(hasSelection) self.buttonDatabaseEdit.set_sensitive(hasSelection) self.buttonDatabaseRemove.set_sensitive(hasSelection) - self.buttonDatabaseDelete.set_sensitive(hasSelection) + #self.buttonDatabaseDelete.set_sensitive(hasSelection) class DialogDatabaseManager(gtk.Dialog): From a944ba7cd3d66dceb6f622125e375a963dc24275 Mon Sep 17 00:00:00 2001 From: unknown Date: Sat, 31 Oct 2009 20:06:16 -0400 Subject: [PATCH 02/54] comments edit --- pyfpdb/fpdb.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pyfpdb/fpdb.py b/pyfpdb/fpdb.py index ef67749d..17720885 100755 --- a/pyfpdb/fpdb.py +++ b/pyfpdb/fpdb.py @@ -513,10 +513,10 @@ class fpdb: # self.lock.release() def quit(self, widget, data=None): + # TODO: can we get some / all of the stuff done in this function to execute on any kind of abort? print "Quitting normally" - #check if current settings differ from profile, if so offer to save or abort + # TODO: check if current settings differ from profile, if so offer to save or abort self.db.disconnect() - # hide icon as it doesn't go away immediately in Windows - is this ok in Linux Eric? self.statusIcon.set_visible(False) gtk.main_quit() From 868a0b5bf03002d34497baa705d6ec698f40e4d0 Mon Sep 17 00:00:00 2001 From: unknown Date: Sat, 31 Oct 2009 21:25:13 -0400 Subject: [PATCH 03/54] getting stud tourney to not crash import: fix call to storeHudCache in Database to use handStartTime rather than the undefined hand_start_time; stub out store_hands_players_stud_tourney as it looks like it was never updated to use current database setup. result: hud works, no longer crashes import, presumably does not store any hand info though. HHC base guessMaxSeats returns existing value of maxseats if some prior code has set it somewhere already --- pyfpdb/Database.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/pyfpdb/Database.py b/pyfpdb/Database.py index ba71310b..5bf7f488 100755 --- a/pyfpdb/Database.py +++ b/pyfpdb/Database.py @@ -761,14 +761,18 @@ class Database: hands_id = self.storeHands( self.backend, siteHandNo, gametypeId , handStartTime, names, tableName, maxSeats - , hudImportData, board_values, board_suits ) + , hudImportData, (None, None, None, None, None), (None, None, None, None, None) ) + # changed board_values and board_suits to arrays of None, just like the + # cash game version of this function does - i don't believe this to be + # the correct thing to do (tell me if i'm wrong) but it should keep the + # importer from crashing hands_players_ids = self.store_hands_players_stud_tourney(self.backend, hands_id , playerIds, startCashes, antes, cardValues, cardSuits , winnings, rakes, seatNos, tourneys_players_ids, tourneyTypeId) if 'dropHudCache' not in settings or settings['dropHudCache'] != 'drop': - self.storeHudCache(self.backend, base, category, gametypeId, hand_start_time, playerIds, hudImportData) + self.storeHudCache(self.backend, base, category, gametypeId, handStartTime, playerIds, hudImportData) return hands_id #end def tourney_stud @@ -1946,7 +1950,7 @@ class Database: def store_hands_players_stud_tourney(self, backend, hands_id, player_ids, start_cashes, antes, card_values, card_suits, winnings, rakes, seatNos, tourneys_players_ids, tourneyTypeId): #stores hands_players for tourney stud/razz hands - + return # TODO: stubbed out until someone updates it for current database structuring try: result=[] for i in xrange(len(player_ids)): From 64ee50223923a4a6ddeda6672399ac730ba54f5a Mon Sep 17 00:00:00 2001 From: unknown Date: Sat, 31 Oct 2009 21:25:27 -0400 Subject: [PATCH 04/54] here's the HHC patch i forgot to add on last commit --- pyfpdb/HandHistoryConverter.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pyfpdb/HandHistoryConverter.py b/pyfpdb/HandHistoryConverter.py index 0642d845..0024cfe5 100644 --- a/pyfpdb/HandHistoryConverter.py +++ b/pyfpdb/HandHistoryConverter.py @@ -451,7 +451,10 @@ or None if we fail to get the info """ self.doc = doc def guessMaxSeats(self, hand): - """Return a guess at max_seats when not specified in HH.""" + """Return a guess at maxseats when not specified in HH.""" + # if some other code prior to this has already set it, return it + if maxseats > 1 and maxseats < 11: + return maxseats mo = self.maxOccSeat(hand) if mo == 10: return 10 #that was easy From cdc310dcb64fd285078e5eb9bd6cd903e9090866 Mon Sep 17 00:00:00 2001 From: unknown Date: Sun, 1 Nov 2009 01:23:07 -0400 Subject: [PATCH 05/54] if HUD is told to create for a layout that doesn't exist in the config file, it will pick a 9 or 10 max layout and use it's positions, which you can then move the windows around, and save, and it should be saved in the right spot. --- pyfpdb/Hud.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/pyfpdb/Hud.py b/pyfpdb/Hud.py index 38402f8f..60fc29be 100644 --- a/pyfpdb/Hud.py +++ b/pyfpdb/Hud.py @@ -455,6 +455,9 @@ class Hud: # Need range here, not xrange -> need the actual list adj = range(0, self.max + 1) # default seat adjustments = no adjustment # does the user have a fav_seat? + if self.max not in config.supported_sites[self.table.site].layout: + sys.stderr.write("No layout found for %d-max games for site %s\n" % (self.max, self.table.site) ) + return adj if self.table.site != None and int(config.supported_sites[self.table.site].layout[self.max].fav_seat) > 0: try: fav_seat = config.supported_sites[self.table.site].layout[self.max].fav_seat @@ -494,6 +497,10 @@ class Hud: sys.stderr.write("------------------------------------------------------------\nCreating hud from hand %s\n" % hand) adj = self.adj_seats(hand, config) loc = self.config.get_locations(self.table.site, self.max) + if loc is None and self.max != 10: + loc = self.config.get_locations(self.table.site, 10) + if loc is None and self.max != 9: + loc = self.config.get_locations(self.table.site, 9) # create the stat windows for i in xrange(1, self.max + 1): From cb0c7430e691cd87f634a6985fad9f0e6977fede Mon Sep 17 00:00:00 2001 From: unknown Date: Sun, 1 Nov 2009 01:54:59 -0400 Subject: [PATCH 06/54] add comment at point in Configuration where we would need to add support for saving new table layouts. --- pyfpdb/Configuration.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index c89546ca..620217ab 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -555,7 +555,9 @@ class Config: fav_seat = None, locations = None): site_node = self.get_site_node(site_name) layout_node = self.get_layout_node(site_node, max) - if layout_node == None: return + # TODO: how do we support inserting new layouts? + if layout_node == None: + return for i in range(1, max + 1): location_node = self.get_location_node(layout_node, i) location_node.setAttribute("x", str( locations[i-1][0] )) From bcbafc160d76cfb85a7b18e7063b67e03daf224a Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Sun, 1 Nov 2009 07:36:18 +0100 Subject: [PATCH 07/54] millions of changes, highlights: - started validating user input on create/add database - implemented fuctionality to create sqlite databases - never worked with sqlite,, you can not create multiple dbs in one file, so removed db attr again - a nice todo list Signed-off-by: fpdb-mme --- pyfpdb/DatabaseManager.py | 234 ++++++++++++++++++++++++++++---------- 1 file changed, 174 insertions(+), 60 deletions(-) diff --git a/pyfpdb/DatabaseManager.py b/pyfpdb/DatabaseManager.py index e584d7eb..6bb2e8d4 100644 --- a/pyfpdb/DatabaseManager.py +++ b/pyfpdb/DatabaseManager.py @@ -1,3 +1,18 @@ +"""Database manager + +@todo: (gtk) how to validate user input in gtk.Dialog? as soon as the user clicks ok the dialog is dead. we use a while loop as workaround. not nice +@todo: (fpdb) we need the application name 'fpdb' from somewhere to put it in dialog titles + +@todo: (all dialogs) save/restore size and pos + +@todo: (WidgetDatabaseManager) give database status meaningful colors +@todo: (WidgetDatabaseManager) implement database purging +@todo: (WidgetDatabaseManager) implement database export +@todo: (WidgetDatabaseManager) what to do on database doubleclick? +@todo: (WidgetDatabaseManager) context menu for database tree +@todo: (WidgetDatabaseManager) initializing/validating databases may take a while. how to give feedback? + +""" import os import pygtk @@ -48,8 +63,7 @@ class DatabaseManager(gobject.GObject): self._databases.append(database) def remove_database(self, database): self._databases.remove(database) - def init_database(self, database): - pass + def activate_database(self, database): if self._activeDatabase is not None: self._activeDatabase.status = self._activeDatabase.StatusInactive @@ -68,7 +82,7 @@ class DatabaseManager(gobject.GObject): gobject.type_register(DatabaseManager) gobject.signal_new('database-activated', DatabaseManager, gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (int, )) gobject.signal_new('database-deactivated', DatabaseManager, gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (int, )) - +gobject.signal_new('database-error', DatabaseManager, gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (int, )) class DatabaseTypeMeta(type): def __new__(klass, name, bases, kws): @@ -86,6 +100,19 @@ class DatabaseTypeBase(object): StatusInactive = 'inactive' StatusError = 'error' #TODO: not implemented + #TODO: not happy with returning error string. just being too lazy to impl dozens of error codes for later translation + def init_new_database(self): + """initializes a new empty database + @return: (str) error if something goes wrong, None otherwise + """ + raise NotImplementedError() + + def validate_database(self): + """checks if the database is valid + @return: (str) error if something goes wrong, None otherwise + """ + raise NotImplementedError() + class DatabaseTypePostgres(DatabaseTypeBase): Type = 'postgres' @classmethod @@ -99,6 +126,14 @@ class DatabaseTypePostgres(DatabaseTypeBase): self.password = password self.database = database self.status = self.StatusInactive + + #TODO: implement + def init_new_database(self): + pass + + #TODO: implement + def validate_database(self): + pass class DatabaseTypeMysql(DatabaseTypeBase): Type = 'mysql' @@ -113,6 +148,15 @@ class DatabaseTypeMysql(DatabaseTypeBase): self.password = password self.database = database self.status = self.StatusInactive + + #TODO: implement + def init_new_database(self): + pass + + #TODO: implement + def validate_database(self): + pass + class DatabaseTypeSqLite(DatabaseTypeBase): Type = 'sqlite' @@ -122,8 +166,26 @@ class DatabaseTypeSqLite(DatabaseTypeBase): def __init__(self, name='', host='', file='', database='fpdb'): self.name = name self.file = file - self.database = database self.status = self.StatusInactive + + def init_new_database(self): + # make shure all attrs are specified + if not self.file: + return 'no database file specified' + # create file if necessary (this will truncate file if it exists) + try: + open(self.file, 'w').close() + except IOError: + return 'can not write file' + + #TODO: init tables (...) + + + def validate_database(self): + pass + #TODO: check if tables (...) exist + + #TODO: how do we want to handle unsupported database types? # ..uncomment to remove unsupported database types @@ -135,6 +197,20 @@ class DatabaseTypeSqLite(DatabaseTypeBase): #except ImportError: del DatabaseManager.DatabaseTypes['sqlite'] #*************************************************************************************************************************** +#TODO: there is not title (on linux), wtf? +def DialogError(parent=None, msg=''): + dlg = gtk.MessageDialog( + parent=parent, + flags=gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT, + type=gtk.MESSAGE_ERROR, + buttons=gtk.BUTTONS_OK, + message_format=msg, + ) + dlg.run() + dlg.destroy() + return None + + #TODO: derrive from gtk.VBox? class WidgetDatabaseProperties(gtk.VBox): @@ -189,7 +265,7 @@ class WidgetDatabaseProperties(gtk.VBox): dlg.destroy() - + #TODO: bit ugly this thingy. try to find a better way to map database attrs to gtk widgets class FieldWidget(object): def __init__(self, text='', attrDatabase='', widget=None, attrGet=None, attrSet=None, defaultValue=None, canEdit=False, tooltip=''): """ @@ -243,16 +319,6 @@ class WidgetDatabaseProperties(gtk.VBox): canEdit=True, tooltip='Any name you like to name the database ' ), - self.FieldWidget( - text='Db:', - attrDatabase='database', - widget=gtk.Entry(), - defaultValue='', - attrGet='get_text', - attrSet='set_text', - canEdit=False, - tooltip='Name of the database to create' - ), self.FieldWidget( text='File:', attrDatabase='file', @@ -303,6 +369,16 @@ class WidgetDatabaseProperties(gtk.VBox): canEdit=False, tooltip='Password used to login to the host' ), + self.FieldWidget( + text='Db:', + attrDatabase='database', + widget=gtk.Entry(), + defaultValue='', + attrGet='get_text', + attrSet='set_text', + canEdit=False, + tooltip='Name of the database' + ), ) # setup database type combo @@ -403,13 +479,16 @@ class DialogDatabaseProperties(gtk.Dialog): #TODO: derrive from gtk.VBox? # ..is there a way to derrive from gtk.Widget or similar? this would make parentWidget kw obsolete class WidgetDatabaseManager(gtk.VBox): + """ + """ + def __init__(self, databaseManager, parentWidget=None): gtk.VBox.__init__(self) self.parentWidget = parentWidget self.databaseManager = databaseManager - self.databaseManager.connect('database-activated', self.on_database_activated) - self.databaseManager.connect('database-deactivated', self.on_database_deactivated) + self.databaseManager.connect('database-activated', self.on_database_manager_database_activated) + self.databaseManager.connect('database-deactivated', self.on_database_manager_database_deactivated) self.databaseStatusNames = { DatabaseTypeBase.StatusActive: 'Active', DatabaseTypeBase.StatusInactive: 'Inactive', @@ -504,7 +583,7 @@ class WidgetDatabaseManager(gtk.VBox): model.set_value(it, self.treeDatabaseColumns['_id'], self.databaseManager.database_id(database)) - def on_database_activated(self, databaseManager, idDatabase): + def on_database_manager_database_activated(self, databaseManager, idDatabase): database = self.databaseManager.database_from_id(idDatabase) model = self.treeDatabases.get_model() for row in iter(model): @@ -515,7 +594,7 @@ class WidgetDatabaseManager(gtk.VBox): raise ValueError('database not found') - def on_database_deactivated(self, databaseManager, idDatabase): + def on_database_manager_database_deactivated(self, databaseManager, idDatabase): database = self.databaseManager.database_from_id(idDatabase) model = self.treeDatabases.get_model() for row in iter(model): @@ -539,46 +618,80 @@ class WidgetDatabaseManager(gtk.VBox): #TODO: for some reason i have to click OK/Cancel twice to close the dialog def on_button_database_new_clicked(self, button): - databaseType = self.databaseManager.get_default_database_type() - if databaseType is None: - raise ValueError('no defult database type set') - dlg = DialogDatabaseProperties( - self.databaseManager, - databaseType(), - parent=self.parentWidget, - mode=WidgetDatabaseProperties.ModeNew, - title='[New database] - database properties' - ) - if dlg.run() == gtk.RESPONSE_REJECT: - pass - if dlg.run() == gtk.RESPONSE_ACCEPT: - database = dlg.get_widget_database_properties().get_database() - #TODO: sanity checks + init databse if necessary - self.databaseManager.add_database(database) - self.treeDatabases.get_model().append( (database.name, 'foo', database.Type, self.databaseManager.database_id(database)) ) - dlg.destroy() - - - def on_button_database_add_clicked(self, button): - databaseType = self.databaseManager.get_default_database_type() - if databaseType is None: - raise ValueError('no defult database type set') - dlg = DialogDatabaseProperties( - self.databaseManager, - databaseType(), - parent=self.parentWidget, - mode=WidgetDatabaseProperties.ModeAdd, - title='[Add database] - database properties' - ) - if dlg.run() == gtk.RESPONSE_REJECT: - pass - if dlg.run() == gtk.RESPONSE_ACCEPT: - database = dlg.get_widget_database_properties().get_database() - #TODO: sanity checks + databaseKlass = self.databaseManager.get_default_database_type() + if databaseKlass is None: + raise ValueError('no default database type set') + database = databaseKlass() + + while True: + dlg = DialogDatabaseProperties( + self.databaseManager, + database, + parent=self.parentWidget, + mode=WidgetDatabaseProperties.ModeNew, + title='New database' + ) + response = dlg.run() + if response == gtk.RESPONSE_ACCEPT: + database = dlg.get_widget_database_properties().get_database() + #TODO: initing may or may not take a while. how to handle? + error = database.init_new_database() + if error: + DialogError(parent=dlg, msg=error) + dlg.destroy() + continue + else: + database = None + dlg.destroy() + break + + + if database is None: + return + + self.databaseManager.add_database(database) + model = self.treeDatabases.get_model() + it = model.append() + model.set_value(it, self.treeDatabaseColumns['name'], database.name) + model.set_value(it, self.treeDatabaseColumns['status'], self.databaseStatusNames[database.status] ) + model.set_value(it, self.treeDatabaseColumns['type'], database.display_name() ) + model.set_value(it, self.treeDatabaseColumns['_id'], self.databaseManager.database_id(database)) + + + def on_button_database_add_clicked(self, button): + databaseKlass = self.databaseManager.get_default_database_type() + if databaseKlass is None: + raise ValueError('no defult database type set') + database = databaseKlass() + + while True: + dlg = DialogDatabaseProperties( + self.databaseManager, + database, + parent=self.parentWidget, + mode=WidgetDatabaseProperties.ModeAdd, + title='Add database' + ) + response = dlg.run() + if response == gtk.RESPONSE_ACCEPT: + database = dlg.get_widget_database_properties().get_database() + #TODO: validating may or may not take a while. how to handle? + error = database.validate_database() + if error: + DialogError(parent=self.parentWidget, msg=error) + dlg.destroy() + continue + else: + database = None + dlg.destroy() + break + + if database is None: + return + self.databaseManager.add_database(database) model = self.treeDatabases.get_model() it = model.append() - print database.name model.set_value(it, self.treeDatabaseColumns['name'], database.name) model.set_value(it, self.treeDatabaseColumns['status'], self.databaseStatusNames[database.status] ) model.set_value(it, self.treeDatabaseColumns['type'], database.display_name() ) @@ -598,11 +711,12 @@ class WidgetDatabaseManager(gtk.VBox): database, parent=self.parentWidget, mode=WidgetDatabaseProperties.ModeEdit, - title='[Edit database] - database properties' + title='Edit database' ) - if dlg.run() == gtk.RESPONSE_REJECT: + response = dlg.run() + if response == gtk.RESPONSE_REJECT: pass - if dlg.run() == gtk.RESPONSE_ACCEPT: + elif response == gtk.RESPONSE_ACCEPT: database = dlg.get_database() selection = self.treeDatabases.get_selection() if selection is not None: @@ -634,7 +748,7 @@ class WidgetDatabaseManager(gtk.VBox): class DialogDatabaseManager(gtk.Dialog): def __init__(self, databaseManager, parent=None): gtk.Dialog.__init__(self, - title="My dialog", + title="Databases", parent=parent, flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, buttons=( From 6fcf81e56645505cfda348ddf3fc44dc529bb54f Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Sun, 1 Nov 2009 09:51:00 +0100 Subject: [PATCH 08/54] bugfix: InterProcessLock.locked() was broken cause InterProcessLock.aquire() no longer raises SingleInstanceError - fixed InterProcessLock.locked() - fixed doctests notes: - doctests run ok on linux with InterProcessLockFcntl and InterprocessLockSocket - doctests fail on linux/wine with InterprocessLockWin32 when trying to aquire the lock held by the process created on the fly. just a guess ..maybe the mutex is not released automatically when terminating the process. does native win32 guarantee this? --- pyfpdb/interlocks.py | 37 +++++++++++++------------------------ 1 file changed, 13 insertions(+), 24 deletions(-) diff --git a/pyfpdb/interlocks.py b/pyfpdb/interlocks.py index b19ff43b..366edd68 100755 --- a/pyfpdb/interlocks.py +++ b/pyfpdb/interlocks.py @@ -60,14 +60,10 @@ class InterProcessLockBase: self._has_lock = False def locked(self): - if self._has_lock: - return True - try: - self.acquire() + if self.acquire(): self.release() return False - except SingleInstanceError: - return True + return True LOCK_FILE_DIRECTORY = '/tmp' @@ -162,38 +158,33 @@ def test_construct(): >>> lock1 = InterProcessLock(name=test_name) >>> lock1.acquire() + True >>> lock2 = InterProcessLock(name=test_name) >>> lock3 = InterProcessLock(name=test_name) # Since lock1 is locked, other attempts to acquire it fail. >>> lock2.acquire() - Traceback (most recent call last): - ... - SingleInstanceError: Could not acquire exclusive lock on /tmp/test.lck + False >>> lock3.acquire() - Traceback (most recent call last): - ... - SingleInstanceError: Could not acquire exclusive lock on /tmp/test.lck + False # Release the lock and let lock2 have it. >>> lock1.release() >>> lock2.acquire() + True >>> lock3.acquire() - Traceback (most recent call last): - ... - SingleInstanceError: Could not acquire exclusive lock on /tmp/test.lck + False # Release it and give it back to lock1 >>> lock2.release() >>> lock1.acquire() + True >>> lock2.acquire() - Traceback (most recent call last): - ... - SingleInstanceError: Could not acquire exclusive lock on /tmp/test.lck + False # Test lock status >>> lock2.locked() @@ -237,15 +228,14 @@ def test_construct(): >>> pid = execute('import interlocks;a=interlocks.InterProcessLock(name=\\''+test_name+ '\\');a.acquire();') >>> lock1.acquire() - Traceback (most recent call last): - ... - SingleInstanceError: Could not acquire exclusive lock on /tmp/test.lck + False >>> os_independent_kill(pid) >>> time.sleep(1) >>> lock1.acquire() + True >>> lock1.release() # Testing wait @@ -253,13 +243,12 @@ def test_construct(): >>> pid = execute('import interlocks;a=interlocks.InterProcessLock(name=\\''+test_name+ '\\');a.acquire();') >>> lock1.acquire() - Traceback (most recent call last): - ... - SingleInstanceError: Could not acquire exclusive lock on /tmp/test.lck + False >>> os_independent_kill(pid) >>> lock1.acquire(True) + True >>> lock1.release() """ From f5d2f5a2dca3f18ef6fddb3a00d9383ebac5b521 Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Sun, 1 Nov 2009 09:58:14 +0100 Subject: [PATCH 09/54] fix: according to doctests os_independend_kill() is supposed to return None --- pyfpdb/interlocks.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyfpdb/interlocks.py b/pyfpdb/interlocks.py index 366edd68..4e427e7d 100755 --- a/pyfpdb/interlocks.py +++ b/pyfpdb/interlocks.py @@ -215,7 +215,7 @@ def test_construct(): ... import win32con ... import pywintypes ... handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE , pywintypes.FALSE, pid) - ... return (0 != win32api.TerminateProcess(handle, 0)) + ... #return (0 != win32api.TerminateProcess(handle, 0)) # Test to acquire the lock in another process. >>> def execute(cmd): From 0225987826e441a57479015fd7aa41698658ae15 Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Sun, 1 Nov 2009 20:07:41 +0100 Subject: [PATCH 10/54] added basic support to add databases present in *.xml to our manager notes: - i dont do too much error checking on input, guess this should be done in Configuration.py --- pyfpdb/DatabaseManager.py | 53 ++++++++++++++++++++++++++++++++------- 1 file changed, 44 insertions(+), 9 deletions(-) diff --git a/pyfpdb/DatabaseManager.py b/pyfpdb/DatabaseManager.py index 6bb2e8d4..7164a6e0 100644 --- a/pyfpdb/DatabaseManager.py +++ b/pyfpdb/DatabaseManager.py @@ -2,6 +2,7 @@ @todo: (gtk) how to validate user input in gtk.Dialog? as soon as the user clicks ok the dialog is dead. we use a while loop as workaround. not nice @todo: (fpdb) we need the application name 'fpdb' from somewhere to put it in dialog titles +@todo: (fpdb) config object should be initialized globally and accessible from all modules via Configuration.py @todo: (all dialogs) save/restore size and pos @@ -26,13 +27,47 @@ class DatabaseManager(gobject.GObject): @classmethod def from_fpdb(klass, data, defaultDatabaseType=None): - #TODO: parse whatever data is - #TODO: sort out unsupported databases passed by user and log - databases = ( - DatabaseTypeSqLite(name='myDb'), - DatabaseTypeSqLite(name='myDb2'), - - ) + + #NOTE: if no databases are present in config fpdb fails with + # Traceback (most recent call last): + # File "/home/me2/Scr/Repos/fpdb-mme/pyfpdb/DatabaseManager.py", line 783, in + # databaseManager = DatabaseManager.from_fpdb('', defaultDatabaseType=DatabaseTypeSqLite) + # File "/home/me2/Scr/Repos/fpdb-mme/pyfpdb/DatabaseManager.py", line 36, in from_fpdb + # config = Configuration.Config(file=options.config, dbname=options.dbname) + # File "/home/me2/Scr/Repos/fpdb-mme/pyfpdb/Configuration.py", line 436, in __init__ + # db = self.get_db_parameters() + # File "/home/me2/Scr/Repos/fpdb-mme/pyfpdb/Configuration.py", line 583, in get_db_parameters + # name = self.db_selected + # AttributeError: Config instance has no attribute 'db_selected' + import sys + import Options + import Configuration + #NOTE: fpdb should perform this globally + (options, sys.argv) = Options.fpdb_options() + config = Configuration.Config(file=options.config, dbname=options.dbname) + #TODO: handle no database present + defaultDatabaseName = config.get_db_parameters().get('db-databaseName', None) + #TODO: fpdb stores databases in no particular order. this has to be fixed somehow + databases = [] + for name, fpdbDatabase in config.supported_databases.items(): + databaseKlass = klass.DatabaseTypes.get(fpdbDatabase.db_type, None) + #NOTE: Config does not seem to validate user input, so anything may end up here + if databaseKlass is None: + raise ValueError('Unknown databasetype: %s' % fpdbDatabase.db_type) + + database = databaseKlass() + if database.Type == 'sqlite': + database.name = fpdbDatabase.db_name + database.file = fpdbDatabase.db_server + else: + database.name = fpdbDatabase.db_name + database.host = fpdbDatabase.db_server + #NOTE: fpdbDatabase.db_ip is no is a string + database.port = int(fpdbDatabase.db_ip) + database.user = fpdbDatabase.db_user + database.password = fpdbDatabase.db_pass + databases.append(database) + return klass(databases=databases, defaultDatabaseType=defaultDatabaseType) def to_fpdb(self): @@ -114,7 +149,7 @@ class DatabaseTypeBase(object): raise NotImplementedError() class DatabaseTypePostgres(DatabaseTypeBase): - Type = 'postgres' + Type = 'postgresql' @classmethod def display_name(klass): return 'Postgres' @@ -197,7 +232,7 @@ class DatabaseTypeSqLite(DatabaseTypeBase): #except ImportError: del DatabaseManager.DatabaseTypes['sqlite'] #*************************************************************************************************************************** -#TODO: there is not title (on linux), wtf? +#TODO: there is no title (on linux), wtf? def DialogError(parent=None, msg=''): dlg = gtk.MessageDialog( parent=parent, From 62ee67c07178ad7fdb0a4e6c6811e4d22292036f Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Mon, 2 Nov 2009 08:30:24 +0100 Subject: [PATCH 11/54] under certain circumstances attribute Config.db_selected could end up being undefined. this could cause later code relying on it failing in strange ways. --- pyfpdb/Configuration.py | 1 + 1 file changed, 1 insertion(+) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 5dba6aac..10cd72b0 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -371,6 +371,7 @@ class Config: self.aux_windows = {} self.hhcs = {} self.popup_windows = {} + self.db_selected = None # database the user would like to use # s_sites = doc.getElementsByTagName("supported_sites") for site_node in doc.getElementsByTagName("site"): From 01b56919ca5d11f6767df66c676ff72eb524e136 Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Mon, 2 Nov 2009 08:40:34 +0100 Subject: [PATCH 12/54] we take all tags from xml instead of taking all tags contained in added a note on this --- pyfpdb/Configuration.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 10cd72b0..85aa392b 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -388,6 +388,8 @@ class Config: # 1) command line option # or 2) selected="True" in config element # or 3) just choose the first we come across + #TODO: do we want to take all tags or all tags contained in + # ..this may break stuff for some users. so leave it unchanged for now untill there is a decission for db_node in doc.getElementsByTagName("database"): try: db = Database(node = db_node) From d9a120a2c62e5b3c9c01aff88bc636b6f43e1e1c Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Mon, 2 Nov 2009 08:48:07 +0100 Subject: [PATCH 13/54] removed superfluous try ..except clause. Database.__init__() was not doing any sanity checks, so the try ..except clause was only covering exceptions we are actually interested in --- pyfpdb/Configuration.py | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 85aa392b..58a249ff 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -391,20 +391,17 @@ class Config: #TODO: do we want to take all tags or all tags contained in # ..this may break stuff for some users. so leave it unchanged for now untill there is a decission for db_node in doc.getElementsByTagName("database"): - try: - db = Database(node = db_node) - except: - raise FpdbError("Unable to create database object") - else: - if db.db_name in self.supported_databases: - raise FpdbError("Database names must be unique") - # If there is only one Database node, or none are marked - # default, use first - if not self.supported_databases: - self.db_selected = db.db_name - self.supported_databases[db.db_name] = db - if db.db_selected: - self.db_selected = db.db_name + db = Database(node=db_node) + if db.db_name in self.supported_databases: + raise FpdbError("Database names must be unique") + # If there is only one Database node, or none are marked + # default, use first + # default, use first + if not self.supported_databases: + self.db_selected = db.db_name + self.supported_databases[db.db_name] = db + if db.db_selected: + self.db_selected = db.db_name if dbname and dbname in self.supported_databases: self.db_selected = dbname From d59f1eb72096c16655652acc374437cdb04b5319 Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Mon, 2 Nov 2009 08:52:46 +0100 Subject: [PATCH 14/54] added a comment what Config.supported_databases holds for readability --- pyfpdb/Configuration.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 58a249ff..265a5fa8 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -367,7 +367,7 @@ class Config: self.file = file self.supported_sites = {} self.supported_games = {} - self.supported_databases = {} + self.supported_databases = {} # databaseName --> Database instance self.aux_windows = {} self.hhcs = {} self.popup_windows = {} From 75b8c4943aaa0789bd26fc2801f8135ceff80d34 Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Mon, 2 Nov 2009 09:09:23 +0100 Subject: [PATCH 15/54] rewrote fix_tf() helper function to string_to_bool(). this represents better is what it actually does. comments stated that the function was some kind of fix for xml.dom, but XML is unaware of python types by intention ;-) --- pyfpdb/Configuration.py | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 265a5fa8..71d78f44 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -45,13 +45,15 @@ except ConfigParser.NoSectionError: # debian package path log = logging.getLogger("config") log.debug("config logger initialised") -def fix_tf(x, default = True): -# The xml parser doesn't translate "True" to True. Therefore, we never get -# True or False from the parser only "True" or "False". So translate the -# string to the python boolean representation. - if x == "1" or x == 1 or string.lower(x) == "true" or string.lower(x) == "t": +def string_to_bool(string, default=True): + """converts a string representation of a boolean value to boolean True or False + @param string: (str) the string to convert + @param default: value to return if the string can not be converted to a boolean value + """ + string = string.lower() + if string in ('1', 'true', 't'): return True - if x == "0" or x == 0 or string.lower(x) == "false" or string.lower(x) == "f": + elif string in ('0', 'false', 'f'): return False return default @@ -106,7 +108,7 @@ class Site: self.font = node.getAttribute("font") self.font_size = node.getAttribute("font_size") self.use_frames = node.getAttribute("use_frames") - self.enabled = fix_tf(node.getAttribute("enabled"), default = True) + self.enabled = string_to_bool(node.getAttribute("enabled"), default = True) self.xpad = node.getAttribute("xpad") self.ypad = node.getAttribute("ypad") self.layout = {} @@ -213,7 +215,7 @@ class Database: self.db_user = node.getAttribute("db_user") self.db_type = node.getAttribute("db_type") self.db_pass = node.getAttribute("db_pass") - self.db_selected = fix_tf(node.getAttribute("default"),"False") + self.db_selected = string_to_bool(node.getAttribute("default"),"False") log.debug("Database db_name:'%(name)s' db_server:'%(server)s' db_ip:'%(ip)s' db_user:'%(user)s' db_type:'%(type)s' db_pass (not logged) selected:'%(sel)s'" \ % { 'name':self.db_name, 'server':self.db_server, 'ip':self.db_ip, 'user':self.db_user, 'type':self.db_type, 'sel':self.db_selected} ) @@ -277,8 +279,8 @@ class Import: self.interval = node.getAttribute("interval") self.callFpdbHud = node.getAttribute("callFpdbHud") self.hhArchiveBase = node.getAttribute("hhArchiveBase") - self.saveActions = fix_tf(node.getAttribute("saveActions"), True) - self.fastStoreHudCache = fix_tf(node.getAttribute("fastStoreHudCache"), False) + self.saveActions = string_to_bool(node.getAttribute("saveActions"), True) + self.fastStoreHudCache = string_to_bool(node.getAttribute("fastStoreHudCache"), False) def __str__(self): return " interval = %s\n callFpdbHud = %s\n hhArchiveBase = %s\n saveActions = %s\n fastStoreHudCache = %s\n" \ @@ -289,14 +291,14 @@ class HudUI: self.node = node self.label = node.getAttribute('label') # - self.aggregate_ring = fix_tf(node.getAttribute('aggregate_ring_game_stats')) - self.aggregate_tour = fix_tf(node.getAttribute('aggregate_tourney_stats')) + self.aggregate_ring = string_to_bool(node.getAttribute('aggregate_ring_game_stats')) + self.aggregate_tour = string_to_bool(node.getAttribute('aggregate_tourney_stats')) self.hud_style = node.getAttribute('stat_aggregation_range') self.hud_days = node.getAttribute('aggregation_days') self.agg_bb_mult = node.getAttribute('aggregation_level_multiplier') # - self.h_aggregate_ring = fix_tf(node.getAttribute('aggregate_hero_ring_game_stats')) - self.h_aggregate_tour = fix_tf(node.getAttribute('aggregate_hero_tourney_stats')) + self.h_aggregate_ring = string_to_bool(node.getAttribute('aggregate_hero_ring_game_stats')) + self.h_aggregate_tour = string_to_bool(node.getAttribute('aggregate_hero_tourney_stats')) self.h_hud_style = node.getAttribute('hero_stat_aggregation_range') self.h_hud_days = node.getAttribute('hero_aggregation_days') self.h_agg_bb_mult = node.getAttribute('hero_aggregation_level_multiplier') From 10343c0ef43460db1d3674db972292e1218e89a2 Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Mon, 2 Nov 2009 09:14:57 +0100 Subject: [PATCH 16/54] fixed Database.db_selected attribute. it was always be boolean True if the attribute was not set in the tag + it is more readable using keyword arguments explicitely --- pyfpdb/Configuration.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 71d78f44..43361f97 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -108,7 +108,7 @@ class Site: self.font = node.getAttribute("font") self.font_size = node.getAttribute("font_size") self.use_frames = node.getAttribute("use_frames") - self.enabled = string_to_bool(node.getAttribute("enabled"), default = True) + self.enabled = string_to_bool(node.getAttribute("enabled"), default=True) self.xpad = node.getAttribute("xpad") self.ypad = node.getAttribute("ypad") self.layout = {} @@ -215,7 +215,7 @@ class Database: self.db_user = node.getAttribute("db_user") self.db_type = node.getAttribute("db_type") self.db_pass = node.getAttribute("db_pass") - self.db_selected = string_to_bool(node.getAttribute("default"),"False") + self.db_selected = string_to_bool(node.getAttribute("default"), defaukt=False) log.debug("Database db_name:'%(name)s' db_server:'%(server)s' db_ip:'%(ip)s' db_user:'%(user)s' db_type:'%(type)s' db_pass (not logged) selected:'%(sel)s'" \ % { 'name':self.db_name, 'server':self.db_server, 'ip':self.db_ip, 'user':self.db_user, 'type':self.db_type, 'sel':self.db_selected} ) @@ -279,8 +279,8 @@ class Import: self.interval = node.getAttribute("interval") self.callFpdbHud = node.getAttribute("callFpdbHud") self.hhArchiveBase = node.getAttribute("hhArchiveBase") - self.saveActions = string_to_bool(node.getAttribute("saveActions"), True) - self.fastStoreHudCache = string_to_bool(node.getAttribute("fastStoreHudCache"), False) + self.saveActions = string_to_bool(node.getAttribute("saveActions"), default=True) + self.fastStoreHudCache = string_to_bool(node.getAttribute("fastStoreHudCache"), default=False) def __str__(self): return " interval = %s\n callFpdbHud = %s\n hhArchiveBase = %s\n saveActions = %s\n fastStoreHudCache = %s\n" \ From cb16dde3651432f00fe63f1261522b70a4087cd0 Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Mon, 2 Nov 2009 09:16:18 +0100 Subject: [PATCH 17/54] typo --- pyfpdb/Configuration.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 43361f97..1699614e 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -215,7 +215,7 @@ class Database: self.db_user = node.getAttribute("db_user") self.db_type = node.getAttribute("db_type") self.db_pass = node.getAttribute("db_pass") - self.db_selected = string_to_bool(node.getAttribute("default"), defaukt=False) + self.db_selected = string_to_bool(node.getAttribute("default"), default=False) log.debug("Database db_name:'%(name)s' db_server:'%(server)s' db_ip:'%(ip)s' db_user:'%(user)s' db_type:'%(type)s' db_pass (not logged) selected:'%(sel)s'" \ % { 'name':self.db_name, 'server':self.db_server, 'ip':self.db_ip, 'user':self.db_user, 'type':self.db_type, 'sel':self.db_selected} ) From 8f2a2c20ccab413501e338dacfbd04d69e2f4cc0 Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Mon, 2 Nov 2009 09:29:58 +0100 Subject: [PATCH 18/54] tried my best to write a clearer comment + simplified finding out of what the selected database is --- pyfpdb/Configuration.py | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 1699614e..e19c4c3a 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -384,27 +384,21 @@ class Config: for game_node in doc.getElementsByTagName("game"): game = Game(node = game_node) self.supported_games[game.game_name] = game - + + # parse databases defined by user in the section + # the user may select the actual database to use via commandline or by setting the selected="bool" + # attribute of the tag. if no database is explicitely selected, we use the first one we come across # s_dbs = doc.getElementsByTagName("supported_databases") - # select database from those defined in config by: - # 1) command line option - # or 2) selected="True" in config element - # or 3) just choose the first we come across #TODO: do we want to take all tags or all tags contained in # ..this may break stuff for some users. so leave it unchanged for now untill there is a decission for db_node in doc.getElementsByTagName("database"): db = Database(node=db_node) if db.db_name in self.supported_databases: raise FpdbError("Database names must be unique") - # If there is only one Database node, or none are marked - # default, use first - # default, use first - if not self.supported_databases: + if self.db_selected is None or db.db_selected: self.db_selected = db.db_name self.supported_databases[db.db_name] = db - if db.db_selected: - self.db_selected = db.db_name - + if dbname and dbname in self.supported_databases: self.db_selected = dbname From 3a7d159d52fefff0f340f4bf3a6fee78e907d170 Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Mon, 2 Nov 2009 09:38:27 +0100 Subject: [PATCH 19/54] sorry, whitespace was messed up, have to find a better way to convert --- pyfpdb/Configuration.py | 175 ++++++++++++++++++++-------------------- 1 file changed, 88 insertions(+), 87 deletions(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index e19c4c3a..8e55ee15 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -60,7 +60,7 @@ def string_to_bool(string, default=True): class Layout: def __init__(self, node): - self.max = int( node.getAttribute('max') ) + self.max = int( node.getAttribute('max') ) if node.hasAttribute('fav_seat'): self.fav_seat = int( node.getAttribute('fav_seat') ) self.width = int( node.getAttribute('width') ) self.height = int( node.getAttribute('height') ) @@ -98,20 +98,20 @@ class Site: self.table_finder = node.getAttribute("table_finder") self.screen_name = node.getAttribute("screen_name") self.site_path = normalizePath(node.getAttribute("site_path")) - self.HH_path = normalizePath(node.getAttribute("HH_path")) - self.decoder = node.getAttribute("decoder") + self.HH_path = normalizePath(node.getAttribute("HH_path")) + self.decoder = node.getAttribute("decoder") self.hudopacity = node.getAttribute("hudopacity") self.hudbgcolor = node.getAttribute("bgcolor") self.hudfgcolor = node.getAttribute("fgcolor") self.converter = node.getAttribute("converter") self.aux_window = node.getAttribute("aux_window") - self.font = node.getAttribute("font") + self.font = node.getAttribute("font") self.font_size = node.getAttribute("font_size") self.use_frames = node.getAttribute("use_frames") - self.enabled = string_to_bool(node.getAttribute("enabled"), default=True) - self.xpad = node.getAttribute("xpad") - self.ypad = node.getAttribute("ypad") - self.layout = {} + self.enabled = string_to_bool(node.getAttribute("enabled"), default=True) + self.xpad = node.getAttribute("xpad") + self.ypad = node.getAttribute("ypad") + self.layout = {} print self.site_name, self.HH_path @@ -120,10 +120,10 @@ class Site: self.layout[lo.max] = lo # Site defaults - if self.xpad == "": self.xpad = 1 + if self.xpad == "": self.xpad = 1 else: self.xpad = int(self.xpad) - if self.ypad == "": self.ypad = 0 + if self.ypad == "": self.ypad = 0 else: self.ypad = int(self.ypad) if self.font_size == "": self.font_size = 7 @@ -133,7 +133,7 @@ class Site: else: self.hudopacity = float(self.hudopacity) if self.use_frames == "": self.use_frames = False - if self.font == "": self.font = "Sans" + if self.font == "": self.font = "Sans" if self.hudbgcolor == "": self.hudbgcolor = "000000" if self.hudfgcolor == "": self.hudfgcolor = "FFFFFF" @@ -162,10 +162,10 @@ class Stat: class Game: def __init__(self, node): self.game_name = node.getAttribute("game_name") - self.rows = int( node.getAttribute("rows") ) - self.cols = int( node.getAttribute("cols") ) - self.xpad = node.getAttribute("xpad") - self.ypad = node.getAttribute("ypad") + self.rows = int( node.getAttribute("rows") ) + self.cols = int( node.getAttribute("cols") ) + self.xpad = node.getAttribute("xpad") + self.ypad = node.getAttribute("ypad") # Defaults if self.xpad == "": self.xpad = 1 @@ -179,15 +179,15 @@ class Game: aux_list[i] = aux_list[i].strip() self.aux = aux_list - self.stats = {} + self.stats = {} for stat_node in node.getElementsByTagName('stat'): stat = Stat() stat.stat_name = stat_node.getAttribute("stat_name") - stat.row = int( stat_node.getAttribute("row") ) - stat.col = int( stat_node.getAttribute("col") ) - stat.tip = stat_node.getAttribute("tip") - stat.click = stat_node.getAttribute("click") - stat.popup = stat_node.getAttribute("popup") + stat.row = int( stat_node.getAttribute("row") ) + stat.col = int( stat_node.getAttribute("col") ) + stat.tip = stat_node.getAttribute("tip") + stat.click = stat_node.getAttribute("click") + stat.popup = stat_node.getAttribute("popup") stat.hudprefix = stat_node.getAttribute("hudprefix") stat.hudsuffix = stat_node.getAttribute("hudsuffix") stat.hudcolor = stat_node.getAttribute("hudcolor") @@ -206,18 +206,18 @@ class Game: temp = temp + "%s" % self.stats[stat] return temp - + class Database: def __init__(self, node): self.db_name = node.getAttribute("db_name") self.db_server = node.getAttribute("db_server") - self.db_ip = node.getAttribute("db_ip") + self.db_ip = node.getAttribute("db_ip") self.db_user = node.getAttribute("db_user") self.db_type = node.getAttribute("db_type") self.db_pass = node.getAttribute("db_pass") self.db_selected = string_to_bool(node.getAttribute("default"), default=False) log.debug("Database db_name:'%(name)s' db_server:'%(server)s' db_ip:'%(ip)s' db_user:'%(user)s' db_type:'%(type)s' db_pass (not logged) selected:'%(sel)s'" \ - % { 'name':self.db_name, 'server':self.db_server, 'ip':self.db_ip, 'user':self.db_user, 'type':self.db_type, 'sel':self.db_selected} ) + % { 'name':self.db_name, 'server':self.db_server, 'ip':self.db_ip, 'user':self.db_user, 'type':self.db_type, 'sel':self.db_selected} ) def __str__(self): temp = 'Database = ' + self.db_name + '\n' @@ -253,7 +253,7 @@ class Aux_window: class HHC: def __init__(self, node): - self.site = node.getAttribute("site") + self.site = node.getAttribute("site") self.converter = node.getAttribute("converter") def __str__(self): @@ -263,7 +263,7 @@ class HHC: class Popup: def __init__(self, node): self.name = node.getAttribute("pu_name") - self.pu_stats = [] + self.pu_stats = [] for stat_node in node.getElementsByTagName('pu_stat'): self.pu_stats.append(stat_node.getAttribute("pu_stat_name")) @@ -276,7 +276,7 @@ class Popup: class Import: def __init__(self, node): self.node = node - self.interval = node.getAttribute("interval") + self.interval = node.getAttribute("interval") self.callFpdbHud = node.getAttribute("callFpdbHud") self.hhArchiveBase = node.getAttribute("hhArchiveBase") self.saveActions = string_to_bool(node.getAttribute("saveActions"), default=True) @@ -284,7 +284,7 @@ class Import: def __str__(self): return " interval = %s\n callFpdbHud = %s\n hhArchiveBase = %s\n saveActions = %s\n fastStoreHudCache = %s\n" \ - % (self.interval, self.callFpdbHud, self.hhArchiveBase, self.saveActions, self.fastStoreHudCache) + % (self.interval, self.callFpdbHud, self.hhArchiveBase, self.saveActions, self.fastStoreHudCache) class HudUI: def __init__(self, node): @@ -293,15 +293,15 @@ class HudUI: # self.aggregate_ring = string_to_bool(node.getAttribute('aggregate_ring_game_stats')) self.aggregate_tour = string_to_bool(node.getAttribute('aggregate_tourney_stats')) - self.hud_style = node.getAttribute('stat_aggregation_range') - self.hud_days = node.getAttribute('aggregation_days') + self.hud_style = node.getAttribute('stat_aggregation_range') + self.hud_days = node.getAttribute('aggregation_days') self.agg_bb_mult = node.getAttribute('aggregation_level_multiplier') # self.h_aggregate_ring = string_to_bool(node.getAttribute('aggregate_hero_ring_game_stats')) self.h_aggregate_tour = string_to_bool(node.getAttribute('aggregate_hero_tourney_stats')) self.h_hud_style = node.getAttribute('hero_stat_aggregation_range') - self.h_hud_days = node.getAttribute('hero_aggregation_days') - self.h_agg_bb_mult = node.getAttribute('hero_aggregation_level_multiplier') + self.h_hud_days = node.getAttribute('hero_aggregation_days') + self.h_agg_bb_mult = node.getAttribute('hero_aggregation_level_multiplier') def __str__(self): @@ -311,7 +311,7 @@ class HudUI: class Tv: def __init__(self, node): self.combinedStealFold = node.getAttribute("combinedStealFold") - self.combined2B3B = node.getAttribute("combined2B3B") + self.combined2B3B = node.getAttribute("combined2B3B") self.combinedPostflop = node.getAttribute("combinedPostflop") def __str__(self): @@ -390,7 +390,7 @@ class Config: # attribute of the tag. if no database is explicitely selected, we use the first one we come across # s_dbs = doc.getElementsByTagName("supported_databases") #TODO: do we want to take all tags or all tags contained in - # ..this may break stuff for some users. so leave it unchanged for now untill there is a decission + # ..this may break stuff for some users. so leave it unchanged for now untill there is a decission for db_node in doc.getElementsByTagName("database"): db = Database(node=db_node) if db.db_name in self.supported_databases: @@ -402,12 +402,13 @@ class Config: if dbname and dbname in self.supported_databases: self.db_selected = dbname -# s_dbs = doc.getElementsByTagName("mucked_windows") + +# s_dbs = doc.getElementsByTagName("mucked_windows") for aw_node in doc.getElementsByTagName("aw"): aw = Aux_window(node = aw_node) self.aux_windows[aw.name] = aw -# s_dbs = doc.getElementsByTagName("mucked_windows") +# s_dbs = doc.getElementsByTagName("mucked_windows") for hhc_node in doc.getElementsByTagName("hhc"): hhc = HHC(node = hhc_node) self.hhcs[hhc.site] = hhc @@ -437,8 +438,8 @@ class Config: else: df_parms = self.read_default_conf(df_file) self.set_db_parameters(db_name = 'fpdb', db_ip = df_parms['db-host'], - db_user = df_parms['db-user'], - db_pass = df_parms['db-password']) + db_user = df_parms['db-user'], + db_pass = df_parms['db-password']) self.save(file=os.path.join(self.default_config_path, "HUD_config.xml")) print "" @@ -449,7 +450,7 @@ class Config: def find_config(self): """Looks in cwd and in self.default_config_path for a config file.""" if os.path.exists('HUD_config.xml'): # there is a HUD_config in the cwd - file = 'HUD_config.xml' # so we use it + file = 'HUD_config.xml' # so we use it else: # no HUD_config in the cwd, look where it should be in the first place config_path = os.path.join(self.default_config_path, 'HUD_config.xml') if os.path.exists(config_path): @@ -492,7 +493,7 @@ class Config: def find_example_config(self): if os.path.exists('HUD_config.xml.example'): # there is a HUD_config in the cwd - file = 'HUD_config.xml' # so we use it + file = 'HUD_config.xml' # so we use it try: shutil.copyfile(file+'.example', file) except: @@ -606,16 +607,16 @@ class Config: return db def set_db_parameters(self, db_name = 'fpdb', db_ip = None, db_user = None, - db_pass = None, db_server = None, db_type = None): + db_pass = None, db_server = None, db_type = None): db_node = self.get_db_node(db_name) if db_node != None: - if db_ip != None: db_node.setAttribute("db_ip", db_ip) + if db_ip != None: db_node.setAttribute("db_ip", db_ip) if db_user != None: db_node.setAttribute("db_user", db_user) if db_pass != None: db_node.setAttribute("db_pass", db_pass) if db_server != None: db_node.setAttribute("db_server", db_server) if db_type != None: db_node.setAttribute("db_type", db_type) if self.supported_databases.has_key(db_name): - if db_ip != None: self.supported_databases[db_name].dp_ip = db_ip + if db_ip != None: self.supported_databases[db_name].dp_ip = db_ip if db_user != None: self.supported_databases[db_name].dp_user = db_user if db_pass != None: self.supported_databases[db_name].dp_pass = db_pass if db_server != None: self.supported_databases[db_name].dp_server = db_server @@ -634,8 +635,8 @@ class Config: try: tv['combinedStealFold'] = self.tv.combinedStealFold except: tv['combinedStealFold'] = True - try: tv['combined2B3B'] = self.tv.combined2B3B - except: tv['combined2B3B'] = True + try: tv['combined2B3B'] = self.tv.combined2B3B + except: tv['combined2B3B'] = True try: tv['combinedPostflop'] = self.tv.combinedPostflop except: tv['combinedPostflop'] = True @@ -648,7 +649,7 @@ class Config: default_text = 'FPDB Menu - Right click\nLeft-Drag to Move' try: hui['label'] = self.ui.label - if self.ui.label == '': # Empty menu label is a big no-no + if self.ui.label == '': # Empty menu label is a big no-no hui['label'] = default_text except: hui['label'] = default_text @@ -662,11 +663,11 @@ class Config: try: hui['hud_style'] = self.ui.hud_style except: hui['hud_style'] = 'A' - try: hui['hud_days'] = int(self.ui.hud_days) - except: hui['hud_days'] = 90 + try: hui['hud_days'] = int(self.ui.hud_days) + except: hui['hud_days'] = 90 - try: hui['agg_bb_mult'] = self.ui.agg_bb_mult - except: hui['agg_bb_mult'] = 1 + try: hui['agg_bb_mult'] = self.ui.agg_bb_mult + except: hui['agg_bb_mult'] = 1 # Hero specific @@ -676,11 +677,11 @@ class Config: try: hui['h_aggregate_tour'] = self.ui.h_aggregate_tour except: hui['h_aggregate_tour'] = True - try: hui['h_hud_style'] = self.ui.h_hud_style - except: hui['h_hud_style'] = 'S' + try: hui['h_hud_style'] = self.ui.h_hud_style + except: hui['h_hud_style'] = 'S' - try: hui['h_hud_days'] = int(self.ui.h_hud_days) - except: hui['h_hud_days'] = 30 + try: hui['h_hud_days'] = int(self.ui.h_hud_days) + except: hui['h_hud_days'] = 30 try: hui['h_agg_bb_mult'] = self.ui.h_agg_bb_mult except: hui['h_agg_bb_mult'] = 1 @@ -690,19 +691,19 @@ class Config: def get_import_parameters(self): imp = {} - try: imp['callFpdbHud'] = self.imp.callFpdbHud - except: imp['callFpdbHud'] = True + try: imp['callFpdbHud'] = self.imp.callFpdbHud + except: imp['callFpdbHud'] = True - try: imp['interval'] = self.imp.interval - except: imp['interval'] = 10 + try: imp['interval'] = self.imp.interval + except: imp['interval'] = 10 - try: imp['hhArchiveBase'] = self.imp.hhArchiveBase - except: imp['hhArchiveBase'] = "~/.fpdb/HandHistories/" + try: imp['hhArchiveBase'] = self.imp.hhArchiveBase + except: imp['hhArchiveBase'] = "~/.fpdb/HandHistories/" - try: imp['saveActions'] = self.imp.saveActions - except: imp['saveActions'] = True + try: imp['saveActions'] = self.imp.saveActions + except: imp['saveActions'] = True - try: imp['fastStoreHudCache'] = self.imp.fastStoreHudCache + try: imp['fastStoreHudCache'] = self.imp.fastStoreHudCache except: imp['fastStoreHudCache'] = True return imp @@ -758,8 +759,8 @@ class Config: locations = self.supported_sites[site].layout[max].location except: locations = ( ( 0, 0), (684, 61), (689, 239), (692, 346), - (586, 393), (421, 440), (267, 440), ( 0, 361), - ( 0, 280), (121, 280), ( 46, 30) ) + (586, 393), (421, 440), (267, 440), ( 0, 361), + ( 0, 280), (121, 280), ( 46, 30) ) return locations def get_aux_locations(self, aux = "mucked", max = "9"): @@ -768,8 +769,8 @@ class Config: locations = self.aux_windows[aux].layout[max].location except: locations = ( ( 0, 0), (684, 61), (689, 239), (692, 346), - (586, 393), (421, 440), (267, 440), ( 0, 361), - ( 0, 280), (121, 280), ( 46, 30) ) + (586, 393), (421, 440), (267, 440), ( 0, 361), + ( 0, 280), (121, 280), ( 46, 30) ) return locations def get_supported_sites(self, all = False): @@ -785,21 +786,21 @@ class Config: """Returns a dict of the site parameters for the specified site""" parms = {} parms["converter"] = self.supported_sites[site].converter - parms["decoder"] = self.supported_sites[site].decoder + parms["decoder"] = self.supported_sites[site].decoder parms["hudbgcolor"] = self.supported_sites[site].hudbgcolor parms["hudfgcolor"] = self.supported_sites[site].hudfgcolor parms["hudopacity"] = self.supported_sites[site].hudopacity parms["screen_name"] = self.supported_sites[site].screen_name parms["site_path"] = self.supported_sites[site].site_path parms["table_finder"] = self.supported_sites[site].table_finder - parms["HH_path"] = self.supported_sites[site].HH_path + parms["HH_path"] = self.supported_sites[site].HH_path parms["site_name"] = self.supported_sites[site].site_name parms["aux_window"] = self.supported_sites[site].aux_window - parms["font"] = self.supported_sites[site].font + parms["font"] = self.supported_sites[site].font parms["font_size"] = self.supported_sites[site].font_size - parms["enabled"] = self.supported_sites[site].enabled - parms["xpad"] = self.supported_sites[site].xpad - parms["ypad"] = self.supported_sites[site].ypad + parms["enabled"] = self.supported_sites[site].enabled + parms["xpad"] = self.supported_sites[site].xpad + parms["ypad"] = self.supported_sites[site].ypad return parms def set_site_parameters(self, site_name, converter = None, decoder = None, @@ -811,18 +812,18 @@ class Config: """Sets the specified site parameters for the specified site.""" site_node = self.get_site_node(site_name) if db_node != None: - if converter != None: site_node.setAttribute("converter", converter) + if converter != None: site_node.setAttribute("converter", converter) if decoder != None: site_node.setAttribute("decoder", decoder) - if hudbgcolor != None: site_node.setAttribute("hudbgcolor", hudbgcolor) - if hudfgcolor != None: site_node.setAttribute("hudfgcolor", hudfgcolor) - if hudopacity != None: site_node.setAttribute("hudopacity", hudopacity) + if hudbgcolor != None: site_node.setAttribute("hudbgcolor", hudbgcolor) + if hudfgcolor != None: site_node.setAttribute("hudfgcolor", hudfgcolor) + if hudopacity != None: site_node.setAttribute("hudopacity", hudopacity) if screen_name != None: site_node.setAttribute("screen_name", screen_name) - if site_path != None: site_node.setAttribute("site_path", site_path) + if site_path != None: site_node.setAttribute("site_path", site_path) if table_finder != None: site_node.setAttribute("table_finder", table_finder) if HH_path != None: site_node.setAttribute("HH_path", HH_path) if enabled != None: site_node.setAttribute("enabled", enabled) - if font != None: site_node.setAttribute("font", font) - if font_size != None: site_node.setAttribute("font_size", font_size) + if font != None: site_node.setAttribute("font", font) + if font_size != None: site_node.setAttribute("font_size", font_size) return def get_aux_windows(self): @@ -850,11 +851,11 @@ class Config: param = {} if self.supported_games.has_key(name): param['game_name'] = self.supported_games[name].game_name - param['rows'] = self.supported_games[name].rows - param['cols'] = self.supported_games[name].cols - param['xpad'] = self.supported_games[name].xpad - param['ypad'] = self.supported_games[name].ypad - param['aux'] = self.supported_games[name].aux + param['rows'] = self.supported_games[name].rows + param['cols'] = self.supported_games[name].cols + param['xpad'] = self.supported_games[name].xpad + param['ypad'] = self.supported_games[name].ypad + param['aux'] = self.supported_games[name].aux return param def get_supported_games(self): @@ -914,8 +915,8 @@ if __name__== "__main__": c.edit_layout("PokerStars", 6, locations=( (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6) )) c.save(file="testout.xml") - print "db = ", c.get_db_parameters() -# print "tv = ", c.get_tv_parameters() + print "db = ", c.get_db_parameters() +# print "tv = ", c.get_tv_parameters() # print "imp = ", c.get_import_parameters() print "paths = ", c.get_default_paths("PokerStars") print "colors = ", c.get_default_colors("PokerStars") From 612d6607a17b2167eea19808275f12e6110d2456 Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Mon, 2 Nov 2009 09:40:16 +0100 Subject: [PATCH 20/54] fix: FpdbError is not defined, use ValueError instead --- pyfpdb/Configuration.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 8e55ee15..94c445a9 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -394,7 +394,7 @@ class Config: for db_node in doc.getElementsByTagName("database"): db = Database(node=db_node) if db.db_name in self.supported_databases: - raise FpdbError("Database names must be unique") + raise ValueError("Database names must be unique") if self.db_selected is None or db.db_selected: self.db_selected = db.db_name self.supported_databases[db.db_name] = db From d3eeeef2e81dcc486d9c97aea061dc3ee3b4bfe9 Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Mon, 2 Nov 2009 09:45:53 +0100 Subject: [PATCH 21/54] fpdb can not handle the case where no database is defined in xml, so throw a ValueError for now --- pyfpdb/Configuration.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 94c445a9..d174e5da 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -401,7 +401,9 @@ class Config: if dbname and dbname in self.supported_databases: self.db_selected = dbname - + #NOTE: fpdb can not handle the case when no database is defined in xml, so we throw an exception for now + if self.db_selected is None: + raise ValueError('There must be at least one database defined') # s_dbs = doc.getElementsByTagName("mucked_windows") for aw_node in doc.getElementsByTagName("aw"): From fb76540df6df84d6a2e20e8c3bbff3436bbee639 Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Mon, 2 Nov 2009 09:54:16 +0100 Subject: [PATCH 22/54] added a TODO: if the user may passes '' (empty string) as database name via command line, his choice is ignored when we parse the xml we allow for ''. there has to be a decission if to allow '' or not --- pyfpdb/Configuration.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index d174e5da..f2371aa1 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -398,7 +398,8 @@ class Config: if self.db_selected is None or db.db_selected: self.db_selected = db.db_name self.supported_databases[db.db_name] = db - + #TODO: if the user may passes '' (empty string) as database name via command line, his choice is ignored + # when we parse the xml we allow for ''. there has to be a decission if to allow '' or not if dbname and dbname in self.supported_databases: self.db_selected = dbname #NOTE: fpdb can not handle the case when no database is defined in xml, so we throw an exception for now From 34bbc45cb8be83167e1a0fbc3f127bf26168fb33 Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Mon, 2 Nov 2009 09:55:08 +0100 Subject: [PATCH 23/54] whitespace --- pyfpdb/Configuration.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index f2371aa1..5405e84b 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -399,7 +399,7 @@ class Config: self.db_selected = db.db_name self.supported_databases[db.db_name] = db #TODO: if the user may passes '' (empty string) as database name via command line, his choice is ignored - # when we parse the xml we allow for ''. there has to be a decission if to allow '' or not + # ..when we parse the xml we allow for ''. there has to be a decission if to allow '' or not if dbname and dbname in self.supported_databases: self.db_selected = dbname #NOTE: fpdb can not handle the case when no database is defined in xml, so we throw an exception for now From 9e94f44fa7dbc79deb7c0e99961e6edccf0eb9db Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Mon, 2 Nov 2009 10:06:54 +0100 Subject: [PATCH 24/54] started defining some application wide consts. these consts (more to come if my approach is accepted) are used all over the fpdb and should always be taken from one place --- pyfpdb/Configuration.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 5405e84b..95d445b7 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -44,7 +44,22 @@ except ConfigParser.NoSectionError: # debian package path log = logging.getLogger("config") log.debug("config logger initialised") +######################################################################## +# application wide consts +APPLICATION_NAME_SHORT = 'fpdb' +APPLICATION_VERSION = 'xx.xx.xx' + +DATABASE_TYPE_POSTGRESQL = 'postgresql' +DATABASE_TYPE_SQLITE = 'sqlite' +DATABASE_TYPE_MYSQL = 'mysql' +DATABASE_TYPES = ( + DATABASE_TYPE_POSTGRESQL, + DATABASE_TYPE_SQLITE, + DATABASE_TYPE_MYSQL, + ) + +######################################################################## def string_to_bool(string, default=True): """converts a string representation of a boolean value to boolean True or False @param string: (str) the string to convert From a18091161a5920c84389af7635e3df247342fe2d Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Mon, 2 Nov 2009 10:29:10 +0100 Subject: [PATCH 25/54] added a note and some thoughts for review --- pyfpdb/Configuration.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 95d445b7..79958269 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -593,6 +593,13 @@ class Config: else: self.aux_windows[aux_name].layout[max].location[i] = ( locations[i][0], locations[i][1] ) + #NOTE: we got a nice Database class, so why map it again here? + # user input validation should be done when initializing the Database class. this allows to give appropriate feddback when something goes wrong + # try ..except is evil here. it swallows all kinds of errors. dont do this + # naming database types 2, 3, 4 on the fly is no good idea. i see this all over the code. better use some globally defined consts (see DATABASE_TYPE_*) + # i would like to drop this method entirely and replace it by get_selected_database() or better get_active_database(), returning one of our Database instances + # thus we can drop self.db_selected (holding database name) entirely and replace it with self._active_database = Database, avoiding to define the same + # thing multiple times def get_db_parameters(self): db = {} name = self.db_selected From 62c915928deadab5496bb44d8ccad7eaf7849ad4 Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Tue, 3 Nov 2009 10:50:13 +0100 Subject: [PATCH 26/54] - added a global const to config to point to "database" directory - adjusted fpdb_db.py to make use use of this const --- pyfpdb/Configuration.py | 4 ++++ pyfpdb/fpdb_db.py | 10 +++++----- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 79958269..060aecff 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -50,6 +50,10 @@ log.debug("config logger initialised") APPLICATION_NAME_SHORT = 'fpdb' APPLICATION_VERSION = 'xx.xx.xx' +DIR_SELF = os.path.dirname(os.path.abspath(__file__)) +#TODO: imo no good idea to place 'database' in parent dir +DIR_DATABASES = os.path.join(os.path.dirname(DIR_SELF), 'database') + DATABASE_TYPE_POSTGRESQL = 'postgresql' DATABASE_TYPE_SQLITE = 'sqlite' DATABASE_TYPE_MYSQL = 'mysql' diff --git a/pyfpdb/fpdb_db.py b/pyfpdb/fpdb_db.py index da0bbbe7..310c219b 100644 --- a/pyfpdb/fpdb_db.py +++ b/pyfpdb/fpdb_db.py @@ -33,12 +33,12 @@ except ImportError: import fpdb_simple import FpdbSQLQueries +import Configuration class fpdb_db: MYSQL_INNODB = 2 PGSQL = 3 SQLITE = 4 - sqlite_db_dir = ".." + os.sep + "database" def __init__(self): """Simple constructor, doesnt really do anything""" @@ -123,10 +123,10 @@ class fpdb_db: else: logging.warning("SQLite won't work well without 'sqlalchemy' installed.") - if not os.path.isdir(self.sqlite_db_dir): - print "Creating directory: '%s'" % (self.sqlite_db_dir) - os.mkdir(self.sqlite_db_dir) - self.db = sqlite3.connect( self.sqlite_db_dir + os.sep + database + if not os.path.isdir(Configuration.DIR_DATABASES): + print "Creating directory: '%s'" % (Configuration.DIR_DATABASES) + os.mkdir(Configuration.DIR_DATABASES) + self.db = sqlite3.connect( os.path.join(Configuration.DIR_DATABASES, database) , detect_types=sqlite3.PARSE_DECLTYPES ) sqlite3.register_converter("bool", lambda x: bool(int(x))) sqlite3.register_adapter(bool, lambda x: "1" if x else "0") From 50bafadcb12b7a9292dddacd9a082d2436756e52 Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Tue, 3 Nov 2009 15:17:48 +0100 Subject: [PATCH 27/54] we throw an exception now if the user supplies an unsupported database backend note: checked all refences. i think we can raise savely without breaking stuff. it is only used in Database.py on get_backend_name(), raising an exception anyways if the backend is unknown --- pyfpdb/Configuration.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 060aecff..33a998d3 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -229,7 +229,7 @@ class Game: class Database: def __init__(self, node): self.db_name = node.getAttribute("db_name") - self.db_server = node.getAttribute("db_server") + self.db_server = node.getAttribute("db_server").lower() self.db_ip = node.getAttribute("db_ip") self.db_user = node.getAttribute("db_user") self.db_type = node.getAttribute("db_type") @@ -626,13 +626,14 @@ class Config: try: db['db-type'] = self.supported_databases[name].db_type except: pass - if string.lower(self.supported_databases[name].db_server) == 'mysql': + if self.supported_databases[name].db_server== DATABASE_TYPE_MYSQL: db['db-backend'] = 2 - elif string.lower(self.supported_databases[name].db_server) == 'postgresql': + elif self.supported_databases[name].db_server== DATABASE_TYPE_POSTGRESQL: db['db-backend'] = 3 - elif string.lower(self.supported_databases[name].db_server) == 'sqlite': + elif self.supported_databases[name].db_server== DATABASE_TYPE_SQLITE: db['db-backend'] = 4 - else: db['db-backend'] = None # this is big trouble + else: + raise ValueError('Unsupported database backend: %s' % self.supported_databases[name].db_server) return db def set_db_parameters(self, db_name = 'fpdb', db_ip = None, db_user = None, From 944d48d7ef81a42b2ca2dc49f1d8ea95e2e8f2de Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Tue, 3 Nov 2009 15:35:20 +0100 Subject: [PATCH 28/54] refactored logging setup removed fallback to '/usr/share/python-fpdb/logging.conf' if 'logging.conf' could not be found in the current directory. 1. this looked redundant, 2. usually only root has write access to /usr/share/* ok or not? --- pyfpdb/Configuration.py | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 33a998d3..a9fa0d93 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -36,14 +36,6 @@ from xml.dom.minidom import Node import logging, logging.config import ConfigParser - -try: # local path - logging.config.fileConfig(os.path.join(sys.path[0],"logging.conf")) -except ConfigParser.NoSectionError: # debian package path - logging.config.fileConfig('/usr/share/python-fpdb/logging.conf') - -log = logging.getLogger("config") -log.debug("config logger initialised") ######################################################################## # application wide consts @@ -63,6 +55,10 @@ DATABASE_TYPES = ( DATABASE_TYPE_MYSQL, ) +# setup logging +logging.config.fileConfig(os.path.join(DIR_SELF,"logging.conf")) +log = logging.getLogger("config") + ######################################################################## def string_to_bool(string, default=True): """converts a string representation of a boolean value to boolean True or False From 92f98e9f5122c9d7259910ad426b0953b1c3e008 Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Tue, 3 Nov 2009 16:09:58 +0100 Subject: [PATCH 29/54] added an application wide exception handler --- pyfpdb/Configuration.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index a9fa0d93..1f47b61b 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -59,6 +59,14 @@ DATABASE_TYPES = ( logging.config.fileConfig(os.path.join(DIR_SELF,"logging.conf")) log = logging.getLogger("config") +# setup application wide exception handler +def excepthook(Type, value, tb): + p = traceback.format_exception(type, value, tb) + log.critical(p) + raise Type(value) + +sys.excepthook = excepthook + ######################################################################## def string_to_bool(string, default=True): """converts a string representation of a boolean value to boolean True or False @@ -140,7 +148,7 @@ class Site: if self.ypad == "": self.ypad = 0 else: self.ypad = int(self.ypad) - + if self.font_size == "": self.font_size = 7 else: self.font_size = int(self.font_size) From 9063d9749cdee8de409275dd5128d09e90f6ab8f Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Tue, 3 Nov 2009 19:18:51 +0100 Subject: [PATCH 30/54] removed all occurences of db_type/db-type --- pyfpdb/Configuration.py | 12 +- pyfpdb/Database.py | 3 +- pyfpdb/HUD_config.xml.example | 4 +- pyfpdb/SQL.py | 6095 ++++++++++++++++----------------- pyfpdb/fpdb.py | 2 +- 5 files changed, 3054 insertions(+), 3062 deletions(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 1f47b61b..01f1c74c 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -236,11 +236,10 @@ class Database: self.db_server = node.getAttribute("db_server").lower() self.db_ip = node.getAttribute("db_ip") self.db_user = node.getAttribute("db_user") - self.db_type = node.getAttribute("db_type") self.db_pass = node.getAttribute("db_pass") self.db_selected = string_to_bool(node.getAttribute("default"), default=False) - log.debug("Database db_name:'%(name)s' db_server:'%(server)s' db_ip:'%(ip)s' db_user:'%(user)s' db_type:'%(type)s' db_pass (not logged) selected:'%(sel)s'" \ - % { 'name':self.db_name, 'server':self.db_server, 'ip':self.db_ip, 'user':self.db_user, 'type':self.db_type, 'sel':self.db_selected} ) + log.debug("Database db_name:'%(name)s' db_server:'%(server)s' db_ip:'%(ip)s' db_user:'%(user)s' db_pass (not logged) selected:'%(sel)s'" \ + % { 'name':self.db_name, 'server':self.db_server, 'ip':self.db_ip, 'user':self.db_user, 'sel':self.db_selected} ) def __str__(self): temp = 'Database = ' + self.db_name + '\n' @@ -627,9 +626,6 @@ class Config: try: db['db-server'] = self.supported_databases[name].db_server except: pass - try: db['db-type'] = self.supported_databases[name].db_type - except: pass - if self.supported_databases[name].db_server== DATABASE_TYPE_MYSQL: db['db-backend'] = 2 elif self.supported_databases[name].db_server== DATABASE_TYPE_POSTGRESQL: @@ -641,20 +637,18 @@ class Config: return db def set_db_parameters(self, db_name = 'fpdb', db_ip = None, db_user = None, - db_pass = None, db_server = None, db_type = None): + db_pass = None, db_server = None): db_node = self.get_db_node(db_name) if db_node != None: if db_ip != None: db_node.setAttribute("db_ip", db_ip) if db_user != None: db_node.setAttribute("db_user", db_user) if db_pass != None: db_node.setAttribute("db_pass", db_pass) if db_server != None: db_node.setAttribute("db_server", db_server) - if db_type != None: db_node.setAttribute("db_type", db_type) if self.supported_databases.has_key(db_name): if db_ip != None: self.supported_databases[db_name].dp_ip = db_ip if db_user != None: self.supported_databases[db_name].dp_user = db_user if db_pass != None: self.supported_databases[db_name].dp_pass = db_pass if db_server != None: self.supported_databases[db_name].dp_server = db_server - if db_type != None: self.supported_databases[db_name].dp_type = db_type return def getDefaultSite(self): diff --git a/pyfpdb/Database.py b/pyfpdb/Database.py index 1533c05c..c9051c9c 100755 --- a/pyfpdb/Database.py +++ b/pyfpdb/Database.py @@ -205,7 +205,7 @@ class Database: # where possible avoid creating new SQL instance by using the global one passed in if sql is None: - self.sql = SQL.Sql(type = self.type, db_server = self.db_server) + self.sql = SQL.Sql(db_server = self.db_server) else: self.sql = sql @@ -249,7 +249,6 @@ class Database: db_params = c.get_db_parameters() self.import_options = c.get_import_parameters() - self.type = db_params['db-type'] self.backend = db_params['db-backend'] self.db_server = db_params['db-server'] self.database = db_params['db-databaseName'] diff --git a/pyfpdb/HUD_config.xml.example b/pyfpdb/HUD_config.xml.example index 34a8f16d..e8c8f626 100644 --- a/pyfpdb/HUD_config.xml.example +++ b/pyfpdb/HUD_config.xml.example @@ -570,8 +570,8 @@ Left-Drag to Move" - - + + diff --git a/pyfpdb/SQL.py b/pyfpdb/SQL.py index 3c25963f..82979e76 100644 --- a/pyfpdb/SQL.py +++ b/pyfpdb/SQL.py @@ -33,312 +33,295 @@ import re class Sql: - def __init__(self, game = 'holdem', type = 'fpdb', db_server = 'mysql'): + def __init__(self, game = 'holdem', db_server = 'mysql'): self.query = {} ###############################################################################3 # Support for the Free Poker DataBase = fpdb http://fpdb.sourceforge.net/ # - if type == 'fpdb': - ################################ - # List tables - ################################ - if db_server == 'mysql': - self.query['list_tables'] = """SHOW TABLES""" - elif db_server == 'postgresql': - self.query['list_tables'] = """SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'""" - elif db_server == 'sqlite': - self.query['list_tables'] = """SELECT name FROM sqlite_master - WHERE type='table' - ORDER BY name;""" + ################################ + # List tables + ################################ + if db_server == 'mysql': + self.query['list_tables'] = """SHOW TABLES""" + elif db_server == 'postgresql': + self.query['list_tables'] = """SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'""" + elif db_server == 'sqlite': + self.query['list_tables'] = """SELECT name FROM sqlite_master + WHERE type='table' + ORDER BY name;""" - ################################################################## - # Drop Tables - MySQL, PostgreSQL and SQLite all share same syntax - ################################################################## + ################################################################## + # Drop Tables - MySQL, PostgreSQL and SQLite all share same syntax + ################################################################## - self.query['drop_table'] = """DROP TABLE IF EXISTS """ + self.query['drop_table'] = """DROP TABLE IF EXISTS """ - ################################ - # Create Settings - ################################ - if db_server == 'mysql': - self.query['createSettingsTable'] = """CREATE TABLE Settings ( - version SMALLINT NOT NULL) - ENGINE=INNODB""" - elif db_server == 'postgresql': - self.query['createSettingsTable'] = """CREATE TABLE Settings (version SMALLINT NOT NULL)""" + ################################ + # Create Settings + ################################ + if db_server == 'mysql': + self.query['createSettingsTable'] = """CREATE TABLE Settings ( + version SMALLINT NOT NULL) + ENGINE=INNODB""" + elif db_server == 'postgresql': + self.query['createSettingsTable'] = """CREATE TABLE Settings (version SMALLINT NOT NULL)""" - elif db_server == 'sqlite': - self.query['createSettingsTable'] = """CREATE TABLE Settings - (version INTEGER NOT NULL) """ + elif db_server == 'sqlite': + self.query['createSettingsTable'] = """CREATE TABLE Settings + (version INTEGER NOT NULL) """ - ################################ - # Create Sites - ################################ + ################################ + # Create Sites + ################################ - if db_server == 'mysql': - self.query['createSitesTable'] = """CREATE TABLE Sites ( - id SMALLINT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), - name varchar(32) NOT NULL, - currency char(3) NOT NULL) - ENGINE=INNODB""" - elif db_server == 'postgresql': - self.query['createSitesTable'] = """CREATE TABLE Sites ( - id SERIAL, PRIMARY KEY (id), - name varchar(32), - currency char(3))""" - elif db_server == 'sqlite': - self.query['createSitesTable'] = """CREATE TABLE Sites ( + if db_server == 'mysql': + self.query['createSitesTable'] = """CREATE TABLE Sites ( + id SMALLINT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), + name varchar(32) NOT NULL, + currency char(3) NOT NULL) + ENGINE=INNODB""" + elif db_server == 'postgresql': + self.query['createSitesTable'] = """CREATE TABLE Sites ( + id SERIAL, PRIMARY KEY (id), + name varchar(32), + currency char(3))""" + elif db_server == 'sqlite': + self.query['createSitesTable'] = """CREATE TABLE Sites ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + currency TEXT NOT NULL)""" + + + ################################ + # Create Gametypes + ################################ + + if db_server == 'mysql': + self.query['createGametypesTable'] = """CREATE TABLE Gametypes ( + id SMALLINT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), + siteId SMALLINT UNSIGNED NOT NULL, FOREIGN KEY (siteId) REFERENCES Sites(id), + type char(4) NOT NULL, + base char(4) NOT NULL, + category varchar(9) NOT NULL, + limitType char(2) NOT NULL, + hiLo char(1) NOT NULL, + smallBlind int, + bigBlind int, + smallBet int NOT NULL, + bigBet int NOT NULL) + ENGINE=INNODB""" + elif db_server == 'postgresql': + self.query['createGametypesTable'] = """CREATE TABLE Gametypes ( + id SERIAL, PRIMARY KEY (id), + siteId INTEGER, FOREIGN KEY (siteId) REFERENCES Sites(id), + type char(4), + base char(4), + category varchar(9), + limitType char(2), + hiLo char(1), + smallBlind int, + bigBlind int, + smallBet int, + bigBet int)""" + elif db_server == 'sqlite': + self.query['createGametypesTable'] = """CREATE TABLE GameTypes ( + id INTEGER PRIMARY KEY, + siteId INTEGER, + type TEXT, + base TEXT, + category TEXT, + limitType TEXT, + hiLo TEXT, + smallBlind INTEGER, + bigBlind INTEGER, + smallBet INTEGER, + bigBet INTEGER, + FOREIGN KEY(siteId) REFERENCES Sites(id) ON DELETE CASCADE)""" + + + ################################ + # Create Players + ################################ + + if db_server == 'mysql': + self.query['createPlayersTable'] = """CREATE TABLE Players ( + id INT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), + name VARCHAR(32) CHARACTER SET utf8 NOT NULL, + siteId SMALLINT UNSIGNED NOT NULL, FOREIGN KEY (siteId) REFERENCES Sites(id), + comment text, + commentTs DATETIME) + ENGINE=INNODB""" + elif db_server == 'postgresql': + self.query['createPlayersTable'] = """CREATE TABLE Players ( + id SERIAL, PRIMARY KEY (id), + name VARCHAR(32), + siteId INTEGER, FOREIGN KEY (siteId) REFERENCES Sites(id), + comment text, + commentTs timestamp without time zone)""" + elif db_server == 'sqlite': + self.query['createPlayersTable'] = """CREATE TABLE Players ( + id INTEGER PRIMARY KEY, + name TEXT, + siteId INTEGER, + comment TEXT, + commentTs REAL, + FOREIGN KEY(siteId) REFERENCES Sites(id) ON DELETE CASCADE)""" + + + ################################ + # Create Autorates + ################################ + + if db_server == 'mysql': + self.query['createAutoratesTable'] = """CREATE TABLE Autorates ( + id BIGINT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), + playerId INT UNSIGNED NOT NULL, FOREIGN KEY (playerId) REFERENCES Players(id), + gametypeId SMALLINT UNSIGNED NOT NULL, FOREIGN KEY (gametypeId) REFERENCES Gametypes(id), + description varchar(50) NOT NULL, + shortDesc char(8) NOT NULL, + ratingTime DATETIME NOT NULL, + handCount int NOT NULL) + ENGINE=INNODB""" + elif db_server == 'postgresql': + self.query['createAutoratesTable'] = """CREATE TABLE Autorates ( + id BIGSERIAL, PRIMARY KEY (id), + playerId INT, FOREIGN KEY (playerId) REFERENCES Players(id), + gametypeId INT, FOREIGN KEY (gametypeId) REFERENCES Gametypes(id), + description varchar(50), + shortDesc char(8), + ratingTime timestamp without time zone, + handCount int)""" + elif db_server == 'sqlite': + self.query['createAutoratesTable'] = """CREATE TABLE Autorates ( id INTEGER PRIMARY KEY, - name TEXT NOT NULL, - currency TEXT NOT NULL)""" + playerId INT, + gametypeId INT, + description TEXT, + shortDesc TEXT, + ratingTime REAL, + handCount int)""" - ################################ - # Create Gametypes - ################################ + ################################ + # Create Hands + ################################ - if db_server == 'mysql': - self.query['createGametypesTable'] = """CREATE TABLE Gametypes ( + if db_server == 'mysql': + self.query['createHandsTable'] = """CREATE TABLE Hands ( + id BIGINT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), + tableName VARCHAR(20) NOT NULL, + siteHandNo BIGINT NOT NULL, + gametypeId SMALLINT UNSIGNED NOT NULL, FOREIGN KEY (gametypeId) REFERENCES Gametypes(id), + handStart DATETIME NOT NULL, + importTime DATETIME NOT NULL, + seats TINYINT NOT NULL, + maxSeats TINYINT NOT NULL, + boardcard1 smallint, /* 0=none, 1-13=2-Ah 14-26=2-Ad 27-39=2-Ac 40-52=2-As */ + boardcard2 smallint, + boardcard3 smallint, + boardcard4 smallint, + boardcard5 smallint, + texture smallint, + playersVpi SMALLINT NOT NULL, /* num of players vpi */ + playersAtStreet1 SMALLINT NOT NULL, /* num of players seeing flop/street4 */ + playersAtStreet2 SMALLINT NOT NULL, + playersAtStreet3 SMALLINT NOT NULL, + playersAtStreet4 SMALLINT NOT NULL, + playersAtShowdown SMALLINT NOT NULL, + street0Raises TINYINT NOT NULL, /* num small bets paid to see flop/street4, including blind */ + street1Raises TINYINT NOT NULL, /* num small bets paid to see turn/street5 */ + street2Raises TINYINT NOT NULL, /* num big bets paid to see river/street6 */ + street3Raises TINYINT NOT NULL, /* num big bets paid to see sd/street7 */ + street4Raises TINYINT NOT NULL, /* num big bets paid to see showdown */ + street1Pot INT, /* pot size at flop/street4 */ + street2Pot INT, /* pot size at turn/street5 */ + street3Pot INT, /* pot size at river/street6 */ + street4Pot INT, /* pot size at sd/street7 */ + showdownPot INT, /* pot size at sd/street7 */ + comment TEXT, + commentTs DATETIME) + ENGINE=INNODB""" + elif db_server == 'postgresql': + self.query['createHandsTable'] = """CREATE TABLE Hands ( + id BIGSERIAL, PRIMARY KEY (id), + tableName VARCHAR(20) NOT NULL, + siteHandNo BIGINT NOT NULL, + gametypeId INT NOT NULL, FOREIGN KEY (gametypeId) REFERENCES Gametypes(id), + handStart timestamp without time zone NOT NULL, + importTime timestamp without time zone NOT NULL, + seats SMALLINT NOT NULL, + maxSeats SMALLINT NOT NULL, + boardcard1 smallint, /* 0=none, 1-13=2-Ah 14-26=2-Ad 27-39=2-Ac 40-52=2-As */ + boardcard2 smallint, + boardcard3 smallint, + boardcard4 smallint, + boardcard5 smallint, + texture smallint, + playersVpi SMALLINT NOT NULL, /* num of players vpi */ + playersAtStreet1 SMALLINT NOT NULL, /* num of players seeing flop/street4 */ + playersAtStreet2 SMALLINT NOT NULL, + playersAtStreet3 SMALLINT NOT NULL, + playersAtStreet4 SMALLINT NOT NULL, + playersAtShowdown SMALLINT NOT NULL, + street0Raises SMALLINT NOT NULL, /* num small bets paid to see flop/street4, including blind */ + street1Raises SMALLINT NOT NULL, /* num small bets paid to see turn/street5 */ + street2Raises SMALLINT NOT NULL, /* num big bets paid to see river/street6 */ + street3Raises SMALLINT NOT NULL, /* num big bets paid to see sd/street7 */ + street4Raises SMALLINT NOT NULL, /* num big bets paid to see showdown */ + street1Pot INT, /* pot size at flop/street4 */ + street2Pot INT, /* pot size at turn/street5 */ + street3Pot INT, /* pot size at river/street6 */ + street4Pot INT, /* pot size at sd/street7 */ + showdownPot INT, /* pot size at sd/street7 */ + comment TEXT, + commentTs timestamp without time zone)""" + elif db_server == 'sqlite': + self.query['createHandsTable'] = """CREATE TABLE Hands ( + id INTEGER PRIMARY KEY, + tableName TEXT(20) NOT NULL, + siteHandNo INT NOT NULL, + gametypeId INT NOT NULL, + handStart REAL NOT NULL, + importTime REAL NOT NULL, + seats INT NOT NULL, + maxSeats INT NOT NULL, + boardcard1 INT, /* 0=none, 1-13=2-Ah 14-26=2-Ad 27-39=2-Ac 40-52=2-As */ + boardcard2 INT, + boardcard3 INT, + boardcard4 INT, + boardcard5 INT, + texture INT, + playersVpi INT NOT NULL, /* num of players vpi */ + playersAtStreet1 INT NOT NULL, /* num of players seeing flop/street4 */ + playersAtStreet2 INT NOT NULL, + playersAtStreet3 INT NOT NULL, + playersAtStreet4 INT NOT NULL, + playersAtShowdown INT NOT NULL, + street0Raises INT NOT NULL, /* num small bets paid to see flop/street4, including blind */ + street1Raises INT NOT NULL, /* num small bets paid to see turn/street5 */ + street2Raises INT NOT NULL, /* num big bets paid to see river/street6 */ + street3Raises INT NOT NULL, /* num big bets paid to see sd/street7 */ + street4Raises INT NOT NULL, /* num big bets paid to see showdown */ + street1Pot INT, /* pot size at flop/street4 */ + street2Pot INT, /* pot size at turn/street5 */ + street3Pot INT, /* pot size at river/street6 */ + street4Pot INT, /* pot size at sd/street7 */ + showdownPot INT, /* pot size at sd/street7 */ + comment TEXT, + commentTs REAL)""" + + + ################################ + # Create TourneyTypes + ################################ + + if db_server == 'mysql': + self.query['createTourneyTypesTable'] = """CREATE TABLE TourneyTypes ( id SMALLINT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), siteId SMALLINT UNSIGNED NOT NULL, FOREIGN KEY (siteId) REFERENCES Sites(id), - type char(4) NOT NULL, - base char(4) NOT NULL, - category varchar(9) NOT NULL, - limitType char(2) NOT NULL, - hiLo char(1) NOT NULL, - smallBlind int, - bigBlind int, - smallBet int NOT NULL, - bigBet int NOT NULL) - ENGINE=INNODB""" - elif db_server == 'postgresql': - self.query['createGametypesTable'] = """CREATE TABLE Gametypes ( - id SERIAL, PRIMARY KEY (id), - siteId INTEGER, FOREIGN KEY (siteId) REFERENCES Sites(id), - type char(4), - base char(4), - category varchar(9), - limitType char(2), - hiLo char(1), - smallBlind int, - bigBlind int, - smallBet int, - bigBet int)""" - elif db_server == 'sqlite': - self.query['createGametypesTable'] = """CREATE TABLE GameTypes ( - id INTEGER PRIMARY KEY, - siteId INTEGER, - type TEXT, - base TEXT, - category TEXT, - limitType TEXT, - hiLo TEXT, - smallBlind INTEGER, - bigBlind INTEGER, - smallBet INTEGER, - bigBet INTEGER, - FOREIGN KEY(siteId) REFERENCES Sites(id) ON DELETE CASCADE)""" - - - ################################ - # Create Players - ################################ - - if db_server == 'mysql': - self.query['createPlayersTable'] = """CREATE TABLE Players ( - id INT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), - name VARCHAR(32) CHARACTER SET utf8 NOT NULL, - siteId SMALLINT UNSIGNED NOT NULL, FOREIGN KEY (siteId) REFERENCES Sites(id), - comment text, - commentTs DATETIME) - ENGINE=INNODB""" - elif db_server == 'postgresql': - self.query['createPlayersTable'] = """CREATE TABLE Players ( - id SERIAL, PRIMARY KEY (id), - name VARCHAR(32), - siteId INTEGER, FOREIGN KEY (siteId) REFERENCES Sites(id), - comment text, - commentTs timestamp without time zone)""" - elif db_server == 'sqlite': - self.query['createPlayersTable'] = """CREATE TABLE Players ( - id INTEGER PRIMARY KEY, - name TEXT, - siteId INTEGER, - comment TEXT, - commentTs REAL, - FOREIGN KEY(siteId) REFERENCES Sites(id) ON DELETE CASCADE)""" - - - ################################ - # Create Autorates - ################################ - - if db_server == 'mysql': - self.query['createAutoratesTable'] = """CREATE TABLE Autorates ( - id BIGINT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), - playerId INT UNSIGNED NOT NULL, FOREIGN KEY (playerId) REFERENCES Players(id), - gametypeId SMALLINT UNSIGNED NOT NULL, FOREIGN KEY (gametypeId) REFERENCES Gametypes(id), - description varchar(50) NOT NULL, - shortDesc char(8) NOT NULL, - ratingTime DATETIME NOT NULL, - handCount int NOT NULL) - ENGINE=INNODB""" - elif db_server == 'postgresql': - self.query['createAutoratesTable'] = """CREATE TABLE Autorates ( - id BIGSERIAL, PRIMARY KEY (id), - playerId INT, FOREIGN KEY (playerId) REFERENCES Players(id), - gametypeId INT, FOREIGN KEY (gametypeId) REFERENCES Gametypes(id), - description varchar(50), - shortDesc char(8), - ratingTime timestamp without time zone, - handCount int)""" - elif db_server == 'sqlite': - self.query['createAutoratesTable'] = """CREATE TABLE Autorates ( - id INTEGER PRIMARY KEY, - playerId INT, - gametypeId INT, - description TEXT, - shortDesc TEXT, - ratingTime REAL, - handCount int)""" - - - ################################ - # Create Hands - ################################ - - if db_server == 'mysql': - self.query['createHandsTable'] = """CREATE TABLE Hands ( - id BIGINT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), - tableName VARCHAR(20) NOT NULL, - siteHandNo BIGINT NOT NULL, - gametypeId SMALLINT UNSIGNED NOT NULL, FOREIGN KEY (gametypeId) REFERENCES Gametypes(id), - handStart DATETIME NOT NULL, - importTime DATETIME NOT NULL, - seats TINYINT NOT NULL, - maxSeats TINYINT NOT NULL, - boardcard1 smallint, /* 0=none, 1-13=2-Ah 14-26=2-Ad 27-39=2-Ac 40-52=2-As */ - boardcard2 smallint, - boardcard3 smallint, - boardcard4 smallint, - boardcard5 smallint, - texture smallint, - playersVpi SMALLINT NOT NULL, /* num of players vpi */ - playersAtStreet1 SMALLINT NOT NULL, /* num of players seeing flop/street4 */ - playersAtStreet2 SMALLINT NOT NULL, - playersAtStreet3 SMALLINT NOT NULL, - playersAtStreet4 SMALLINT NOT NULL, - playersAtShowdown SMALLINT NOT NULL, - street0Raises TINYINT NOT NULL, /* num small bets paid to see flop/street4, including blind */ - street1Raises TINYINT NOT NULL, /* num small bets paid to see turn/street5 */ - street2Raises TINYINT NOT NULL, /* num big bets paid to see river/street6 */ - street3Raises TINYINT NOT NULL, /* num big bets paid to see sd/street7 */ - street4Raises TINYINT NOT NULL, /* num big bets paid to see showdown */ - street1Pot INT, /* pot size at flop/street4 */ - street2Pot INT, /* pot size at turn/street5 */ - street3Pot INT, /* pot size at river/street6 */ - street4Pot INT, /* pot size at sd/street7 */ - showdownPot INT, /* pot size at sd/street7 */ - comment TEXT, - commentTs DATETIME) - ENGINE=INNODB""" - elif db_server == 'postgresql': - self.query['createHandsTable'] = """CREATE TABLE Hands ( - id BIGSERIAL, PRIMARY KEY (id), - tableName VARCHAR(20) NOT NULL, - siteHandNo BIGINT NOT NULL, - gametypeId INT NOT NULL, FOREIGN KEY (gametypeId) REFERENCES Gametypes(id), - handStart timestamp without time zone NOT NULL, - importTime timestamp without time zone NOT NULL, - seats SMALLINT NOT NULL, - maxSeats SMALLINT NOT NULL, - boardcard1 smallint, /* 0=none, 1-13=2-Ah 14-26=2-Ad 27-39=2-Ac 40-52=2-As */ - boardcard2 smallint, - boardcard3 smallint, - boardcard4 smallint, - boardcard5 smallint, - texture smallint, - playersVpi SMALLINT NOT NULL, /* num of players vpi */ - playersAtStreet1 SMALLINT NOT NULL, /* num of players seeing flop/street4 */ - playersAtStreet2 SMALLINT NOT NULL, - playersAtStreet3 SMALLINT NOT NULL, - playersAtStreet4 SMALLINT NOT NULL, - playersAtShowdown SMALLINT NOT NULL, - street0Raises SMALLINT NOT NULL, /* num small bets paid to see flop/street4, including blind */ - street1Raises SMALLINT NOT NULL, /* num small bets paid to see turn/street5 */ - street2Raises SMALLINT NOT NULL, /* num big bets paid to see river/street6 */ - street3Raises SMALLINT NOT NULL, /* num big bets paid to see sd/street7 */ - street4Raises SMALLINT NOT NULL, /* num big bets paid to see showdown */ - street1Pot INT, /* pot size at flop/street4 */ - street2Pot INT, /* pot size at turn/street5 */ - street3Pot INT, /* pot size at river/street6 */ - street4Pot INT, /* pot size at sd/street7 */ - showdownPot INT, /* pot size at sd/street7 */ - comment TEXT, - commentTs timestamp without time zone)""" - elif db_server == 'sqlite': - self.query['createHandsTable'] = """CREATE TABLE Hands ( - id INTEGER PRIMARY KEY, - tableName TEXT(20) NOT NULL, - siteHandNo INT NOT NULL, - gametypeId INT NOT NULL, - handStart REAL NOT NULL, - importTime REAL NOT NULL, - seats INT NOT NULL, - maxSeats INT NOT NULL, - boardcard1 INT, /* 0=none, 1-13=2-Ah 14-26=2-Ad 27-39=2-Ac 40-52=2-As */ - boardcard2 INT, - boardcard3 INT, - boardcard4 INT, - boardcard5 INT, - texture INT, - playersVpi INT NOT NULL, /* num of players vpi */ - playersAtStreet1 INT NOT NULL, /* num of players seeing flop/street4 */ - playersAtStreet2 INT NOT NULL, - playersAtStreet3 INT NOT NULL, - playersAtStreet4 INT NOT NULL, - playersAtShowdown INT NOT NULL, - street0Raises INT NOT NULL, /* num small bets paid to see flop/street4, including blind */ - street1Raises INT NOT NULL, /* num small bets paid to see turn/street5 */ - street2Raises INT NOT NULL, /* num big bets paid to see river/street6 */ - street3Raises INT NOT NULL, /* num big bets paid to see sd/street7 */ - street4Raises INT NOT NULL, /* num big bets paid to see showdown */ - street1Pot INT, /* pot size at flop/street4 */ - street2Pot INT, /* pot size at turn/street5 */ - street3Pot INT, /* pot size at river/street6 */ - street4Pot INT, /* pot size at sd/street7 */ - showdownPot INT, /* pot size at sd/street7 */ - comment TEXT, - commentTs REAL)""" - - - ################################ - # Create TourneyTypes - ################################ - - if db_server == 'mysql': - self.query['createTourneyTypesTable'] = """CREATE TABLE TourneyTypes ( - id SMALLINT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), - siteId SMALLINT UNSIGNED NOT NULL, FOREIGN KEY (siteId) REFERENCES Sites(id), - buyin INT NOT NULL, - fee INT NOT NULL, - maxSeats INT NOT NULL DEFAULT -1, - knockout BOOLEAN NOT NULL DEFAULT False, - rebuyOrAddon BOOLEAN NOT NULL DEFAULT False, - speed varchar(10), - headsUp BOOLEAN NOT NULL DEFAULT False, - shootout BOOLEAN NOT NULL DEFAULT False, - matrix BOOLEAN NOT NULL DEFAULT False, - sng BOOLEAN NOT NULL DEFAULT False - ) - ENGINE=INNODB""" - elif db_server == 'postgresql': - self.query['createTourneyTypesTable'] = """CREATE TABLE TourneyTypes ( - id SERIAL, PRIMARY KEY (id), - siteId INT NOT NULL, FOREIGN KEY (siteId) REFERENCES Sites(id), buyin INT NOT NULL, fee INT NOT NULL, maxSeats INT NOT NULL DEFAULT -1, @@ -349,2852 +332,2868 @@ class Sql: shootout BOOLEAN NOT NULL DEFAULT False, matrix BOOLEAN NOT NULL DEFAULT False, sng BOOLEAN NOT NULL DEFAULT False - )""" - elif db_server == 'sqlite': - self.query['createTourneyTypesTable'] = """CREATE TABLE TourneyTypes ( - id INTEGER PRIMARY KEY, - siteId INT NOT NULL, - buyin INT NOT NULL, - fee INT NOT NULL, - maxSeats INT NOT NULL DEFAULT -1, - knockout BOOLEAN NOT NULL DEFAULT 0, - rebuyOrAddon BOOLEAN NOT NULL DEFAULT 0, - speed TEXT, - headsUp BOOLEAN NOT NULL DEFAULT 0, - shootout BOOLEAN NOT NULL DEFAULT 0, - matrix BOOLEAN NOT NULL DEFAULT 0, - sng BOOLEAN NOT NULL DEFAULT 0 - )""" + ) + ENGINE=INNODB""" + elif db_server == 'postgresql': + self.query['createTourneyTypesTable'] = """CREATE TABLE TourneyTypes ( + id SERIAL, PRIMARY KEY (id), + siteId INT NOT NULL, FOREIGN KEY (siteId) REFERENCES Sites(id), + buyin INT NOT NULL, + fee INT NOT NULL, + maxSeats INT NOT NULL DEFAULT -1, + knockout BOOLEAN NOT NULL DEFAULT False, + rebuyOrAddon BOOLEAN NOT NULL DEFAULT False, + speed varchar(10), + headsUp BOOLEAN NOT NULL DEFAULT False, + shootout BOOLEAN NOT NULL DEFAULT False, + matrix BOOLEAN NOT NULL DEFAULT False, + sng BOOLEAN NOT NULL DEFAULT False + )""" + elif db_server == 'sqlite': + self.query['createTourneyTypesTable'] = """CREATE TABLE TourneyTypes ( + id INTEGER PRIMARY KEY, + siteId INT NOT NULL, + buyin INT NOT NULL, + fee INT NOT NULL, + maxSeats INT NOT NULL DEFAULT -1, + knockout BOOLEAN NOT NULL DEFAULT 0, + rebuyOrAddon BOOLEAN NOT NULL DEFAULT 0, + speed TEXT, + headsUp BOOLEAN NOT NULL DEFAULT 0, + shootout BOOLEAN NOT NULL DEFAULT 0, + matrix BOOLEAN NOT NULL DEFAULT 0, + sng BOOLEAN NOT NULL DEFAULT 0 + )""" - ################################ - # Create Tourneys - ################################ + ################################ + # Create Tourneys + ################################ - if db_server == 'mysql': - self.query['createTourneysTable'] = """CREATE TABLE Tourneys ( - id INT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), - tourneyTypeId SMALLINT UNSIGNED NOT NULL DEFAULT 1, FOREIGN KEY (tourneyTypeId) REFERENCES TourneyTypes(id), - siteTourneyNo BIGINT NOT NULL, - entries INT NOT NULL, - prizepool INT NOT NULL, - startTime DATETIME NOT NULL, - endTime DATETIME, - buyinChips INT, - tourneyName varchar(40), - matrixIdProcessed TINYINT UNSIGNED DEFAULT 0, /* Mask use : 1=Positionnal Winnings|2=Match1|4=Match2|...|pow(2,n)=Matchn */ - rebuyChips INT DEFAULT 0, - addonChips INT DEFAULT 0, - rebuyAmount INT DEFAULT 0, - addonAmount INT DEFAULT 0, - totalRebuys INT DEFAULT 0, - totalAddons INT DEFAULT 0, - koBounty INT DEFAULT 0, - comment TEXT, - commentTs DATETIME) - ENGINE=INNODB""" - elif db_server == 'postgresql': - self.query['createTourneysTable'] = """CREATE TABLE Tourneys ( - id SERIAL, PRIMARY KEY (id), - tourneyTypeId INT DEFAULT 1, FOREIGN KEY (tourneyTypeId) REFERENCES TourneyTypes(id), - siteTourneyNo BIGINT, - entries INT, - prizepool INT, - startTime timestamp without time zone, - endTime timestamp without time zone, - buyinChips INT, - tourneyName varchar(40), - matrixIdProcessed SMALLINT DEFAULT 0, /* Mask use : 1=Positionnal Winnings|2=Match1|4=Match2|...|pow(2,n)=Matchn */ - rebuyChips INT DEFAULT 0, - addonChips INT DEFAULT 0, - rebuyAmount INT DEFAULT 0, - addonAmount INT DEFAULT 0, - totalRebuys INT DEFAULT 0, - totalAddons INT DEFAULT 0, - koBounty INT DEFAULT 0, - comment TEXT, - commentTs timestamp without time zone)""" - elif db_server == 'sqlite': - self.query['createTourneysTable'] = """CREATE TABLE Tourneys ( - id INTEGER PRIMARY KEY, - tourneyTypeId INT DEFAULT 1, - siteTourneyNo INT, - entries INT, - prizepool INT, - startTime REAL, - endTime REAL, - buyinChips INT, - tourneyName TEXT, - matrixIdProcessed INT UNSIGNED DEFAULT 0, /* Mask use : 1=Positionnal Winnings|2=Match1|4=Match2|...|pow(2,n)=Matchn */ - rebuyChips INT DEFAULT 0, - addonChips INT DEFAULT 0, - rebuyAmount INT DEFAULT 0, - addonAmount INT DEFAULT 0, - totalRebuys INT DEFAULT 0, - totalAddons INT DEFAULT 0, - koBounty INT DEFAULT 0, - comment TEXT, - commentTs REAL)""" - ################################ - # Create HandsPlayers - ################################ + if db_server == 'mysql': + self.query['createTourneysTable'] = """CREATE TABLE Tourneys ( + id INT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), + tourneyTypeId SMALLINT UNSIGNED NOT NULL DEFAULT 1, FOREIGN KEY (tourneyTypeId) REFERENCES TourneyTypes(id), + siteTourneyNo BIGINT NOT NULL, + entries INT NOT NULL, + prizepool INT NOT NULL, + startTime DATETIME NOT NULL, + endTime DATETIME, + buyinChips INT, + tourneyName varchar(40), + matrixIdProcessed TINYINT UNSIGNED DEFAULT 0, /* Mask use : 1=Positionnal Winnings|2=Match1|4=Match2|...|pow(2,n)=Matchn */ + rebuyChips INT DEFAULT 0, + addonChips INT DEFAULT 0, + rebuyAmount INT DEFAULT 0, + addonAmount INT DEFAULT 0, + totalRebuys INT DEFAULT 0, + totalAddons INT DEFAULT 0, + koBounty INT DEFAULT 0, + comment TEXT, + commentTs DATETIME) + ENGINE=INNODB""" + elif db_server == 'postgresql': + self.query['createTourneysTable'] = """CREATE TABLE Tourneys ( + id SERIAL, PRIMARY KEY (id), + tourneyTypeId INT DEFAULT 1, FOREIGN KEY (tourneyTypeId) REFERENCES TourneyTypes(id), + siteTourneyNo BIGINT, + entries INT, + prizepool INT, + startTime timestamp without time zone, + endTime timestamp without time zone, + buyinChips INT, + tourneyName varchar(40), + matrixIdProcessed SMALLINT DEFAULT 0, /* Mask use : 1=Positionnal Winnings|2=Match1|4=Match2|...|pow(2,n)=Matchn */ + rebuyChips INT DEFAULT 0, + addonChips INT DEFAULT 0, + rebuyAmount INT DEFAULT 0, + addonAmount INT DEFAULT 0, + totalRebuys INT DEFAULT 0, + totalAddons INT DEFAULT 0, + koBounty INT DEFAULT 0, + comment TEXT, + commentTs timestamp without time zone)""" + elif db_server == 'sqlite': + self.query['createTourneysTable'] = """CREATE TABLE Tourneys ( + id INTEGER PRIMARY KEY, + tourneyTypeId INT DEFAULT 1, + siteTourneyNo INT, + entries INT, + prizepool INT, + startTime REAL, + endTime REAL, + buyinChips INT, + tourneyName TEXT, + matrixIdProcessed INT UNSIGNED DEFAULT 0, /* Mask use : 1=Positionnal Winnings|2=Match1|4=Match2|...|pow(2,n)=Matchn */ + rebuyChips INT DEFAULT 0, + addonChips INT DEFAULT 0, + rebuyAmount INT DEFAULT 0, + addonAmount INT DEFAULT 0, + totalRebuys INT DEFAULT 0, + totalAddons INT DEFAULT 0, + koBounty INT DEFAULT 0, + comment TEXT, + commentTs REAL)""" + ################################ + # Create HandsPlayers + ################################ - if db_server == 'mysql': - self.query['createHandsPlayersTable'] = """CREATE TABLE HandsPlayers ( - id BIGINT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), - handId BIGINT UNSIGNED NOT NULL, FOREIGN KEY (handId) REFERENCES Hands(id), - playerId INT UNSIGNED NOT NULL, FOREIGN KEY (playerId) REFERENCES Players(id), - startCash INT NOT NULL, - position CHAR(1), - seatNo SMALLINT NOT NULL, + if db_server == 'mysql': + self.query['createHandsPlayersTable'] = """CREATE TABLE HandsPlayers ( + id BIGINT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), + handId BIGINT UNSIGNED NOT NULL, FOREIGN KEY (handId) REFERENCES Hands(id), + playerId INT UNSIGNED NOT NULL, FOREIGN KEY (playerId) REFERENCES Players(id), + startCash INT NOT NULL, + position CHAR(1), + seatNo SMALLINT NOT NULL, + + card1 smallint NOT NULL, /* 0=none, 1-13=2-Ah 14-26=2-Ad 27-39=2-Ac 40-52=2-As */ + card2 smallint NOT NULL, + card3 smallint, + card4 smallint, + card5 smallint, + card6 smallint, + card7 smallint, + startCards smallint, + + ante INT, + winnings int NOT NULL, + rake int NOT NULL, + totalProfit INT, + comment text, + commentTs DATETIME, + tourneysPlayersId BIGINT UNSIGNED, + tourneyTypeId SMALLINT UNSIGNED NOT NULL DEFAULT 1, FOREIGN KEY (tourneyTypeId) REFERENCES TourneyTypes(id), + + wonWhenSeenStreet1 FLOAT, + wonWhenSeenStreet2 FLOAT, + wonWhenSeenStreet3 FLOAT, + wonWhenSeenStreet4 FLOAT, + wonAtSD FLOAT, + + street0VPI BOOLEAN, + street0Aggr BOOLEAN, + street0_3BChance BOOLEAN, + street0_3BDone BOOLEAN, + street0_4BChance BOOLEAN, + street0_4BDone BOOLEAN, + other3BStreet0 BOOLEAN, + other4BStreet0 BOOLEAN, + + street1Seen BOOLEAN, + street2Seen BOOLEAN, + street3Seen BOOLEAN, + street4Seen BOOLEAN, + sawShowdown BOOLEAN, + + street1Aggr BOOLEAN, + street2Aggr BOOLEAN, + street3Aggr BOOLEAN, + street4Aggr BOOLEAN, + + otherRaisedStreet0 BOOLEAN, + otherRaisedStreet1 BOOLEAN, + otherRaisedStreet2 BOOLEAN, + otherRaisedStreet3 BOOLEAN, + otherRaisedStreet4 BOOLEAN, + foldToOtherRaisedStreet0 BOOLEAN, + foldToOtherRaisedStreet1 BOOLEAN, + foldToOtherRaisedStreet2 BOOLEAN, + foldToOtherRaisedStreet3 BOOLEAN, + foldToOtherRaisedStreet4 BOOLEAN, + + stealAttemptChance BOOLEAN, + stealAttempted BOOLEAN, + foldBbToStealChance BOOLEAN, + foldedBbToSteal BOOLEAN, + foldSbToStealChance BOOLEAN, + foldedSbToSteal BOOLEAN, + + street1CBChance BOOLEAN, + street1CBDone BOOLEAN, + street2CBChance BOOLEAN, + street2CBDone BOOLEAN, + street3CBChance BOOLEAN, + street3CBDone BOOLEAN, + street4CBChance BOOLEAN, + street4CBDone BOOLEAN, + + foldToStreet1CBChance BOOLEAN, + foldToStreet1CBDone BOOLEAN, + foldToStreet2CBChance BOOLEAN, + foldToStreet2CBDone BOOLEAN, + foldToStreet3CBChance BOOLEAN, + foldToStreet3CBDone BOOLEAN, + foldToStreet4CBChance BOOLEAN, + foldToStreet4CBDone BOOLEAN, + + street1CheckCallRaiseChance BOOLEAN, + street1CheckCallRaiseDone BOOLEAN, + street2CheckCallRaiseChance BOOLEAN, + street2CheckCallRaiseDone BOOLEAN, + street3CheckCallRaiseChance BOOLEAN, + street3CheckCallRaiseDone BOOLEAN, + street4CheckCallRaiseChance BOOLEAN, + street4CheckCallRaiseDone BOOLEAN, + + street0Calls TINYINT, + street1Calls TINYINT, + street2Calls TINYINT, + street3Calls TINYINT, + street4Calls TINYINT, + street0Bets TINYINT, + street1Bets TINYINT, + street2Bets TINYINT, + street3Bets TINYINT, + street4Bets TINYINT, + street0Raises TINYINT, + street1Raises TINYINT, + street2Raises TINYINT, + street3Raises TINYINT, + street4Raises TINYINT, + + actionString VARCHAR(15), + + FOREIGN KEY (tourneysPlayersId) REFERENCES TourneysPlayers(id)) + ENGINE=INNODB""" + elif db_server == 'postgresql': + self.query['createHandsPlayersTable'] = """CREATE TABLE HandsPlayers ( + id BIGSERIAL, PRIMARY KEY (id), + handId BIGINT NOT NULL, FOREIGN KEY (handId) REFERENCES Hands(id), + playerId INT NOT NULL, FOREIGN KEY (playerId) REFERENCES Players(id), + startCash INT NOT NULL, + position CHAR(1), + seatNo SMALLINT NOT NULL, + + card1 smallint NOT NULL, /* 0=none, 1-13=2-Ah 14-26=2-Ad 27-39=2-Ac 40-52=2-As */ + card2 smallint NOT NULL, + card3 smallint, + card4 smallint, + card5 smallint, + card6 smallint, + card7 smallint, + startCards smallint, + + ante INT, + winnings int NOT NULL, + rake int NOT NULL, + totalProfit INT, + comment text, + commentTs timestamp without time zone, + tourneysPlayersId BIGINT, + tourneyTypeId INT NOT NULL DEFAULT 1, FOREIGN KEY (tourneyTypeId) REFERENCES TourneyTypes(id), + + wonWhenSeenStreet1 FLOAT, + wonWhenSeenStreet2 FLOAT, + wonWhenSeenStreet3 FLOAT, + wonWhenSeenStreet4 FLOAT, + wonAtSD FLOAT, + + street0VPI BOOLEAN, + street0Aggr BOOLEAN, + street0_3BChance BOOLEAN, + street0_3BDone BOOLEAN, + street0_4BChance BOOLEAN, + street0_4BDone BOOLEAN, + other3BStreet0 BOOLEAN, + other4BStreet0 BOOLEAN, + + street1Seen BOOLEAN, + street2Seen BOOLEAN, + street3Seen BOOLEAN, + street4Seen BOOLEAN, + sawShowdown BOOLEAN, + + street1Aggr BOOLEAN, + street2Aggr BOOLEAN, + street3Aggr BOOLEAN, + street4Aggr BOOLEAN, + + otherRaisedStreet0 BOOLEAN, + otherRaisedStreet1 BOOLEAN, + otherRaisedStreet2 BOOLEAN, + otherRaisedStreet3 BOOLEAN, + otherRaisedStreet4 BOOLEAN, + foldToOtherRaisedStreet0 BOOLEAN, + foldToOtherRaisedStreet1 BOOLEAN, + foldToOtherRaisedStreet2 BOOLEAN, + foldToOtherRaisedStreet3 BOOLEAN, + foldToOtherRaisedStreet4 BOOLEAN, + + stealAttemptChance BOOLEAN, + stealAttempted BOOLEAN, + foldBbToStealChance BOOLEAN, + foldedBbToSteal BOOLEAN, + foldSbToStealChance BOOLEAN, + foldedSbToSteal BOOLEAN, + + street1CBChance BOOLEAN, + street1CBDone BOOLEAN, + street2CBChance BOOLEAN, + street2CBDone BOOLEAN, + street3CBChance BOOLEAN, + street3CBDone BOOLEAN, + street4CBChance BOOLEAN, + street4CBDone BOOLEAN, + + foldToStreet1CBChance BOOLEAN, + foldToStreet1CBDone BOOLEAN, + foldToStreet2CBChance BOOLEAN, + foldToStreet2CBDone BOOLEAN, + foldToStreet3CBChance BOOLEAN, + foldToStreet3CBDone BOOLEAN, + foldToStreet4CBChance BOOLEAN, + foldToStreet4CBDone BOOLEAN, + + street1CheckCallRaiseChance BOOLEAN, + street1CheckCallRaiseDone BOOLEAN, + street2CheckCallRaiseChance BOOLEAN, + street2CheckCallRaiseDone BOOLEAN, + street3CheckCallRaiseChance BOOLEAN, + street3CheckCallRaiseDone BOOLEAN, + street4CheckCallRaiseChance BOOLEAN, + street4CheckCallRaiseDone BOOLEAN, + + street0Calls SMALLINT, + street1Calls SMALLINT, + street2Calls SMALLINT, + street3Calls SMALLINT, + street4Calls SMALLINT, + street0Bets SMALLINT, + street1Bets SMALLINT, + street2Bets SMALLINT, + street3Bets SMALLINT, + street4Bets SMALLINT, + street0Raises SMALLINT, + street1Raises SMALLINT, + street2Raises SMALLINT, + street3Raises SMALLINT, + street4Raises SMALLINT, + + actionString VARCHAR(15), + + FOREIGN KEY (tourneysPlayersId) REFERENCES TourneysPlayers(id))""" + elif db_server == 'sqlite': + self.query['createHandsPlayersTable'] = """CREATE TABLE HandsPlayers ( + id INTEGER PRIMARY KEY, + handId INT NOT NULL, + playerId INT NOT NULL, + startCash INT NOT NULL, + position TEXT, + seatNo INT NOT NULL, + + card1 INT NOT NULL, /* 0=none, 1-13=2-Ah 14-26=2-Ad 27-39=2-Ac 40-52=2-As */ + card2 INT NOT NULL, + card3 INT, + card4 INT, + card5 INT, + card6 INT, + card7 INT, + startCards INT, + + ante INT, + winnings INT NOT NULL, + rake INT NOT NULL, + totalProfit INT, + comment TEXT, + commentTs REAL, + tourneysPlayersId INT, + tourneyTypeId INT NOT NULL DEFAULT 1, + + wonWhenSeenStreet1 REAL, + wonWhenSeenStreet2 REAL, + wonWhenSeenStreet3 REAL, + wonWhenSeenStreet4 REAL, + wonAtSD REAL, + + street0VPI INT, + street0Aggr INT, + street0_3BChance INT, + street0_3BDone INT, + street0_4BChance INT, + street0_4BDone INT, + other3BStreet0 INT, + other4BStreet0 INT, + + street1Seen INT, + street2Seen INT, + street3Seen INT, + street4Seen INT, + sawShowdown INT, + + street1Aggr INT, + street2Aggr INT, + street3Aggr INT, + street4Aggr INT, + + otherRaisedStreet0 INT, + otherRaisedStreet1 INT, + otherRaisedStreet2 INT, + otherRaisedStreet3 INT, + otherRaisedStreet4 INT, + foldToOtherRaisedStreet0 INT, + foldToOtherRaisedStreet1 INT, + foldToOtherRaisedStreet2 INT, + foldToOtherRaisedStreet3 INT, + foldToOtherRaisedStreet4 INT, + + stealAttemptChance INT, + stealAttempted INT, + foldBbToStealChance INT, + foldedBbToSteal INT, + foldSbToStealChance INT, + foldedSbToSteal INT, + + street1CBChance INT, + street1CBDone INT, + street2CBChance INT, + street2CBDone INT, + street3CBChance INT, + street3CBDone INT, + street4CBChance INT, + street4CBDone INT, + + foldToStreet1CBChance INT, + foldToStreet1CBDone INT, + foldToStreet2CBChance INT, + foldToStreet2CBDone INT, + foldToStreet3CBChance INT, + foldToStreet3CBDone INT, + foldToStreet4CBChance INT, + foldToStreet4CBDone INT, + + street1CheckCallRaiseChance INT, + street1CheckCallRaiseDone INT, + street2CheckCallRaiseChance INT, + street2CheckCallRaiseDone INT, + street3CheckCallRaiseChance INT, + street3CheckCallRaiseDone INT, + street4CheckCallRaiseChance INT, + street4CheckCallRaiseDone INT, + + street0Calls INT, + street1Calls INT, + street2Calls INT, + street3Calls INT, + street4Calls INT, + street0Bets INT, + street1Bets INT, + street2Bets INT, + street3Bets INT, + street4Bets INT, + street0Raises INT, + street1Raises INT, + street2Raises INT, + street3Raises INT, + street4Raises INT, + + actionString REAL) + """ + + + ################################ + # Create TourneysPlayers + ################################ + + if db_server == 'mysql': + self.query['createTourneysPlayersTable'] = """CREATE TABLE TourneysPlayers ( + id BIGINT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), + tourneyId INT UNSIGNED NOT NULL, FOREIGN KEY (tourneyId) REFERENCES Tourneys(id), + playerId INT UNSIGNED NOT NULL, FOREIGN KEY (playerId) REFERENCES Players(id), + payinAmount INT NOT NULL, + rank INT NOT NULL, + winnings INT NOT NULL, + nbRebuys INT DEFAULT 0, + nbAddons INT DEFAULT 0, + nbKO INT DEFAULT 0, + comment TEXT, + commentTs DATETIME) + ENGINE=INNODB""" + elif db_server == 'postgresql': + self.query['createTourneysPlayersTable'] = """CREATE TABLE TourneysPlayers ( + id BIGSERIAL, PRIMARY KEY (id), + tourneyId INT, FOREIGN KEY (tourneyId) REFERENCES Tourneys(id), + playerId INT, FOREIGN KEY (playerId) REFERENCES Players(id), + payinAmount INT, + rank INT, + winnings INT, + nbRebuys INT DEFAULT 0, + nbAddons INT DEFAULT 0, + nbKO INT DEFAULT 0, + comment TEXT, + commentTs timestamp without time zone)""" + elif db_server == 'sqlite': + self.query['createTourneysPlayersTable'] = """CREATE TABLE TourneysPlayers ( + id INT PRIMARY KEY, + tourneyId INT, + playerId INT, + payinAmount INT, + rank INT, + winnings INT, + nbRebuys INT DEFAULT 0, + nbAddons INT DEFAULT 0, + nbKO INT DEFAULT 0, + comment TEXT, + commentTs timestamp without time zone, + FOREIGN KEY (tourneyId) REFERENCES Tourneys(id), + FOREIGN KEY (playerId) REFERENCES Players(id) + )""" + + + ################################ + # Create HandsActions + ################################ + + if db_server == 'mysql': + self.query['createHandsActionsTable'] = """CREATE TABLE HandsActions ( + id BIGINT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), + handsPlayerId BIGINT UNSIGNED NOT NULL, FOREIGN KEY (handsPlayerId) REFERENCES HandsPlayers(id), + street SMALLINT NOT NULL, + actionNo SMALLINT NOT NULL, + action CHAR(5) NOT NULL, + allIn BOOLEAN NOT NULL, + amount INT NOT NULL, + comment TEXT, + commentTs DATETIME) + ENGINE=INNODB""" + elif db_server == 'postgresql': + self.query['createHandsActionsTable'] = """CREATE TABLE HandsActions ( + id BIGSERIAL, PRIMARY KEY (id), + handsPlayerId BIGINT, FOREIGN KEY (handsPlayerId) REFERENCES HandsPlayers(id), + street SMALLINT, + actionNo SMALLINT, + action CHAR(5), + allIn BOOLEAN, + amount INT, + comment TEXT, + commentTs timestamp without time zone)""" + elif db_server == 'sqlite': + self.query['createHandsActionsTable'] = """CREATE TABLE HandsActions ( + id INT PRIMARY KEY, + handsPlayerId BIGINT, + street SMALLINT, + actionNo SMALLINT, + action CHAR(5), + allIn INT, + amount INT, + comment TEXT, + commentTs timestamp without time zone, + FOREIGN KEY (handsPlayerId) REFERENCES HandsPlayers(id) + )""" + + + ################################ + # Create HudCache + ################################ + + if db_server == 'mysql': + self.query['createHudCacheTable'] = """CREATE TABLE HudCache ( + id BIGINT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), + gametypeId SMALLINT UNSIGNED NOT NULL, FOREIGN KEY (gametypeId) REFERENCES Gametypes(id), + playerId INT UNSIGNED NOT NULL, FOREIGN KEY (playerId) REFERENCES Players(id), + activeSeats SMALLINT NOT NULL, + position CHAR(1), + tourneyTypeId SMALLINT UNSIGNED NOT NULL DEFAULT 1, FOREIGN KEY (tourneyTypeId) REFERENCES TourneyTypes(id), + styleKey CHAR(7) NOT NULL, /* 1st char is style (A/T/H/S), other 6 are the key */ + HDs INT NOT NULL, + + wonWhenSeenStreet1 FLOAT, + wonWhenSeenStreet2 FLOAT, + wonWhenSeenStreet3 FLOAT, + wonWhenSeenStreet4 FLOAT, + wonAtSD FLOAT, + + street0VPI INT, + street0Aggr INT, + street0_3BChance INT, + street0_3BDone INT, + street0_4BChance INT, + street0_4BDone INT, + other3BStreet0 INT, + other4BStreet0 INT, + + street1Seen INT, + street2Seen INT, + street3Seen INT, + street4Seen INT, + sawShowdown INT, - card1 smallint NOT NULL, /* 0=none, 1-13=2-Ah 14-26=2-Ad 27-39=2-Ac 40-52=2-As */ - card2 smallint NOT NULL, - card3 smallint, - card4 smallint, - card5 smallint, - card6 smallint, - card7 smallint, - startCards smallint, + street1Aggr INT, + street2Aggr INT, + street3Aggr INT, + street4Aggr INT, + + otherRaisedStreet0 INT, + otherRaisedStreet1 INT, + otherRaisedStreet2 INT, + otherRaisedStreet3 INT, + otherRaisedStreet4 INT, + foldToOtherRaisedStreet0 INT, + foldToOtherRaisedStreet1 INT, + foldToOtherRaisedStreet2 INT, + foldToOtherRaisedStreet3 INT, + foldToOtherRaisedStreet4 INT, - ante INT, - winnings int NOT NULL, - rake int NOT NULL, - totalProfit INT, - comment text, - commentTs DATETIME, - tourneysPlayersId BIGINT UNSIGNED, - tourneyTypeId SMALLINT UNSIGNED NOT NULL DEFAULT 1, FOREIGN KEY (tourneyTypeId) REFERENCES TourneyTypes(id), + stealAttemptChance INT, + stealAttempted INT, + foldBbToStealChance INT, + foldedBbToSteal INT, + foldSbToStealChance INT, + foldedSbToSteal INT, - wonWhenSeenStreet1 FLOAT, - wonWhenSeenStreet2 FLOAT, - wonWhenSeenStreet3 FLOAT, - wonWhenSeenStreet4 FLOAT, - wonAtSD FLOAT, - - street0VPI BOOLEAN, - street0Aggr BOOLEAN, - street0_3BChance BOOLEAN, - street0_3BDone BOOLEAN, - street0_4BChance BOOLEAN, - street0_4BDone BOOLEAN, - other3BStreet0 BOOLEAN, - other4BStreet0 BOOLEAN, - - street1Seen BOOLEAN, - street2Seen BOOLEAN, - street3Seen BOOLEAN, - street4Seen BOOLEAN, - sawShowdown BOOLEAN, - - street1Aggr BOOLEAN, - street2Aggr BOOLEAN, - street3Aggr BOOLEAN, - street4Aggr BOOLEAN, - - otherRaisedStreet0 BOOLEAN, - otherRaisedStreet1 BOOLEAN, - otherRaisedStreet2 BOOLEAN, - otherRaisedStreet3 BOOLEAN, - otherRaisedStreet4 BOOLEAN, - foldToOtherRaisedStreet0 BOOLEAN, - foldToOtherRaisedStreet1 BOOLEAN, - foldToOtherRaisedStreet2 BOOLEAN, - foldToOtherRaisedStreet3 BOOLEAN, - foldToOtherRaisedStreet4 BOOLEAN, - - stealAttemptChance BOOLEAN, - stealAttempted BOOLEAN, - foldBbToStealChance BOOLEAN, - foldedBbToSteal BOOLEAN, - foldSbToStealChance BOOLEAN, - foldedSbToSteal BOOLEAN, - - street1CBChance BOOLEAN, - street1CBDone BOOLEAN, - street2CBChance BOOLEAN, - street2CBDone BOOLEAN, - street3CBChance BOOLEAN, - street3CBDone BOOLEAN, - street4CBChance BOOLEAN, - street4CBDone BOOLEAN, - - foldToStreet1CBChance BOOLEAN, - foldToStreet1CBDone BOOLEAN, - foldToStreet2CBChance BOOLEAN, - foldToStreet2CBDone BOOLEAN, - foldToStreet3CBChance BOOLEAN, - foldToStreet3CBDone BOOLEAN, - foldToStreet4CBChance BOOLEAN, - foldToStreet4CBDone BOOLEAN, - - street1CheckCallRaiseChance BOOLEAN, - street1CheckCallRaiseDone BOOLEAN, - street2CheckCallRaiseChance BOOLEAN, - street2CheckCallRaiseDone BOOLEAN, - street3CheckCallRaiseChance BOOLEAN, - street3CheckCallRaiseDone BOOLEAN, - street4CheckCallRaiseChance BOOLEAN, - street4CheckCallRaiseDone BOOLEAN, - - street0Calls TINYINT, - street1Calls TINYINT, - street2Calls TINYINT, - street3Calls TINYINT, - street4Calls TINYINT, - street0Bets TINYINT, - street1Bets TINYINT, - street2Bets TINYINT, - street3Bets TINYINT, - street4Bets TINYINT, - street0Raises TINYINT, - street1Raises TINYINT, - street2Raises TINYINT, - street3Raises TINYINT, - street4Raises TINYINT, - - actionString VARCHAR(15), - - FOREIGN KEY (tourneysPlayersId) REFERENCES TourneysPlayers(id)) - ENGINE=INNODB""" - elif db_server == 'postgresql': - self.query['createHandsPlayersTable'] = """CREATE TABLE HandsPlayers ( - id BIGSERIAL, PRIMARY KEY (id), - handId BIGINT NOT NULL, FOREIGN KEY (handId) REFERENCES Hands(id), - playerId INT NOT NULL, FOREIGN KEY (playerId) REFERENCES Players(id), - startCash INT NOT NULL, - position CHAR(1), - seatNo SMALLINT NOT NULL, - - card1 smallint NOT NULL, /* 0=none, 1-13=2-Ah 14-26=2-Ad 27-39=2-Ac 40-52=2-As */ - card2 smallint NOT NULL, - card3 smallint, - card4 smallint, - card5 smallint, - card6 smallint, - card7 smallint, - startCards smallint, - - ante INT, - winnings int NOT NULL, - rake int NOT NULL, - totalProfit INT, - comment text, - commentTs timestamp without time zone, - tourneysPlayersId BIGINT, - tourneyTypeId INT NOT NULL DEFAULT 1, FOREIGN KEY (tourneyTypeId) REFERENCES TourneyTypes(id), - - wonWhenSeenStreet1 FLOAT, - wonWhenSeenStreet2 FLOAT, - wonWhenSeenStreet3 FLOAT, - wonWhenSeenStreet4 FLOAT, - wonAtSD FLOAT, - - street0VPI BOOLEAN, - street0Aggr BOOLEAN, - street0_3BChance BOOLEAN, - street0_3BDone BOOLEAN, - street0_4BChance BOOLEAN, - street0_4BDone BOOLEAN, - other3BStreet0 BOOLEAN, - other4BStreet0 BOOLEAN, - - street1Seen BOOLEAN, - street2Seen BOOLEAN, - street3Seen BOOLEAN, - street4Seen BOOLEAN, - sawShowdown BOOLEAN, - - street1Aggr BOOLEAN, - street2Aggr BOOLEAN, - street3Aggr BOOLEAN, - street4Aggr BOOLEAN, - - otherRaisedStreet0 BOOLEAN, - otherRaisedStreet1 BOOLEAN, - otherRaisedStreet2 BOOLEAN, - otherRaisedStreet3 BOOLEAN, - otherRaisedStreet4 BOOLEAN, - foldToOtherRaisedStreet0 BOOLEAN, - foldToOtherRaisedStreet1 BOOLEAN, - foldToOtherRaisedStreet2 BOOLEAN, - foldToOtherRaisedStreet3 BOOLEAN, - foldToOtherRaisedStreet4 BOOLEAN, - - stealAttemptChance BOOLEAN, - stealAttempted BOOLEAN, - foldBbToStealChance BOOLEAN, - foldedBbToSteal BOOLEAN, - foldSbToStealChance BOOLEAN, - foldedSbToSteal BOOLEAN, - - street1CBChance BOOLEAN, - street1CBDone BOOLEAN, - street2CBChance BOOLEAN, - street2CBDone BOOLEAN, - street3CBChance BOOLEAN, - street3CBDone BOOLEAN, - street4CBChance BOOLEAN, - street4CBDone BOOLEAN, - - foldToStreet1CBChance BOOLEAN, - foldToStreet1CBDone BOOLEAN, - foldToStreet2CBChance BOOLEAN, - foldToStreet2CBDone BOOLEAN, - foldToStreet3CBChance BOOLEAN, - foldToStreet3CBDone BOOLEAN, - foldToStreet4CBChance BOOLEAN, - foldToStreet4CBDone BOOLEAN, - - street1CheckCallRaiseChance BOOLEAN, - street1CheckCallRaiseDone BOOLEAN, - street2CheckCallRaiseChance BOOLEAN, - street2CheckCallRaiseDone BOOLEAN, - street3CheckCallRaiseChance BOOLEAN, - street3CheckCallRaiseDone BOOLEAN, - street4CheckCallRaiseChance BOOLEAN, - street4CheckCallRaiseDone BOOLEAN, - - street0Calls SMALLINT, - street1Calls SMALLINT, - street2Calls SMALLINT, - street3Calls SMALLINT, - street4Calls SMALLINT, - street0Bets SMALLINT, - street1Bets SMALLINT, - street2Bets SMALLINT, - street3Bets SMALLINT, - street4Bets SMALLINT, - street0Raises SMALLINT, - street1Raises SMALLINT, - street2Raises SMALLINT, - street3Raises SMALLINT, - street4Raises SMALLINT, - - actionString VARCHAR(15), - - FOREIGN KEY (tourneysPlayersId) REFERENCES TourneysPlayers(id))""" - elif db_server == 'sqlite': - self.query['createHandsPlayersTable'] = """CREATE TABLE HandsPlayers ( - id INTEGER PRIMARY KEY, - handId INT NOT NULL, - playerId INT NOT NULL, - startCash INT NOT NULL, - position TEXT, - seatNo INT NOT NULL, + street1CBChance INT, + street1CBDone INT, + street2CBChance INT, + street2CBDone INT, + street3CBChance INT, + street3CBDone INT, + street4CBChance INT, + street4CBDone INT, - card1 INT NOT NULL, /* 0=none, 1-13=2-Ah 14-26=2-Ad 27-39=2-Ac 40-52=2-As */ - card2 INT NOT NULL, - card3 INT, - card4 INT, - card5 INT, - card6 INT, - card7 INT, - startCards INT, + foldToStreet1CBChance INT, + foldToStreet1CBDone INT, + foldToStreet2CBChance INT, + foldToStreet2CBDone INT, + foldToStreet3CBChance INT, + foldToStreet3CBDone INT, + foldToStreet4CBChance INT, + foldToStreet4CBDone INT, - ante INT, - winnings INT NOT NULL, - rake INT NOT NULL, - totalProfit INT, - comment TEXT, - commentTs REAL, - tourneysPlayersId INT, - tourneyTypeId INT NOT NULL DEFAULT 1, + totalProfit INT, + + street1CheckCallRaiseChance INT, + street1CheckCallRaiseDone INT, + street2CheckCallRaiseChance INT, + street2CheckCallRaiseDone INT, + street3CheckCallRaiseChance INT, + street3CheckCallRaiseDone INT, + street4CheckCallRaiseChance INT, + street4CheckCallRaiseDone INT, - wonWhenSeenStreet1 REAL, - wonWhenSeenStreet2 REAL, - wonWhenSeenStreet3 REAL, - wonWhenSeenStreet4 REAL, - wonAtSD REAL, + street0Calls INT, + street1Calls INT, + street2Calls INT, + street3Calls INT, + street4Calls INT, + street0Bets INT, + street1Bets INT, + street2Bets INT, + street3Bets INT, + street4Bets INT, + street0Raises INT, + street1Raises INT, + street2Raises INT, + street3Raises INT, + street4Raises INT) - street0VPI INT, - street0Aggr INT, - street0_3BChance INT, - street0_3BDone INT, - street0_4BChance INT, - street0_4BDone INT, - other3BStreet0 INT, - other4BStreet0 INT, + ENGINE=INNODB""" + elif db_server == 'postgresql': + self.query['createHudCacheTable'] = """CREATE TABLE HudCache ( + id BIGSERIAL, PRIMARY KEY (id), + gametypeId INT, FOREIGN KEY (gametypeId) REFERENCES Gametypes(id), + playerId INT, FOREIGN KEY (playerId) REFERENCES Players(id), + activeSeats SMALLINT, + position CHAR(1), + tourneyTypeId INT DEFAULT 1, FOREIGN KEY (tourneyTypeId) REFERENCES TourneyTypes(id), + styleKey CHAR(7) NOT NULL, /* 1st char is style (A/T/H/S), other 6 are the key */ + HDs INT, - street1Seen INT, - street2Seen INT, - street3Seen INT, - street4Seen INT, - sawShowdown INT, + wonWhenSeenStreet1 FLOAT, + wonWhenSeenStreet2 FLOAT, + wonWhenSeenStreet3 FLOAT, + wonWhenSeenStreet4 FLOAT, + wonAtSD FLOAT, - street1Aggr INT, - street2Aggr INT, - street3Aggr INT, - street4Aggr INT, + street0VPI INT, + street0Aggr INT, + street0_3BChance INT, + street0_3BDone INT, + street0_4BChance INT, + street0_4BDone INT, + other3BStreet0 INT, + other4BStreet0 INT, - otherRaisedStreet0 INT, - otherRaisedStreet1 INT, - otherRaisedStreet2 INT, - otherRaisedStreet3 INT, - otherRaisedStreet4 INT, - foldToOtherRaisedStreet0 INT, - foldToOtherRaisedStreet1 INT, - foldToOtherRaisedStreet2 INT, - foldToOtherRaisedStreet3 INT, - foldToOtherRaisedStreet4 INT, + street1Seen INT, + street2Seen INT, + street3Seen INT, + street4Seen INT, + sawShowdown INT, + street1Aggr INT, + street2Aggr INT, + street3Aggr INT, + street4Aggr INT, - stealAttemptChance INT, - stealAttempted INT, - foldBbToStealChance INT, - foldedBbToSteal INT, - foldSbToStealChance INT, - foldedSbToSteal INT, + otherRaisedStreet0 INT, + otherRaisedStreet1 INT, + otherRaisedStreet2 INT, + otherRaisedStreet3 INT, + otherRaisedStreet4 INT, + foldToOtherRaisedStreet0 INT, + foldToOtherRaisedStreet1 INT, + foldToOtherRaisedStreet2 INT, + foldToOtherRaisedStreet3 INT, + foldToOtherRaisedStreet4 INT, - street1CBChance INT, - street1CBDone INT, - street2CBChance INT, - street2CBDone INT, - street3CBChance INT, - street3CBDone INT, - street4CBChance INT, - street4CBDone INT, + stealAttemptChance INT, + stealAttempted INT, + foldBbToStealChance INT, + foldedBbToSteal INT, + foldSbToStealChance INT, + foldedSbToSteal INT, - foldToStreet1CBChance INT, - foldToStreet1CBDone INT, - foldToStreet2CBChance INT, - foldToStreet2CBDone INT, - foldToStreet3CBChance INT, - foldToStreet3CBDone INT, - foldToStreet4CBChance INT, - foldToStreet4CBDone INT, + street1CBChance INT, + street1CBDone INT, + street2CBChance INT, + street2CBDone INT, + street3CBChance INT, + street3CBDone INT, + street4CBChance INT, + street4CBDone INT, - street1CheckCallRaiseChance INT, - street1CheckCallRaiseDone INT, - street2CheckCallRaiseChance INT, - street2CheckCallRaiseDone INT, - street3CheckCallRaiseChance INT, - street3CheckCallRaiseDone INT, - street4CheckCallRaiseChance INT, - street4CheckCallRaiseDone INT, + foldToStreet1CBChance INT, + foldToStreet1CBDone INT, + foldToStreet2CBChance INT, + foldToStreet2CBDone INT, + foldToStreet3CBChance INT, + foldToStreet3CBDone INT, + foldToStreet4CBChance INT, + foldToStreet4CBDone INT, - street0Calls INT, - street1Calls INT, - street2Calls INT, - street3Calls INT, - street4Calls INT, - street0Bets INT, - street1Bets INT, - street2Bets INT, - street3Bets INT, - street4Bets INT, - street0Raises INT, - street1Raises INT, - street2Raises INT, - street3Raises INT, - street4Raises INT, + totalProfit INT, - actionString REAL) - """ + street1CheckCallRaiseChance INT, + street1CheckCallRaiseDone INT, + street2CheckCallRaiseChance INT, + street2CheckCallRaiseDone INT, + street3CheckCallRaiseChance INT, + street3CheckCallRaiseDone INT, + street4CheckCallRaiseChance INT, + street4CheckCallRaiseDone INT, + + street0Calls INT, + street1Calls INT, + street2Calls INT, + street3Calls INT, + street4Calls INT, + street0Bets INT, + street1Bets INT, + street2Bets INT, + street3Bets INT, + street4Bets INT, + street0Raises INT, + street1Raises INT, + street2Raises INT, + street3Raises INT, + street4Raises INT) + """ + elif db_server == 'sqlite': + self.query['createHudCacheTable'] = """CREATE TABLE HudCache ( + id INTEGER PRIMARY KEY, + gametypeId INT, + playerId INT, + activeSeats INT, + position TEXT, + tourneyTypeId INT DEFAULT 1, + styleKey TEXT NOT NULL, /* 1st char is style (A/T/H/S), other 6 are the key */ + HDs INT, + + wonWhenSeenStreet1 REAL, + wonWhenSeenStreet2 REAL, + wonWhenSeenStreet3 REAL, + wonWhenSeenStreet4 REAL, + wonAtSD REAL, + + street0VPI INT, + street0Aggr INT, + street0_3BChance INT, + street0_3BDone INT, + street0_4BChance INT, + street0_4BDone INT, + other3BStreet0 INT, + other4BStreet0 INT, + + street1Seen INT, + street2Seen INT, + street3Seen INT, + street4Seen INT, + sawShowdown INT, + street1Aggr INT, + street2Aggr INT, + street3Aggr INT, + street4Aggr INT, + + otherRaisedStreet0 INT, + otherRaisedStreet1 INT, + otherRaisedStreet2 INT, + otherRaisedStreet3 INT, + otherRaisedStreet4 INT, + foldToOtherRaisedStreet0 INT, + foldToOtherRaisedStreet1 INT, + foldToOtherRaisedStreet2 INT, + foldToOtherRaisedStreet3 INT, + foldToOtherRaisedStreet4 INT, + + stealAttemptChance INT, + stealAttempted INT, + foldBbToStealChance INT, + foldedBbToSteal INT, + foldSbToStealChance INT, + foldedSbToSteal INT, + + street1CBChance INT, + street1CBDone INT, + street2CBChance INT, + street2CBDone INT, + street3CBChance INT, + street3CBDone INT, + street4CBChance INT, + street4CBDone INT, + + foldToStreet1CBChance INT, + foldToStreet1CBDone INT, + foldToStreet2CBChance INT, + foldToStreet2CBDone INT, + foldToStreet3CBChance INT, + foldToStreet3CBDone INT, + foldToStreet4CBChance INT, + foldToStreet4CBDone INT, + + totalProfit INT, + + street1CheckCallRaiseChance INT, + street1CheckCallRaiseDone INT, + street2CheckCallRaiseChance INT, + street2CheckCallRaiseDone INT, + street3CheckCallRaiseChance INT, + street3CheckCallRaiseDone INT, + street4CheckCallRaiseChance INT, + street4CheckCallRaiseDone INT, + + street0Calls INT, + street1Calls INT, + street2Calls INT, + street3Calls INT, + street4Calls INT, + street0Bets INT, + street1Bets INT, + street2Bets INT, + street3Bets INT, + street4Bets INT, + street0Raises INT, + street1Raises INT, + street2Raises INT, + street3Raises INT, + street4Raises INT) + """ - ################################ - # Create TourneysPlayers - ################################ + if db_server == 'mysql': + self.query['addTourneyIndex'] = """ALTER TABLE Tourneys ADD UNIQUE INDEX siteTourneyNo(siteTourneyNo, tourneyTypeId)""" + elif db_server == 'postgresql': + self.query['addTourneyIndex'] = """CREATE UNIQUE INDEX siteTourneyNo ON Tourneys (siteTourneyNo, tourneyTypeId)""" + elif db_server == 'sqlite': + self.query['addTourneyIndex'] = """CREATE UNIQUE INDEX siteTourneyNo ON Tourneys (siteTourneyNo, tourneyTypeId)""" - if db_server == 'mysql': - self.query['createTourneysPlayersTable'] = """CREATE TABLE TourneysPlayers ( - id BIGINT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), - tourneyId INT UNSIGNED NOT NULL, FOREIGN KEY (tourneyId) REFERENCES Tourneys(id), - playerId INT UNSIGNED NOT NULL, FOREIGN KEY (playerId) REFERENCES Players(id), - payinAmount INT NOT NULL, - rank INT NOT NULL, - winnings INT NOT NULL, - nbRebuys INT DEFAULT 0, - nbAddons INT DEFAULT 0, - nbKO INT DEFAULT 0, - comment TEXT, - commentTs DATETIME) - ENGINE=INNODB""" - elif db_server == 'postgresql': - self.query['createTourneysPlayersTable'] = """CREATE TABLE TourneysPlayers ( - id BIGSERIAL, PRIMARY KEY (id), - tourneyId INT, FOREIGN KEY (tourneyId) REFERENCES Tourneys(id), - playerId INT, FOREIGN KEY (playerId) REFERENCES Players(id), - payinAmount INT, - rank INT, - winnings INT, - nbRebuys INT DEFAULT 0, - nbAddons INT DEFAULT 0, - nbKO INT DEFAULT 0, - comment TEXT, - commentTs timestamp without time zone)""" - elif db_server == 'sqlite': - self.query['createTourneysPlayersTable'] = """CREATE TABLE TourneysPlayers ( - id INT PRIMARY KEY, - tourneyId INT, - playerId INT, - payinAmount INT, - rank INT, - winnings INT, - nbRebuys INT DEFAULT 0, - nbAddons INT DEFAULT 0, - nbKO INT DEFAULT 0, - comment TEXT, - commentTs timestamp without time zone, - FOREIGN KEY (tourneyId) REFERENCES Tourneys(id), - FOREIGN KEY (playerId) REFERENCES Players(id) - )""" + if db_server == 'mysql': + self.query['addHandsIndex'] = """ALTER TABLE Hands ADD UNIQUE INDEX siteHandNo(siteHandNo, gameTypeId)""" + elif db_server == 'postgresql': + self.query['addHandsIndex'] = """CREATE UNIQUE INDEX siteHandNo ON Hands (siteHandNo, gameTypeId)""" + elif db_server == 'sqlite': + self.query['addHandsIndex'] = """CREATE UNIQUE INDEX siteHandNo ON Hands (siteHandNo, gameTypeId)""" + if db_server == 'mysql': + self.query['addPlayersIndex'] = """ALTER TABLE Players ADD UNIQUE INDEX name(name, siteId)""" + elif db_server == 'postgresql': + self.query['addPlayersIndex'] = """CREATE UNIQUE INDEX name ON Players (name, siteId)""" + elif db_server == 'sqlite': + self.query['addPlayersIndex'] = """CREATE UNIQUE INDEX name ON Players (name, siteId)""" - ################################ - # Create HandsActions - ################################ + if db_server == 'mysql': + self.query['addTPlayersIndex'] = """ALTER TABLE TourneysPlayers ADD UNIQUE INDEX tourneyId(tourneyId, playerId)""" + elif db_server == 'postgresql': + self.query['addTPlayersIndex'] = """CREATE UNIQUE INDEX tourneyId ON TourneysPlayers (tourneyId, playerId)""" + elif db_server == 'sqlite': + self.query['addTPlayersIndex'] = """CREATE UNIQUE INDEX tourneyId ON TourneysPlayers (tourneyId, playerId)""" - if db_server == 'mysql': - self.query['createHandsActionsTable'] = """CREATE TABLE HandsActions ( - id BIGINT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), - handsPlayerId BIGINT UNSIGNED NOT NULL, FOREIGN KEY (handsPlayerId) REFERENCES HandsPlayers(id), - street SMALLINT NOT NULL, - actionNo SMALLINT NOT NULL, - action CHAR(5) NOT NULL, - allIn BOOLEAN NOT NULL, - amount INT NOT NULL, - comment TEXT, - commentTs DATETIME) - ENGINE=INNODB""" - elif db_server == 'postgresql': - self.query['createHandsActionsTable'] = """CREATE TABLE HandsActions ( - id BIGSERIAL, PRIMARY KEY (id), - handsPlayerId BIGINT, FOREIGN KEY (handsPlayerId) REFERENCES HandsPlayers(id), - street SMALLINT, - actionNo SMALLINT, - action CHAR(5), - allIn BOOLEAN, - amount INT, - comment TEXT, - commentTs timestamp without time zone)""" - elif db_server == 'sqlite': - self.query['createHandsActionsTable'] = """CREATE TABLE HandsActions ( - id INT PRIMARY KEY, - handsPlayerId BIGINT, - street SMALLINT, - actionNo SMALLINT, - action CHAR(5), - allIn INT, - amount INT, - comment TEXT, - commentTs timestamp without time zone, - FOREIGN KEY (handsPlayerId) REFERENCES HandsPlayers(id) - )""" + if db_server == 'mysql': + self.query['addTTypesIndex'] = """ALTER TABLE TourneyTypes ADD UNIQUE INDEX tourneytypes_all(buyin, fee + , maxSeats, knockout, rebuyOrAddon, speed, headsUp, shootout, matrix, sng)""" + elif db_server == 'postgresql': + self.query['addTTypesIndex'] = """CREATE UNIQUE INDEX tourneyTypes_all ON TourneyTypes (buyin, fee + , maxSeats, knockout, rebuyOrAddon, speed, headsUp, shootout, matrix, sng)""" + elif db_server == 'sqlite': + self.query['addTTypesIndex'] = """CREATE UNIQUE INDEX tourneyTypes_all ON TourneyTypes (buyin, fee + , maxSeats, knockout, rebuyOrAddon, speed, headsUp, shootout, matrix, sng)""" + self.query['get_last_hand'] = "select max(id) from Hands" - ################################ - # Create HudCache - ################################ + self.query['get_player_id'] = """ + select Players.id AS player_id + from Players, Sites + where Players.name = %s + and Sites.name = %s + and Players.siteId = Sites.id + """ - if db_server == 'mysql': - self.query['createHudCacheTable'] = """CREATE TABLE HudCache ( - id BIGINT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), - gametypeId SMALLINT UNSIGNED NOT NULL, FOREIGN KEY (gametypeId) REFERENCES Gametypes(id), - playerId INT UNSIGNED NOT NULL, FOREIGN KEY (playerId) REFERENCES Players(id), - activeSeats SMALLINT NOT NULL, - position CHAR(1), - tourneyTypeId SMALLINT UNSIGNED NOT NULL DEFAULT 1, FOREIGN KEY (tourneyTypeId) REFERENCES TourneyTypes(id), - styleKey CHAR(7) NOT NULL, /* 1st char is style (A/T/H/S), other 6 are the key */ - HDs INT NOT NULL, + self.query['get_player_names'] = """ + select p.name + from Players p + where lower(p.name) like lower(%s) + and (p.siteId = %s or %s = -1) + """ - wonWhenSeenStreet1 FLOAT, - wonWhenSeenStreet2 FLOAT, - wonWhenSeenStreet3 FLOAT, - wonWhenSeenStreet4 FLOAT, - wonAtSD FLOAT, + self.query['getSiteId'] = """SELECT id from Sites where name = %s""" - street0VPI INT, - street0Aggr INT, - street0_3BChance INT, - street0_3BDone INT, - street0_4BChance INT, - street0_4BDone INT, - other3BStreet0 INT, - other4BStreet0 INT, - - street1Seen INT, - street2Seen INT, - street3Seen INT, - street4Seen INT, - sawShowdown INT, - - street1Aggr INT, - street2Aggr INT, - street3Aggr INT, - street4Aggr INT, - - otherRaisedStreet0 INT, - otherRaisedStreet1 INT, - otherRaisedStreet2 INT, - otherRaisedStreet3 INT, - otherRaisedStreet4 INT, - foldToOtherRaisedStreet0 INT, - foldToOtherRaisedStreet1 INT, - foldToOtherRaisedStreet2 INT, - foldToOtherRaisedStreet3 INT, - foldToOtherRaisedStreet4 INT, - - stealAttemptChance INT, - stealAttempted INT, - foldBbToStealChance INT, - foldedBbToSteal INT, - foldSbToStealChance INT, - foldedSbToSteal INT, - - street1CBChance INT, - street1CBDone INT, - street2CBChance INT, - street2CBDone INT, - street3CBChance INT, - street3CBDone INT, - street4CBChance INT, - street4CBDone INT, - - foldToStreet1CBChance INT, - foldToStreet1CBDone INT, - foldToStreet2CBChance INT, - foldToStreet2CBDone INT, - foldToStreet3CBChance INT, - foldToStreet3CBDone INT, - foldToStreet4CBChance INT, - foldToStreet4CBDone INT, - - totalProfit INT, - - street1CheckCallRaiseChance INT, - street1CheckCallRaiseDone INT, - street2CheckCallRaiseChance INT, - street2CheckCallRaiseDone INT, - street3CheckCallRaiseChance INT, - street3CheckCallRaiseDone INT, - street4CheckCallRaiseChance INT, - street4CheckCallRaiseDone INT, - - street0Calls INT, - street1Calls INT, - street2Calls INT, - street3Calls INT, - street4Calls INT, - street0Bets INT, - street1Bets INT, - street2Bets INT, - street3Bets INT, - street4Bets INT, - street0Raises INT, - street1Raises INT, - street2Raises INT, - street3Raises INT, - street4Raises INT) - - ENGINE=INNODB""" - elif db_server == 'postgresql': - self.query['createHudCacheTable'] = """CREATE TABLE HudCache ( - id BIGSERIAL, PRIMARY KEY (id), - gametypeId INT, FOREIGN KEY (gametypeId) REFERENCES Gametypes(id), - playerId INT, FOREIGN KEY (playerId) REFERENCES Players(id), - activeSeats SMALLINT, - position CHAR(1), - tourneyTypeId INT DEFAULT 1, FOREIGN KEY (tourneyTypeId) REFERENCES TourneyTypes(id), - styleKey CHAR(7) NOT NULL, /* 1st char is style (A/T/H/S), other 6 are the key */ - HDs INT, - - wonWhenSeenStreet1 FLOAT, - wonWhenSeenStreet2 FLOAT, - wonWhenSeenStreet3 FLOAT, - wonWhenSeenStreet4 FLOAT, - wonAtSD FLOAT, - - street0VPI INT, - street0Aggr INT, - street0_3BChance INT, - street0_3BDone INT, - street0_4BChance INT, - street0_4BDone INT, - other3BStreet0 INT, - other4BStreet0 INT, - - street1Seen INT, - street2Seen INT, - street3Seen INT, - street4Seen INT, - sawShowdown INT, - street1Aggr INT, - street2Aggr INT, - street3Aggr INT, - street4Aggr INT, - - otherRaisedStreet0 INT, - otherRaisedStreet1 INT, - otherRaisedStreet2 INT, - otherRaisedStreet3 INT, - otherRaisedStreet4 INT, - foldToOtherRaisedStreet0 INT, - foldToOtherRaisedStreet1 INT, - foldToOtherRaisedStreet2 INT, - foldToOtherRaisedStreet3 INT, - foldToOtherRaisedStreet4 INT, - - stealAttemptChance INT, - stealAttempted INT, - foldBbToStealChance INT, - foldedBbToSteal INT, - foldSbToStealChance INT, - foldedSbToSteal INT, - - street1CBChance INT, - street1CBDone INT, - street2CBChance INT, - street2CBDone INT, - street3CBChance INT, - street3CBDone INT, - street4CBChance INT, - street4CBDone INT, - - foldToStreet1CBChance INT, - foldToStreet1CBDone INT, - foldToStreet2CBChance INT, - foldToStreet2CBDone INT, - foldToStreet3CBChance INT, - foldToStreet3CBDone INT, - foldToStreet4CBChance INT, - foldToStreet4CBDone INT, - - totalProfit INT, - - street1CheckCallRaiseChance INT, - street1CheckCallRaiseDone INT, - street2CheckCallRaiseChance INT, - street2CheckCallRaiseDone INT, - street3CheckCallRaiseChance INT, - street3CheckCallRaiseDone INT, - street4CheckCallRaiseChance INT, - street4CheckCallRaiseDone INT, - - street0Calls INT, - street1Calls INT, - street2Calls INT, - street3Calls INT, - street4Calls INT, - street0Bets INT, - street1Bets INT, - street2Bets INT, - street3Bets INT, - street4Bets INT, - street0Raises INT, - street1Raises INT, - street2Raises INT, - street3Raises INT, - street4Raises INT) - """ - elif db_server == 'sqlite': - self.query['createHudCacheTable'] = """CREATE TABLE HudCache ( - id INTEGER PRIMARY KEY, - gametypeId INT, - playerId INT, - activeSeats INT, - position TEXT, - tourneyTypeId INT DEFAULT 1, - styleKey TEXT NOT NULL, /* 1st char is style (A/T/H/S), other 6 are the key */ - HDs INT, - - wonWhenSeenStreet1 REAL, - wonWhenSeenStreet2 REAL, - wonWhenSeenStreet3 REAL, - wonWhenSeenStreet4 REAL, - wonAtSD REAL, - - street0VPI INT, - street0Aggr INT, - street0_3BChance INT, - street0_3BDone INT, - street0_4BChance INT, - street0_4BDone INT, - other3BStreet0 INT, - other4BStreet0 INT, - - street1Seen INT, - street2Seen INT, - street3Seen INT, - street4Seen INT, - sawShowdown INT, - street1Aggr INT, - street2Aggr INT, - street3Aggr INT, - street4Aggr INT, - - otherRaisedStreet0 INT, - otherRaisedStreet1 INT, - otherRaisedStreet2 INT, - otherRaisedStreet3 INT, - otherRaisedStreet4 INT, - foldToOtherRaisedStreet0 INT, - foldToOtherRaisedStreet1 INT, - foldToOtherRaisedStreet2 INT, - foldToOtherRaisedStreet3 INT, - foldToOtherRaisedStreet4 INT, - - stealAttemptChance INT, - stealAttempted INT, - foldBbToStealChance INT, - foldedBbToSteal INT, - foldSbToStealChance INT, - foldedSbToSteal INT, - - street1CBChance INT, - street1CBDone INT, - street2CBChance INT, - street2CBDone INT, - street3CBChance INT, - street3CBDone INT, - street4CBChance INT, - street4CBDone INT, - - foldToStreet1CBChance INT, - foldToStreet1CBDone INT, - foldToStreet2CBChance INT, - foldToStreet2CBDone INT, - foldToStreet3CBChance INT, - foldToStreet3CBDone INT, - foldToStreet4CBChance INT, - foldToStreet4CBDone INT, - - totalProfit INT, - - street1CheckCallRaiseChance INT, - street1CheckCallRaiseDone INT, - street2CheckCallRaiseChance INT, - street2CheckCallRaiseDone INT, - street3CheckCallRaiseChance INT, - street3CheckCallRaiseDone INT, - street4CheckCallRaiseChance INT, - street4CheckCallRaiseDone INT, - - street0Calls INT, - street1Calls INT, - street2Calls INT, - street3Calls INT, - street4Calls INT, - street0Bets INT, - street1Bets INT, - street2Bets INT, - street3Bets INT, - street4Bets INT, - street0Raises INT, - street1Raises INT, - street2Raises INT, - street3Raises INT, - street4Raises INT) - """ - - - if db_server == 'mysql': - self.query['addTourneyIndex'] = """ALTER TABLE Tourneys ADD UNIQUE INDEX siteTourneyNo(siteTourneyNo, tourneyTypeId)""" - elif db_server == 'postgresql': - self.query['addTourneyIndex'] = """CREATE UNIQUE INDEX siteTourneyNo ON Tourneys (siteTourneyNo, tourneyTypeId)""" - elif db_server == 'sqlite': - self.query['addTourneyIndex'] = """CREATE UNIQUE INDEX siteTourneyNo ON Tourneys (siteTourneyNo, tourneyTypeId)""" - - if db_server == 'mysql': - self.query['addHandsIndex'] = """ALTER TABLE Hands ADD UNIQUE INDEX siteHandNo(siteHandNo, gameTypeId)""" - elif db_server == 'postgresql': - self.query['addHandsIndex'] = """CREATE UNIQUE INDEX siteHandNo ON Hands (siteHandNo, gameTypeId)""" - elif db_server == 'sqlite': - self.query['addHandsIndex'] = """CREATE UNIQUE INDEX siteHandNo ON Hands (siteHandNo, gameTypeId)""" - - if db_server == 'mysql': - self.query['addPlayersIndex'] = """ALTER TABLE Players ADD UNIQUE INDEX name(name, siteId)""" - elif db_server == 'postgresql': - self.query['addPlayersIndex'] = """CREATE UNIQUE INDEX name ON Players (name, siteId)""" - elif db_server == 'sqlite': - self.query['addPlayersIndex'] = """CREATE UNIQUE INDEX name ON Players (name, siteId)""" - - if db_server == 'mysql': - self.query['addTPlayersIndex'] = """ALTER TABLE TourneysPlayers ADD UNIQUE INDEX tourneyId(tourneyId, playerId)""" - elif db_server == 'postgresql': - self.query['addTPlayersIndex'] = """CREATE UNIQUE INDEX tourneyId ON TourneysPlayers (tourneyId, playerId)""" - elif db_server == 'sqlite': - self.query['addTPlayersIndex'] = """CREATE UNIQUE INDEX tourneyId ON TourneysPlayers (tourneyId, playerId)""" - - if db_server == 'mysql': - self.query['addTTypesIndex'] = """ALTER TABLE TourneyTypes ADD UNIQUE INDEX tourneytypes_all(buyin, fee - , maxSeats, knockout, rebuyOrAddon, speed, headsUp, shootout, matrix, sng)""" - elif db_server == 'postgresql': - self.query['addTTypesIndex'] = """CREATE UNIQUE INDEX tourneyTypes_all ON TourneyTypes (buyin, fee - , maxSeats, knockout, rebuyOrAddon, speed, headsUp, shootout, matrix, sng)""" - elif db_server == 'sqlite': - self.query['addTTypesIndex'] = """CREATE UNIQUE INDEX tourneyTypes_all ON TourneyTypes (buyin, fee - , maxSeats, knockout, rebuyOrAddon, speed, headsUp, shootout, matrix, sng)""" - - self.query['get_last_hand'] = "select max(id) from Hands" - - self.query['get_player_id'] = """ - select Players.id AS player_id - from Players, Sites - where Players.name = %s - and Sites.name = %s - and Players.siteId = Sites.id - """ - - self.query['get_player_names'] = """ - select p.name - from Players p - where lower(p.name) like lower(%s) - and (p.siteId = %s or %s = -1) - """ - - self.query['getSiteId'] = """SELECT id from Sites where name = %s""" - - self.query['get_stats_from_hand'] = """ - SELECT hc.playerId AS player_id, - hp.seatNo AS seat, - p.name AS screen_name, - sum(hc.HDs) AS n, - sum(hc.street0VPI) AS vpip, - sum(hc.street0Aggr) AS pfr, - sum(hc.street0_3BChance) AS TB_opp_0, - sum(hc.street0_3BDone) AS TB_0, - sum(hc.street1Seen) AS saw_f, - sum(hc.street1Seen) AS saw_1, - sum(hc.street2Seen) AS saw_2, - sum(hc.street3Seen) AS saw_3, - sum(hc.street4Seen) AS saw_4, - sum(hc.sawShowdown) AS sd, - sum(hc.street1Aggr) AS aggr_1, - sum(hc.street2Aggr) AS aggr_2, - sum(hc.street3Aggr) AS aggr_3, - sum(hc.street4Aggr) AS aggr_4, - sum(hc.otherRaisedStreet1) AS was_raised_1, - sum(hc.otherRaisedStreet2) AS was_raised_2, - sum(hc.otherRaisedStreet3) AS was_raised_3, - sum(hc.otherRaisedStreet4) AS was_raised_4, - sum(hc.foldToOtherRaisedStreet1) AS f_freq_1, - sum(hc.foldToOtherRaisedStreet2) AS f_freq_2, - sum(hc.foldToOtherRaisedStreet3) AS f_freq_3, - sum(hc.foldToOtherRaisedStreet4) AS f_freq_4, - sum(hc.wonWhenSeenStreet1) AS w_w_s_1, - sum(hc.wonAtSD) AS wmsd, - sum(hc.stealAttemptChance) AS steal_opp, - sum(hc.stealAttempted) AS steal, - sum(hc.foldSbToStealChance) AS SBstolen, - sum(hc.foldedSbToSteal) AS SBnotDef, - sum(hc.foldBbToStealChance) AS BBstolen, - sum(hc.foldedBbToSteal) AS BBnotDef, - sum(hc.street1CBChance) AS CB_opp_1, - sum(hc.street1CBDone) AS CB_1, - sum(hc.street2CBChance) AS CB_opp_2, - sum(hc.street2CBDone) AS CB_2, - sum(hc.street3CBChance) AS CB_opp_3, - sum(hc.street3CBDone) AS CB_3, - sum(hc.street4CBChance) AS CB_opp_4, - sum(hc.street4CBDone) AS CB_4, - sum(hc.foldToStreet1CBChance) AS f_cb_opp_1, - sum(hc.foldToStreet1CBDone) AS f_cb_1, - sum(hc.foldToStreet2CBChance) AS f_cb_opp_2, - sum(hc.foldToStreet2CBDone) AS f_cb_2, - sum(hc.foldToStreet3CBChance) AS f_cb_opp_3, - sum(hc.foldToStreet3CBDone) AS f_cb_3, - sum(hc.foldToStreet4CBChance) AS f_cb_opp_4, - sum(hc.foldToStreet4CBDone) AS f_cb_4, - sum(hc.totalProfit) AS net, - sum(hc.street1CheckCallRaiseChance) AS ccr_opp_1, - sum(hc.street1CheckCallRaiseDone) AS ccr_1, - sum(hc.street2CheckCallRaiseChance) AS ccr_opp_2, - sum(hc.street2CheckCallRaiseDone) AS ccr_2, - sum(hc.street3CheckCallRaiseChance) AS ccr_opp_3, - sum(hc.street3CheckCallRaiseDone) AS ccr_3, - sum(hc.street4CheckCallRaiseChance) AS ccr_opp_4, - sum(hc.street4CheckCallRaiseDone) AS ccr_4 - FROM Hands h - INNER JOIN HandsPlayers hp ON (hp.handId = h.id) - INNER JOIN HudCache hc ON ( hc.PlayerId = hp.PlayerId+0 - AND hc.gametypeId+0 = h.gametypeId+0) - INNER JOIN Players p ON (p.id = hp.PlayerId+0) - WHERE h.id = %s - AND hc.styleKey > %s - /* styleKey is currently 'd' (for date) followed by a yyyymmdd - date key. Set it to 0000000 or similar to get all records */ - /* also check activeseats here even if only 3 groups eg 2-3/4-6/7+ - e.g. could use a multiplier: - AND h.seats > X / 1.25 and hp.seats < X * 1.25 - where X is the number of active players at the current table (and - 1.25 would be a config value so user could change it) - */ - GROUP BY hc.PlayerId, hp.seatNo, p.name - """ + self.query['get_stats_from_hand'] = """ + SELECT hc.playerId AS player_id, + hp.seatNo AS seat, + p.name AS screen_name, + sum(hc.HDs) AS n, + sum(hc.street0VPI) AS vpip, + sum(hc.street0Aggr) AS pfr, + sum(hc.street0_3BChance) AS TB_opp_0, + sum(hc.street0_3BDone) AS TB_0, + sum(hc.street1Seen) AS saw_f, + sum(hc.street1Seen) AS saw_1, + sum(hc.street2Seen) AS saw_2, + sum(hc.street3Seen) AS saw_3, + sum(hc.street4Seen) AS saw_4, + sum(hc.sawShowdown) AS sd, + sum(hc.street1Aggr) AS aggr_1, + sum(hc.street2Aggr) AS aggr_2, + sum(hc.street3Aggr) AS aggr_3, + sum(hc.street4Aggr) AS aggr_4, + sum(hc.otherRaisedStreet1) AS was_raised_1, + sum(hc.otherRaisedStreet2) AS was_raised_2, + sum(hc.otherRaisedStreet3) AS was_raised_3, + sum(hc.otherRaisedStreet4) AS was_raised_4, + sum(hc.foldToOtherRaisedStreet1) AS f_freq_1, + sum(hc.foldToOtherRaisedStreet2) AS f_freq_2, + sum(hc.foldToOtherRaisedStreet3) AS f_freq_3, + sum(hc.foldToOtherRaisedStreet4) AS f_freq_4, + sum(hc.wonWhenSeenStreet1) AS w_w_s_1, + sum(hc.wonAtSD) AS wmsd, + sum(hc.stealAttemptChance) AS steal_opp, + sum(hc.stealAttempted) AS steal, + sum(hc.foldSbToStealChance) AS SBstolen, + sum(hc.foldedSbToSteal) AS SBnotDef, + sum(hc.foldBbToStealChance) AS BBstolen, + sum(hc.foldedBbToSteal) AS BBnotDef, + sum(hc.street1CBChance) AS CB_opp_1, + sum(hc.street1CBDone) AS CB_1, + sum(hc.street2CBChance) AS CB_opp_2, + sum(hc.street2CBDone) AS CB_2, + sum(hc.street3CBChance) AS CB_opp_3, + sum(hc.street3CBDone) AS CB_3, + sum(hc.street4CBChance) AS CB_opp_4, + sum(hc.street4CBDone) AS CB_4, + sum(hc.foldToStreet1CBChance) AS f_cb_opp_1, + sum(hc.foldToStreet1CBDone) AS f_cb_1, + sum(hc.foldToStreet2CBChance) AS f_cb_opp_2, + sum(hc.foldToStreet2CBDone) AS f_cb_2, + sum(hc.foldToStreet3CBChance) AS f_cb_opp_3, + sum(hc.foldToStreet3CBDone) AS f_cb_3, + sum(hc.foldToStreet4CBChance) AS f_cb_opp_4, + sum(hc.foldToStreet4CBDone) AS f_cb_4, + sum(hc.totalProfit) AS net, + sum(hc.street1CheckCallRaiseChance) AS ccr_opp_1, + sum(hc.street1CheckCallRaiseDone) AS ccr_1, + sum(hc.street2CheckCallRaiseChance) AS ccr_opp_2, + sum(hc.street2CheckCallRaiseDone) AS ccr_2, + sum(hc.street3CheckCallRaiseChance) AS ccr_opp_3, + sum(hc.street3CheckCallRaiseDone) AS ccr_3, + sum(hc.street4CheckCallRaiseChance) AS ccr_opp_4, + sum(hc.street4CheckCallRaiseDone) AS ccr_4 + FROM Hands h + INNER JOIN HandsPlayers hp ON (hp.handId = h.id) + INNER JOIN HudCache hc ON ( hc.PlayerId = hp.PlayerId+0 + AND hc.gametypeId+0 = h.gametypeId+0) + INNER JOIN Players p ON (p.id = hp.PlayerId+0) + WHERE h.id = %s + AND hc.styleKey > %s + /* styleKey is currently 'd' (for date) followed by a yyyymmdd + date key. Set it to 0000000 or similar to get all records */ + /* also check activeseats here even if only 3 groups eg 2-3/4-6/7+ + e.g. could use a multiplier: + AND h.seats > X / 1.25 and hp.seats < X * 1.25 + where X is the number of active players at the current table (and + 1.25 would be a config value so user could change it) + */ + GROUP BY hc.PlayerId, hp.seatNo, p.name + """ # same as above except stats are aggregated for all blind/limit levels - self.query['get_stats_from_hand_aggregated'] = """ - SELECT hc.playerId AS player_id, - max(case when hc.gametypeId = h.gametypeId - then hp.seatNo - else -1 - end) AS seat, - p.name AS screen_name, - sum(hc.HDs) AS n, - sum(hc.street0VPI) AS vpip, - sum(hc.street0Aggr) AS pfr, - sum(hc.street0_3BChance) AS TB_opp_0, - sum(hc.street0_3BDone) AS TB_0, - sum(hc.street1Seen) AS saw_f, - sum(hc.street1Seen) AS saw_1, - sum(hc.street2Seen) AS saw_2, - sum(hc.street3Seen) AS saw_3, - sum(hc.street4Seen) AS saw_4, - sum(hc.sawShowdown) AS sd, - sum(hc.street1Aggr) AS aggr_1, - sum(hc.street2Aggr) AS aggr_2, - sum(hc.street3Aggr) AS aggr_3, - sum(hc.street4Aggr) AS aggr_4, - sum(hc.otherRaisedStreet1) AS was_raised_1, - sum(hc.otherRaisedStreet2) AS was_raised_2, - sum(hc.otherRaisedStreet3) AS was_raised_3, - sum(hc.otherRaisedStreet4) AS was_raised_4, - sum(hc.foldToOtherRaisedStreet1) AS f_freq_1, - sum(hc.foldToOtherRaisedStreet2) AS f_freq_2, - sum(hc.foldToOtherRaisedStreet3) AS f_freq_3, - sum(hc.foldToOtherRaisedStreet4) AS f_freq_4, - sum(hc.wonWhenSeenStreet1) AS w_w_s_1, - sum(hc.wonAtSD) AS wmsd, - sum(hc.stealAttemptChance) AS steal_opp, - sum(hc.stealAttempted) AS steal, - sum(hc.foldSbToStealChance) AS SBstolen, - sum(hc.foldedSbToSteal) AS SBnotDef, - sum(hc.foldBbToStealChance) AS BBstolen, - sum(hc.foldedBbToSteal) AS BBnotDef, - sum(hc.street1CBChance) AS CB_opp_1, - sum(hc.street1CBDone) AS CB_1, - sum(hc.street2CBChance) AS CB_opp_2, - sum(hc.street2CBDone) AS CB_2, - sum(hc.street3CBChance) AS CB_opp_3, - sum(hc.street3CBDone) AS CB_3, - sum(hc.street4CBChance) AS CB_opp_4, - sum(hc.street4CBDone) AS CB_4, - sum(hc.foldToStreet1CBChance) AS f_cb_opp_1, - sum(hc.foldToStreet1CBDone) AS f_cb_1, - sum(hc.foldToStreet2CBChance) AS f_cb_opp_2, - sum(hc.foldToStreet2CBDone) AS f_cb_2, - sum(hc.foldToStreet3CBChance) AS f_cb_opp_3, - sum(hc.foldToStreet3CBDone) AS f_cb_3, - sum(hc.foldToStreet4CBChance) AS f_cb_opp_4, - sum(hc.foldToStreet4CBDone) AS f_cb_4, - sum(hc.totalProfit) AS net, - sum(hc.street1CheckCallRaiseChance) AS ccr_opp_1, - sum(hc.street1CheckCallRaiseDone) AS ccr_1, - sum(hc.street2CheckCallRaiseChance) AS ccr_opp_2, - sum(hc.street2CheckCallRaiseDone) AS ccr_2, - sum(hc.street3CheckCallRaiseChance) AS ccr_opp_3, - sum(hc.street3CheckCallRaiseDone) AS ccr_3, - sum(hc.street4CheckCallRaiseChance) AS ccr_opp_4, - sum(hc.street4CheckCallRaiseDone) AS ccr_4 - FROM Hands h - INNER JOIN HandsPlayers hp ON (hp.handId = h.id) - INNER JOIN HudCache hc ON (hc.playerId = hp.playerId) - INNER JOIN Players p ON (p.id = hc.playerId) - WHERE h.id = %s - AND ( /* 2 separate parts for hero and opponents */ - ( hp.playerId != %s - AND hc.styleKey > %s - AND hc.gametypeId+0 in - (SELECT gt1.id from Gametypes gt1, Gametypes gt2 - WHERE gt1.siteid = gt2.siteid /* find gametypes where these match: */ - AND gt1.type = gt2.type /* ring/tourney */ - AND gt1.category = gt2.category /* holdem/stud*/ - AND gt1.limittype = gt2.limittype /* fl/nl */ - AND gt1.bigblind <= gt2.bigblind * %s /* bigblind similar size */ - AND gt1.bigblind >= gt2.bigblind / %s - AND gt2.id = h.gametypeId) - ) - OR - ( hp.playerId = %s - AND hc.styleKey > %s - AND hc.gametypeId+0 in - (SELECT gt1.id from Gametypes gt1, Gametypes gt2 - WHERE gt1.siteid = gt2.siteid /* find gametypes where these match: */ - AND gt1.type = gt2.type /* ring/tourney */ - AND gt1.category = gt2.category /* holdem/stud*/ - AND gt1.limittype = gt2.limittype /* fl/nl */ - AND gt1.bigblind <= gt2.bigblind * %s /* bigblind similar size */ - AND gt1.bigblind >= gt2.bigblind / %s - AND gt2.id = h.gametypeId) - ) + self.query['get_stats_from_hand_aggregated'] = """ + SELECT hc.playerId AS player_id, + max(case when hc.gametypeId = h.gametypeId + then hp.seatNo + else -1 + end) AS seat, + p.name AS screen_name, + sum(hc.HDs) AS n, + sum(hc.street0VPI) AS vpip, + sum(hc.street0Aggr) AS pfr, + sum(hc.street0_3BChance) AS TB_opp_0, + sum(hc.street0_3BDone) AS TB_0, + sum(hc.street1Seen) AS saw_f, + sum(hc.street1Seen) AS saw_1, + sum(hc.street2Seen) AS saw_2, + sum(hc.street3Seen) AS saw_3, + sum(hc.street4Seen) AS saw_4, + sum(hc.sawShowdown) AS sd, + sum(hc.street1Aggr) AS aggr_1, + sum(hc.street2Aggr) AS aggr_2, + sum(hc.street3Aggr) AS aggr_3, + sum(hc.street4Aggr) AS aggr_4, + sum(hc.otherRaisedStreet1) AS was_raised_1, + sum(hc.otherRaisedStreet2) AS was_raised_2, + sum(hc.otherRaisedStreet3) AS was_raised_3, + sum(hc.otherRaisedStreet4) AS was_raised_4, + sum(hc.foldToOtherRaisedStreet1) AS f_freq_1, + sum(hc.foldToOtherRaisedStreet2) AS f_freq_2, + sum(hc.foldToOtherRaisedStreet3) AS f_freq_3, + sum(hc.foldToOtherRaisedStreet4) AS f_freq_4, + sum(hc.wonWhenSeenStreet1) AS w_w_s_1, + sum(hc.wonAtSD) AS wmsd, + sum(hc.stealAttemptChance) AS steal_opp, + sum(hc.stealAttempted) AS steal, + sum(hc.foldSbToStealChance) AS SBstolen, + sum(hc.foldedSbToSteal) AS SBnotDef, + sum(hc.foldBbToStealChance) AS BBstolen, + sum(hc.foldedBbToSteal) AS BBnotDef, + sum(hc.street1CBChance) AS CB_opp_1, + sum(hc.street1CBDone) AS CB_1, + sum(hc.street2CBChance) AS CB_opp_2, + sum(hc.street2CBDone) AS CB_2, + sum(hc.street3CBChance) AS CB_opp_3, + sum(hc.street3CBDone) AS CB_3, + sum(hc.street4CBChance) AS CB_opp_4, + sum(hc.street4CBDone) AS CB_4, + sum(hc.foldToStreet1CBChance) AS f_cb_opp_1, + sum(hc.foldToStreet1CBDone) AS f_cb_1, + sum(hc.foldToStreet2CBChance) AS f_cb_opp_2, + sum(hc.foldToStreet2CBDone) AS f_cb_2, + sum(hc.foldToStreet3CBChance) AS f_cb_opp_3, + sum(hc.foldToStreet3CBDone) AS f_cb_3, + sum(hc.foldToStreet4CBChance) AS f_cb_opp_4, + sum(hc.foldToStreet4CBDone) AS f_cb_4, + sum(hc.totalProfit) AS net, + sum(hc.street1CheckCallRaiseChance) AS ccr_opp_1, + sum(hc.street1CheckCallRaiseDone) AS ccr_1, + sum(hc.street2CheckCallRaiseChance) AS ccr_opp_2, + sum(hc.street2CheckCallRaiseDone) AS ccr_2, + sum(hc.street3CheckCallRaiseChance) AS ccr_opp_3, + sum(hc.street3CheckCallRaiseDone) AS ccr_3, + sum(hc.street4CheckCallRaiseChance) AS ccr_opp_4, + sum(hc.street4CheckCallRaiseDone) AS ccr_4 + FROM Hands h + INNER JOIN HandsPlayers hp ON (hp.handId = h.id) + INNER JOIN HudCache hc ON (hc.playerId = hp.playerId) + INNER JOIN Players p ON (p.id = hc.playerId) + WHERE h.id = %s + AND ( /* 2 separate parts for hero and opponents */ + ( hp.playerId != %s + AND hc.styleKey > %s + AND hc.gametypeId+0 in + (SELECT gt1.id from Gametypes gt1, Gametypes gt2 + WHERE gt1.siteid = gt2.siteid /* find gametypes where these match: */ + AND gt1.type = gt2.type /* ring/tourney */ + AND gt1.category = gt2.category /* holdem/stud*/ + AND gt1.limittype = gt2.limittype /* fl/nl */ + AND gt1.bigblind <= gt2.bigblind * %s /* bigblind similar size */ + AND gt1.bigblind >= gt2.bigblind / %s + AND gt2.id = h.gametypeId) ) - GROUP BY hc.PlayerId, p.name - """ - # NOTES on above cursor: - # - Do NOT include %s inside query in a comment - the db api thinks - # they are actual arguments. - # - styleKey is currently 'd' (for date) followed by a yyyymmdd - # date key. Set it to 0000000 or similar to get all records - # Could also check activeseats here even if only 3 groups eg 2-3/4-6/7+ - # e.g. could use a multiplier: - # AND h.seats > %s / 1.25 and hp.seats < %s * 1.25 - # where %s is the number of active players at the current table (and - # 1.25 would be a config value so user could change it) + OR + ( hp.playerId = %s + AND hc.styleKey > %s + AND hc.gametypeId+0 in + (SELECT gt1.id from Gametypes gt1, Gametypes gt2 + WHERE gt1.siteid = gt2.siteid /* find gametypes where these match: */ + AND gt1.type = gt2.type /* ring/tourney */ + AND gt1.category = gt2.category /* holdem/stud*/ + AND gt1.limittype = gt2.limittype /* fl/nl */ + AND gt1.bigblind <= gt2.bigblind * %s /* bigblind similar size */ + AND gt1.bigblind >= gt2.bigblind / %s + AND gt2.id = h.gametypeId) + ) + ) + GROUP BY hc.PlayerId, p.name + """ + # NOTES on above cursor: + # - Do NOT include %s inside query in a comment - the db api thinks + # they are actual arguments. + # - styleKey is currently 'd' (for date) followed by a yyyymmdd + # date key. Set it to 0000000 or similar to get all records + # Could also check activeseats here even if only 3 groups eg 2-3/4-6/7+ + # e.g. could use a multiplier: + # AND h.seats > %s / 1.25 and hp.seats < %s * 1.25 + # where %s is the number of active players at the current table (and + # 1.25 would be a config value so user could change it) - if db_server == 'mysql': - self.query['get_stats_from_hand_session'] = """ - SELECT hp.playerId AS player_id, - hp.handId AS hand_id, - hp.seatNo AS seat, - p.name AS screen_name, - h.seats AS seats, - 1 AS n, - cast(hp2.street0VPI as integer) AS vpip, - cast(hp2.street0Aggr as integer) AS pfr, - cast(hp2.street0_3BChance as integer) AS TB_opp_0, - cast(hp2.street0_3BDone as integer) AS TB_0, - cast(hp2.street1Seen as integer) AS saw_f, - cast(hp2.street1Seen as integer) AS saw_1, - cast(hp2.street2Seen as integer) AS saw_2, - cast(hp2.street3Seen as integer) AS saw_3, - cast(hp2.street4Seen as integer) AS saw_4, - cast(hp2.sawShowdown as integer) AS sd, - cast(hp2.street1Aggr as integer) AS aggr_1, - cast(hp2.street2Aggr as integer) AS aggr_2, - cast(hp2.street3Aggr as integer) AS aggr_3, - cast(hp2.street4Aggr as integer) AS aggr_4, - cast(hp2.otherRaisedStreet1 as integer) AS was_raised_1, - cast(hp2.otherRaisedStreet2 as integer) AS was_raised_2, - cast(hp2.otherRaisedStreet3 as integer) AS was_raised_3, - cast(hp2.otherRaisedStreet4 as integer) AS was_raised_4, - cast(hp2.foldToOtherRaisedStreet1 as integer) AS f_freq_1, - cast(hp2.foldToOtherRaisedStreet2 as integer) AS f_freq_2, - cast(hp2.foldToOtherRaisedStreet3 as integer) AS f_freq_3, - cast(hp2.foldToOtherRaisedStreet4 as integer) AS f_freq_4, - cast(hp2.wonWhenSeenStreet1 as integer) AS w_w_s_1, - cast(hp2.wonAtSD as integer) AS wmsd, - cast(hp2.stealAttemptChance as integer) AS steal_opp, - cast(hp2.stealAttempted as integer) AS steal, - cast(hp2.foldSbToStealChance as integer) AS SBstolen, - cast(hp2.foldedSbToSteal as integer) AS SBnotDef, - cast(hp2.foldBbToStealChance as integer) AS BBstolen, - cast(hp2.foldedBbToSteal as integer) AS BBnotDef, - cast(hp2.street1CBChance as integer) AS CB_opp_1, - cast(hp2.street1CBDone as integer) AS CB_1, - cast(hp2.street2CBChance as integer) AS CB_opp_2, - cast(hp2.street2CBDone as integer) AS CB_2, - cast(hp2.street3CBChance as integer) AS CB_opp_3, - cast(hp2.street3CBDone as integer) AS CB_3, - cast(hp2.street4CBChance as integer) AS CB_opp_4, - cast(hp2.street4CBDone as integer) AS CB_4, - cast(hp2.foldToStreet1CBChance as integer) AS f_cb_opp_1, - cast(hp2.foldToStreet1CBDone as integer) AS f_cb_1, - cast(hp2.foldToStreet2CBChance as integer) AS f_cb_opp_2, - cast(hp2.foldToStreet2CBDone as integer) AS f_cb_2, - cast(hp2.foldToStreet3CBChance as integer) AS f_cb_opp_3, - cast(hp2.foldToStreet3CBDone as integer) AS f_cb_3, - cast(hp2.foldToStreet4CBChance as integer) AS f_cb_opp_4, - cast(hp2.foldToStreet4CBDone as integer) AS f_cb_4, - cast(hp2.totalProfit as integer) AS net, - cast(hp2.street1CheckCallRaiseChance as integer) AS ccr_opp_1, - cast(hp2.street1CheckCallRaiseDone as integer) AS ccr_1, - cast(hp2.street2CheckCallRaiseChance as integer) AS ccr_opp_2, - cast(hp2.street2CheckCallRaiseDone as integer) AS ccr_2, - cast(hp2.street3CheckCallRaiseChance as integer) AS ccr_opp_3, - cast(hp2.street3CheckCallRaiseDone as integer) AS ccr_3, - cast(hp2.street4CheckCallRaiseChance as integer) AS ccr_opp_4, - cast(hp2.street4CheckCallRaiseDone as integer) AS ccr_4 - FROM - Hands h /* players in this hand */ - INNER JOIN Hands h2 ON (h2.id > %s AND h2.tableName = h.tableName) - INNER JOIN HandsPlayers hp ON (h.id = hp.handId) - INNER JOIN HandsPlayers hp2 ON (hp2.playerId+0 = hp.playerId+0 AND (hp2.handId = h2.id+0)) /* other hands by these players */ - INNER JOIN Players p ON (p.id = hp2.PlayerId+0) - WHERE hp.handId = %s - /* check activeseats once this data returned (don't want to do that here as it might - assume a session ended just because the number of seats dipped for a few hands) - */ - ORDER BY h.handStart desc, hp2.PlayerId - /* order rows by handstart descending so that we can stop reading rows when - there's a gap over X minutes between hands (ie. when we get back to start of - the session */ - """ - else: # assume postgresql - self.query['get_stats_from_hand_session'] = """ - SELECT hp.playerId AS player_id, - hp.handId AS hand_id, - hp.seatNo AS seat, - p.name AS screen_name, - h.seats AS seats, - 1 AS n, - cast(hp2.street0VPI as integer) AS vpip, - cast(hp2.street0Aggr as integer) AS pfr, - cast(hp2.street0_3BChance as integer) AS TB_opp_0, - cast(hp2.street0_3BDone as integer) AS TB_0, - cast(hp2.street1Seen as integer) AS saw_f, - cast(hp2.street1Seen as integer) AS saw_1, - cast(hp2.street2Seen as integer) AS saw_2, - cast(hp2.street3Seen as integer) AS saw_3, - cast(hp2.street4Seen as integer) AS saw_4, - cast(hp2.sawShowdown as integer) AS sd, - cast(hp2.street1Aggr as integer) AS aggr_1, - cast(hp2.street2Aggr as integer) AS aggr_2, - cast(hp2.street3Aggr as integer) AS aggr_3, - cast(hp2.street4Aggr as integer) AS aggr_4, - cast(hp2.otherRaisedStreet1 as integer) AS was_raised_1, - cast(hp2.otherRaisedStreet2 as integer) AS was_raised_2, - cast(hp2.otherRaisedStreet3 as integer) AS was_raised_3, - cast(hp2.otherRaisedStreet4 as integer) AS was_raised_4, - cast(hp2.foldToOtherRaisedStreet1 as integer) AS f_freq_1, - cast(hp2.foldToOtherRaisedStreet2 as integer) AS f_freq_2, - cast(hp2.foldToOtherRaisedStreet3 as integer) AS f_freq_3, - cast(hp2.foldToOtherRaisedStreet4 as integer) AS f_freq_4, - cast(hp2.wonWhenSeenStreet1 as integer) AS w_w_s_1, - cast(hp2.wonAtSD as integer) AS wmsd, - cast(hp2.stealAttemptChance as integer) AS steal_opp, - cast(hp2.stealAttempted as integer) AS steal, - cast(hp2.foldSbToStealChance as integer) AS SBstolen, - cast(hp2.foldedSbToSteal as integer) AS SBnotDef, - cast(hp2.foldBbToStealChance as integer) AS BBstolen, - cast(hp2.foldedBbToSteal as integer) AS BBnotDef, - cast(hp2.street1CBChance as integer) AS CB_opp_1, - cast(hp2.street1CBDone as integer) AS CB_1, - cast(hp2.street2CBChance as integer) AS CB_opp_2, - cast(hp2.street2CBDone as integer) AS CB_2, - cast(hp2.street3CBChance as integer) AS CB_opp_3, - cast(hp2.street3CBDone as integer) AS CB_3, - cast(hp2.street4CBChance as integer) AS CB_opp_4, - cast(hp2.street4CBDone as integer) AS CB_4, - cast(hp2.foldToStreet1CBChance as integer) AS f_cb_opp_1, - cast(hp2.foldToStreet1CBDone as integer) AS f_cb_1, - cast(hp2.foldToStreet2CBChance as integer) AS f_cb_opp_2, - cast(hp2.foldToStreet2CBDone as integer) AS f_cb_2, - cast(hp2.foldToStreet3CBChance as integer) AS f_cb_opp_3, - cast(hp2.foldToStreet3CBDone as integer) AS f_cb_3, - cast(hp2.foldToStreet4CBChance as integer) AS f_cb_opp_4, - cast(hp2.foldToStreet4CBDone as integer) AS f_cb_4, - cast(hp2.totalProfit as integer) AS net, - cast(hp2.street1CheckCallRaiseChance as integer) AS ccr_opp_1, - cast(hp2.street1CheckCallRaiseDone as integer) AS ccr_1, - cast(hp2.street2CheckCallRaiseChance as integer) AS ccr_opp_2, - cast(hp2.street2CheckCallRaiseDone as integer) AS ccr_2, - cast(hp2.street3CheckCallRaiseChance as integer) AS ccr_opp_3, - cast(hp2.street3CheckCallRaiseDone as integer) AS ccr_3, - cast(hp2.street4CheckCallRaiseChance as integer) AS ccr_opp_4, - cast(hp2.street4CheckCallRaiseDone as integer) AS ccr_4 - FROM Hands h /* this hand */ - INNER JOIN Hands h2 ON ( h2.id > %s /* other hands */ - AND h2.tableName = h.tableName) - INNER JOIN HandsPlayers hp ON (h.id = hp.handId) /* players in this hand */ - INNER JOIN HandsPlayers hp2 ON ( hp2.playerId+0 = hp.playerId+0 - AND hp2.handId = h2.id) /* other hands by these players */ - INNER JOIN Players p ON (p.id = hp2.PlayerId+0) - WHERE h.id = %s - /* check activeseats once this data returned (don't want to do that here as it might - assume a session ended just because the number of seats dipped for a few hands) - */ - ORDER BY h.handStart desc, hp2.PlayerId - /* order rows by handstart descending so that we can stop reading rows when - there's a gap over X minutes between hands (ie. when we get back to start of - the session */ - """ - - self.query['get_players_from_hand'] = """ - SELECT HandsPlayers.playerId, seatNo, name - FROM HandsPlayers INNER JOIN Players ON (HandsPlayers.playerId = Players.id) - WHERE handId = %s + if db_server == 'mysql': + self.query['get_stats_from_hand_session'] = """ + SELECT hp.playerId AS player_id, + hp.handId AS hand_id, + hp.seatNo AS seat, + p.name AS screen_name, + h.seats AS seats, + 1 AS n, + cast(hp2.street0VPI as integer) AS vpip, + cast(hp2.street0Aggr as integer) AS pfr, + cast(hp2.street0_3BChance as integer) AS TB_opp_0, + cast(hp2.street0_3BDone as integer) AS TB_0, + cast(hp2.street1Seen as integer) AS saw_f, + cast(hp2.street1Seen as integer) AS saw_1, + cast(hp2.street2Seen as integer) AS saw_2, + cast(hp2.street3Seen as integer) AS saw_3, + cast(hp2.street4Seen as integer) AS saw_4, + cast(hp2.sawShowdown as integer) AS sd, + cast(hp2.street1Aggr as integer) AS aggr_1, + cast(hp2.street2Aggr as integer) AS aggr_2, + cast(hp2.street3Aggr as integer) AS aggr_3, + cast(hp2.street4Aggr as integer) AS aggr_4, + cast(hp2.otherRaisedStreet1 as integer) AS was_raised_1, + cast(hp2.otherRaisedStreet2 as integer) AS was_raised_2, + cast(hp2.otherRaisedStreet3 as integer) AS was_raised_3, + cast(hp2.otherRaisedStreet4 as integer) AS was_raised_4, + cast(hp2.foldToOtherRaisedStreet1 as integer) AS f_freq_1, + cast(hp2.foldToOtherRaisedStreet2 as integer) AS f_freq_2, + cast(hp2.foldToOtherRaisedStreet3 as integer) AS f_freq_3, + cast(hp2.foldToOtherRaisedStreet4 as integer) AS f_freq_4, + cast(hp2.wonWhenSeenStreet1 as integer) AS w_w_s_1, + cast(hp2.wonAtSD as integer) AS wmsd, + cast(hp2.stealAttemptChance as integer) AS steal_opp, + cast(hp2.stealAttempted as integer) AS steal, + cast(hp2.foldSbToStealChance as integer) AS SBstolen, + cast(hp2.foldedSbToSteal as integer) AS SBnotDef, + cast(hp2.foldBbToStealChance as integer) AS BBstolen, + cast(hp2.foldedBbToSteal as integer) AS BBnotDef, + cast(hp2.street1CBChance as integer) AS CB_opp_1, + cast(hp2.street1CBDone as integer) AS CB_1, + cast(hp2.street2CBChance as integer) AS CB_opp_2, + cast(hp2.street2CBDone as integer) AS CB_2, + cast(hp2.street3CBChance as integer) AS CB_opp_3, + cast(hp2.street3CBDone as integer) AS CB_3, + cast(hp2.street4CBChance as integer) AS CB_opp_4, + cast(hp2.street4CBDone as integer) AS CB_4, + cast(hp2.foldToStreet1CBChance as integer) AS f_cb_opp_1, + cast(hp2.foldToStreet1CBDone as integer) AS f_cb_1, + cast(hp2.foldToStreet2CBChance as integer) AS f_cb_opp_2, + cast(hp2.foldToStreet2CBDone as integer) AS f_cb_2, + cast(hp2.foldToStreet3CBChance as integer) AS f_cb_opp_3, + cast(hp2.foldToStreet3CBDone as integer) AS f_cb_3, + cast(hp2.foldToStreet4CBChance as integer) AS f_cb_opp_4, + cast(hp2.foldToStreet4CBDone as integer) AS f_cb_4, + cast(hp2.totalProfit as integer) AS net, + cast(hp2.street1CheckCallRaiseChance as integer) AS ccr_opp_1, + cast(hp2.street1CheckCallRaiseDone as integer) AS ccr_1, + cast(hp2.street2CheckCallRaiseChance as integer) AS ccr_opp_2, + cast(hp2.street2CheckCallRaiseDone as integer) AS ccr_2, + cast(hp2.street3CheckCallRaiseChance as integer) AS ccr_opp_3, + cast(hp2.street3CheckCallRaiseDone as integer) AS ccr_3, + cast(hp2.street4CheckCallRaiseChance as integer) AS ccr_opp_4, + cast(hp2.street4CheckCallRaiseDone as integer) AS ccr_4 + FROM + Hands h /* players in this hand */ + INNER JOIN Hands h2 ON (h2.id > %s AND h2.tableName = h.tableName) + INNER JOIN HandsPlayers hp ON (h.id = hp.handId) + INNER JOIN HandsPlayers hp2 ON (hp2.playerId+0 = hp.playerId+0 AND (hp2.handId = h2.id+0)) /* other hands by these players */ + INNER JOIN Players p ON (p.id = hp2.PlayerId+0) + WHERE hp.handId = %s + /* check activeseats once this data returned (don't want to do that here as it might + assume a session ended just because the number of seats dipped for a few hands) + */ + ORDER BY h.handStart desc, hp2.PlayerId + /* order rows by handstart descending so that we can stop reading rows when + there's a gap over X minutes between hands (ie. when we get back to start of + the session */ """ + else: # assume postgresql + self.query['get_stats_from_hand_session'] = """ + SELECT hp.playerId AS player_id, + hp.handId AS hand_id, + hp.seatNo AS seat, + p.name AS screen_name, + h.seats AS seats, + 1 AS n, + cast(hp2.street0VPI as integer) AS vpip, + cast(hp2.street0Aggr as integer) AS pfr, + cast(hp2.street0_3BChance as integer) AS TB_opp_0, + cast(hp2.street0_3BDone as integer) AS TB_0, + cast(hp2.street1Seen as integer) AS saw_f, + cast(hp2.street1Seen as integer) AS saw_1, + cast(hp2.street2Seen as integer) AS saw_2, + cast(hp2.street3Seen as integer) AS saw_3, + cast(hp2.street4Seen as integer) AS saw_4, + cast(hp2.sawShowdown as integer) AS sd, + cast(hp2.street1Aggr as integer) AS aggr_1, + cast(hp2.street2Aggr as integer) AS aggr_2, + cast(hp2.street3Aggr as integer) AS aggr_3, + cast(hp2.street4Aggr as integer) AS aggr_4, + cast(hp2.otherRaisedStreet1 as integer) AS was_raised_1, + cast(hp2.otherRaisedStreet2 as integer) AS was_raised_2, + cast(hp2.otherRaisedStreet3 as integer) AS was_raised_3, + cast(hp2.otherRaisedStreet4 as integer) AS was_raised_4, + cast(hp2.foldToOtherRaisedStreet1 as integer) AS f_freq_1, + cast(hp2.foldToOtherRaisedStreet2 as integer) AS f_freq_2, + cast(hp2.foldToOtherRaisedStreet3 as integer) AS f_freq_3, + cast(hp2.foldToOtherRaisedStreet4 as integer) AS f_freq_4, + cast(hp2.wonWhenSeenStreet1 as integer) AS w_w_s_1, + cast(hp2.wonAtSD as integer) AS wmsd, + cast(hp2.stealAttemptChance as integer) AS steal_opp, + cast(hp2.stealAttempted as integer) AS steal, + cast(hp2.foldSbToStealChance as integer) AS SBstolen, + cast(hp2.foldedSbToSteal as integer) AS SBnotDef, + cast(hp2.foldBbToStealChance as integer) AS BBstolen, + cast(hp2.foldedBbToSteal as integer) AS BBnotDef, + cast(hp2.street1CBChance as integer) AS CB_opp_1, + cast(hp2.street1CBDone as integer) AS CB_1, + cast(hp2.street2CBChance as integer) AS CB_opp_2, + cast(hp2.street2CBDone as integer) AS CB_2, + cast(hp2.street3CBChance as integer) AS CB_opp_3, + cast(hp2.street3CBDone as integer) AS CB_3, + cast(hp2.street4CBChance as integer) AS CB_opp_4, + cast(hp2.street4CBDone as integer) AS CB_4, + cast(hp2.foldToStreet1CBChance as integer) AS f_cb_opp_1, + cast(hp2.foldToStreet1CBDone as integer) AS f_cb_1, + cast(hp2.foldToStreet2CBChance as integer) AS f_cb_opp_2, + cast(hp2.foldToStreet2CBDone as integer) AS f_cb_2, + cast(hp2.foldToStreet3CBChance as integer) AS f_cb_opp_3, + cast(hp2.foldToStreet3CBDone as integer) AS f_cb_3, + cast(hp2.foldToStreet4CBChance as integer) AS f_cb_opp_4, + cast(hp2.foldToStreet4CBDone as integer) AS f_cb_4, + cast(hp2.totalProfit as integer) AS net, + cast(hp2.street1CheckCallRaiseChance as integer) AS ccr_opp_1, + cast(hp2.street1CheckCallRaiseDone as integer) AS ccr_1, + cast(hp2.street2CheckCallRaiseChance as integer) AS ccr_opp_2, + cast(hp2.street2CheckCallRaiseDone as integer) AS ccr_2, + cast(hp2.street3CheckCallRaiseChance as integer) AS ccr_opp_3, + cast(hp2.street3CheckCallRaiseDone as integer) AS ccr_3, + cast(hp2.street4CheckCallRaiseChance as integer) AS ccr_opp_4, + cast(hp2.street4CheckCallRaiseDone as integer) AS ccr_4 + FROM Hands h /* this hand */ + INNER JOIN Hands h2 ON ( h2.id > %s /* other hands */ + AND h2.tableName = h.tableName) + INNER JOIN HandsPlayers hp ON (h.id = hp.handId) /* players in this hand */ + INNER JOIN HandsPlayers hp2 ON ( hp2.playerId+0 = hp.playerId+0 + AND hp2.handId = h2.id) /* other hands by these players */ + INNER JOIN Players p ON (p.id = hp2.PlayerId+0) + WHERE h.id = %s + /* check activeseats once this data returned (don't want to do that here as it might + assume a session ended just because the number of seats dipped for a few hands) + */ + ORDER BY h.handStart desc, hp2.PlayerId + /* order rows by handstart descending so that we can stop reading rows when + there's a gap over X minutes between hands (ie. when we get back to start of + the session */ + """ + + self.query['get_players_from_hand'] = """ + SELECT HandsPlayers.playerId, seatNo, name + FROM HandsPlayers INNER JOIN Players ON (HandsPlayers.playerId = Players.id) + WHERE handId = %s + """ # WHERE handId = %s AND Players.id LIKE %s - self.query['get_winners_from_hand'] = """ - SELECT name, winnings - FROM HandsPlayers, Players - WHERE winnings > 0 - AND Players.id = HandsPlayers.playerId - AND handId = %s; - """ - - self.query['get_table_name'] = """ - select h.tableName, h.maxSeats, gt.category, gt.type, gt.siteId - from Hands h - ,Gametypes gt - where h.id = %s - and gt.id = h.gametypeId - """ - - self.query['get_actual_seat'] = """ - select seatNo - from HandsPlayers - where HandsPlayers.handId = %s - and HandsPlayers.playerId = (select Players.id from Players - where Players.name = %s) - """ - - self.query['get_cards'] = """ - select - seatNo AS seat_number, - card1, /*card1Value, card1Suit, */ - card2, /*card2Value, card2Suit, */ - card3, /*card3Value, card3Suit, */ - card4, /*card4Value, card4Suit, */ - card5, /*card5Value, card5Suit, */ - card6, /*card6Value, card6Suit, */ - card7 /*card7Value, card7Suit */ - from HandsPlayers, Players - where handID = %s and HandsPlayers.playerId = Players.id - order by seatNo - """ - - self.query['get_common_cards'] = """ - select - boardcard1, - boardcard2, - boardcard3, - boardcard4, - boardcard5 - from Hands - where Id = %s - """ - - self.query['get_action_from_hand'] = """ - SELECT street, Players.name, HandsActions.action, HandsActions.amount, actionno - FROM Players, HandsActions, HandsPlayers - WHERE HandsPlayers.handid = %s - AND HandsPlayers.playerid = Players.id - AND HandsActions.handsPlayerId = HandsPlayers.id - ORDER BY street, actionno + self.query['get_winners_from_hand'] = """ + SELECT name, winnings + FROM HandsPlayers, Players + WHERE winnings > 0 + AND Players.id = HandsPlayers.playerId + AND handId = %s; """ - if db_server == 'mysql': - self.query['get_hand_1day_ago'] = """ - select coalesce(max(id),0) - from Hands - where handStart < date_sub(utc_timestamp(), interval '1' day)""" - elif db_server == 'postgresql': - self.query['get_hand_1day_ago'] = """ - select coalesce(max(id),0) - from Hands - where handStart < now() at time zone 'UTC' - interval '1 day'""" - elif db_server == 'sqlite': - self.query['get_hand_1day_ago'] = """ - select coalesce(max(id),0) - from Hands - where handStart < strftime('%J', 'now') - 1""" + self.query['get_table_name'] = """ + select h.tableName, h.maxSeats, gt.category, gt.type, gt.siteId + from Hands h + ,Gametypes gt + where h.id = %s + and gt.id = h.gametypeId + """ - # not used yet ... - # gets a date, would need to use handsplayers (not hudcache) to get exact hand Id - if db_server == 'mysql': - self.query['get_date_nhands_ago'] = """ - select concat( 'd', date_format(max(h.handStart), '%Y%m%d') ) - from (select hp.playerId - ,coalesce(greatest(max(hp.handId)-%s,1),1) as maxminusx - from HandsPlayers hp - where hp.playerId = %s - group by hp.playerId) hp2 - inner join HandsPlayers hp3 on ( hp3.handId <= hp2.maxminusx - and hp3.playerId = hp2.playerId) - inner join Hands h on (h.id = hp3.handId) - """ - elif db_server == 'postgresql': - self.query['get_date_nhands_ago'] = """ - select 'd' || to_char(max(h3.handStart), 'YYMMDD') - from (select hp.playerId - ,coalesce(greatest(max(hp.handId)-%s,1),1) as maxminusx - from HandsPlayers hp - where hp.playerId = %s - group by hp.playerId) hp2 - inner join HandsPlayers hp3 on ( hp3.handId <= hp2.maxminusx - and hp3.playerId = hp2.playerId) - inner join Hands h on (h.id = hp3.handId) - """ - elif db_server == 'sqlite': # untested guess at query: - self.query['get_date_nhands_ago'] = """ - select 'd' || strftime(max(h3.handStart), 'YYMMDD') - from (select hp.playerId - ,coalesce(greatest(max(hp.handId)-%s,1),1) as maxminusx - from HandsPlayers hp - where hp.playerId = %s - group by hp.playerId) hp2 - inner join HandsPlayers hp3 on ( hp3.handId <= hp2.maxminusx - and hp3.playerId = hp2.playerId) - inner join Hands h on (h.id = hp3.handId) - """ + self.query['get_actual_seat'] = """ + select seatNo + from HandsPlayers + where HandsPlayers.handId = %s + and HandsPlayers.playerId = (select Players.id from Players + where Players.name = %s) + """ - # used in GuiPlayerStats: - self.query['getPlayerId'] = """SELECT id from Players where name = %s""" + self.query['get_cards'] = """ + select + seatNo AS seat_number, + card1, /*card1Value, card1Suit, */ + card2, /*card2Value, card2Suit, */ + card3, /*card3Value, card3Suit, */ + card4, /*card4Value, card4Suit, */ + card5, /*card5Value, card5Suit, */ + card6, /*card6Value, card6Suit, */ + card7 /*card7Value, card7Suit */ + from HandsPlayers, Players + where handID = %s and HandsPlayers.playerId = Players.id + order by seatNo + """ - self.query['getPlayerIdBySite'] = """SELECT id from Players where name = %s AND siteId = %s""" + self.query['get_common_cards'] = """ + select + boardcard1, + boardcard2, + boardcard3, + boardcard4, + boardcard5 + from Hands + where Id = %s + """ + + self.query['get_action_from_hand'] = """ + SELECT street, Players.name, HandsActions.action, HandsActions.amount, actionno + FROM Players, HandsActions, HandsPlayers + WHERE HandsPlayers.handid = %s + AND HandsPlayers.playerid = Players.id + AND HandsActions.handsPlayerId = HandsPlayers.id + ORDER BY street, actionno + """ + + if db_server == 'mysql': + self.query['get_hand_1day_ago'] = """ + select coalesce(max(id),0) + from Hands + where handStart < date_sub(utc_timestamp(), interval '1' day)""" + elif db_server == 'postgresql': + self.query['get_hand_1day_ago'] = """ + select coalesce(max(id),0) + from Hands + where handStart < now() at time zone 'UTC' - interval '1 day'""" + elif db_server == 'sqlite': + self.query['get_hand_1day_ago'] = """ + select coalesce(max(id),0) + from Hands + where handStart < strftime('%J', 'now') - 1""" + + # not used yet ... + # gets a date, would need to use handsplayers (not hudcache) to get exact hand Id + if db_server == 'mysql': + self.query['get_date_nhands_ago'] = """ + select concat( 'd', date_format(max(h.handStart), '%Y%m%d') ) + from (select hp.playerId + ,coalesce(greatest(max(hp.handId)-%s,1),1) as maxminusx + from HandsPlayers hp + where hp.playerId = %s + group by hp.playerId) hp2 + inner join HandsPlayers hp3 on ( hp3.handId <= hp2.maxminusx + and hp3.playerId = hp2.playerId) + inner join Hands h on (h.id = hp3.handId) + """ + elif db_server == 'postgresql': + self.query['get_date_nhands_ago'] = """ + select 'd' || to_char(max(h3.handStart), 'YYMMDD') + from (select hp.playerId + ,coalesce(greatest(max(hp.handId)-%s,1),1) as maxminusx + from HandsPlayers hp + where hp.playerId = %s + group by hp.playerId) hp2 + inner join HandsPlayers hp3 on ( hp3.handId <= hp2.maxminusx + and hp3.playerId = hp2.playerId) + inner join Hands h on (h.id = hp3.handId) + """ + elif db_server == 'sqlite': # untested guess at query: + self.query['get_date_nhands_ago'] = """ + select 'd' || strftime(max(h3.handStart), 'YYMMDD') + from (select hp.playerId + ,coalesce(greatest(max(hp.handId)-%s,1),1) as maxminusx + from HandsPlayers hp + where hp.playerId = %s + group by hp.playerId) hp2 + inner join HandsPlayers hp3 on ( hp3.handId <= hp2.maxminusx + and hp3.playerId = hp2.playerId) + inner join Hands h on (h.id = hp3.handId) + """ + + # used in GuiPlayerStats: + self.query['getPlayerId'] = """SELECT id from Players where name = %s""" + + self.query['getPlayerIdBySite'] = """SELECT id from Players where name = %s AND siteId = %s""" - # used in Filters: - self.query['getSiteId'] = """SELECT id from Sites where name = %s""" - self.query['getGames'] = """SELECT DISTINCT category from Gametypes""" - self.query['getLimits'] = """SELECT DISTINCT bigBlind from Gametypes ORDER by bigBlind DESC""" - self.query['getLimits2'] = """SELECT DISTINCT type, limitType, bigBlind - from Gametypes - ORDER by type, limitType DESC, bigBlind DESC""" + # used in Filters: + self.query['getSiteId'] = """SELECT id from Sites where name = %s""" + self.query['getGames'] = """SELECT DISTINCT category from Gametypes""" + self.query['getLimits'] = """SELECT DISTINCT bigBlind from Gametypes ORDER by bigBlind DESC""" + self.query['getLimits2'] = """SELECT DISTINCT type, limitType, bigBlind + from Gametypes + ORDER by type, limitType DESC, bigBlind DESC""" - if db_server == 'mysql': - self.query['playerDetailedStats'] = """ - select AS hgametypeid - , AS pname - ,gt.base - ,gt.category - ,upper(gt.limitType) AS limittype - ,s.name - ,min(gt.bigBlind) AS minbigblind - ,max(gt.bigBlind) AS maxbigblind - /*, AS gtid*/ - , AS plposition - ,count(1) AS n - ,100.0*sum(cast(hp.street0VPI as integer))/count(1) AS vpip - ,100.0*sum(cast(hp.street0Aggr as integer))/count(1) AS pfr - ,case when sum(cast(hp.street0_3Bchance as integer)) = 0 then -999 - else 100.0*sum(cast(hp.street0_3Bdone as integer))/sum(cast(hp.street0_3Bchance as integer)) - end AS pf3 - ,case when sum(cast(hp.stealattemptchance as integer)) = 0 then -999 - else 100.0*sum(cast(hp.stealattempted as integer))/sum(cast(hp.stealattemptchance as integer)) - end AS steals - ,100.0*sum(cast(hp.street1Seen as integer))/count(1) AS saw_f - ,100.0*sum(cast(hp.sawShowdown as integer))/count(1) AS sawsd - ,case when sum(cast(hp.street1Seen as integer)) = 0 then -999 - else 100.0*sum(cast(hp.sawShowdown as integer))/sum(cast(hp.street1Seen as integer)) - end AS wtsdwsf - ,case when sum(cast(hp.sawShowdown as integer)) = 0 then -999 - else 100.0*sum(cast(hp.wonAtSD as integer))/sum(cast(hp.sawShowdown as integer)) - end AS wmsd - ,case when sum(cast(hp.street1Seen as integer)) = 0 then -999 - else 100.0*sum(cast(hp.street1Aggr as integer))/sum(cast(hp.street1Seen as integer)) - end AS flafq - ,case when sum(cast(hp.street2Seen as integer)) = 0 then -999 - else 100.0*sum(cast(hp.street2Aggr as integer))/sum(cast(hp.street2Seen as integer)) - end AS tuafq - ,case when sum(cast(hp.street3Seen as integer)) = 0 then -999 - else 100.0*sum(cast(hp.street3Aggr as integer))/sum(cast(hp.street3Seen as integer)) - end AS rvafq - ,case when sum(cast(hp.street1Seen as integer))+sum(cast(hp.street2Seen as integer))+sum(cast(hp.street3Seen as integer)) = 0 then -999 - else 100.0*(sum(cast(hp.street1Aggr as integer))+sum(cast(hp.street2Aggr as integer))+sum(cast(hp.street3Aggr as integer))) - /(sum(cast(hp.street1Seen as integer))+sum(cast(hp.street2Seen as integer))+sum(cast(hp.street3Seen as integer))) - end AS pofafq - ,sum(hp.totalProfit)/100.0 AS net - ,sum(hp.rake)/100.0 AS rake - ,100.0*avg(hp.totalProfit/(gt.bigBlind+0.0)) AS bbper100 - ,avg(hp.totalProfit)/100.0 AS profitperhand - ,100.0*avg((hp.totalProfit+hp.rake)/(gt.bigBlind+0.0)) AS bb100xr - ,avg((hp.totalProfit+hp.rake)/100.0) AS profhndxr - ,avg(h.seats+0.0) AS avgseats - ,variance(hp.totalProfit/100.0) AS variance - from HandsPlayers hp - inner join Hands h on (h.id = hp.handId) - inner join Gametypes gt on (gt.Id = h.gameTypeId) - inner join Sites s on (s.Id = gt.siteId) - inner join Players p on (p.Id = hp.playerId) - where hp.playerId in - /*and hp.tourneysPlayersId IS NULL*/ - and h.seats - - - and date_format(h.handStart, '%Y-%m-%d') - group by hgameTypeId - ,pname - ,gt.base - ,gt.category - - ,plposition - ,upper(gt.limitType) - ,s.name - having 1 = 1 - order by pname - ,gt.base - ,gt.category - - ,case when 'B' then 'B' - when 'S' then 'S' - else concat('Z', ) - end - - ,upper(gt.limitType) desc - ,maxbigblind desc - ,s.name - """ - elif db_server == 'postgresql': - self.query['playerDetailedStats'] = """ - select AS hgametypeid - , AS pname - ,gt.base - ,gt.category - ,upper(gt.limitType) AS limittype - ,s.name - ,min(gt.bigBlind) AS minbigblind - ,max(gt.bigBlind) AS maxbigblind - /*, AS gtid*/ - , AS plposition - ,count(1) AS n - ,100.0*sum(cast(hp.street0VPI as integer))/count(1) AS vpip - ,100.0*sum(cast(hp.street0Aggr as integer))/count(1) AS pfr - ,case when sum(cast(hp.street0_3Bchance as integer)) = 0 then -999 - else 100.0*sum(cast(hp.street0_3Bdone as integer))/sum(cast(hp.street0_3Bchance as integer)) - end AS pf3 - ,case when sum(cast(hp.stealattemptchance as integer)) = 0 then -999 - else 100.0*sum(cast(hp.stealattempted as integer))/sum(cast(hp.stealattemptchance as integer)) - end AS steals - ,100.0*sum(cast(hp.street1Seen as integer))/count(1) AS saw_f - ,100.0*sum(cast(hp.sawShowdown as integer))/count(1) AS sawsd - ,case when sum(cast(hp.street1Seen as integer)) = 0 then -999 - else 100.0*sum(cast(hp.sawShowdown as integer))/sum(cast(hp.street1Seen as integer)) - end AS wtsdwsf - ,case when sum(cast(hp.sawShowdown as integer)) = 0 then -999 - else 100.0*sum(cast(hp.wonAtSD as integer))/sum(cast(hp.sawShowdown as integer)) - end AS wmsd - ,case when sum(cast(hp.street1Seen as integer)) = 0 then -999 - else 100.0*sum(cast(hp.street1Aggr as integer))/sum(cast(hp.street1Seen as integer)) - end AS flafq - ,case when sum(cast(hp.street2Seen as integer)) = 0 then -999 - else 100.0*sum(cast(hp.street2Aggr as integer))/sum(cast(hp.street2Seen as integer)) - end AS tuafq - ,case when sum(cast(hp.street3Seen as integer)) = 0 then -999 - else 100.0*sum(cast(hp.street3Aggr as integer))/sum(cast(hp.street3Seen as integer)) - end AS rvafq - ,case when sum(cast(hp.street1Seen as integer))+sum(cast(hp.street2Seen as integer))+sum(cast(hp.street3Seen as integer)) = 0 then -999 - else 100.0*(sum(cast(hp.street1Aggr as integer))+sum(cast(hp.street2Aggr as integer))+sum(cast(hp.street3Aggr as integer))) - /(sum(cast(hp.street1Seen as integer))+sum(cast(hp.street2Seen as integer))+sum(cast(hp.street3Seen as integer))) - end AS pofafq - ,sum(hp.totalProfit)/100.0 AS net - ,sum(hp.rake)/100.0 AS rake - ,100.0*avg(hp.totalProfit/(gt.bigBlind+0.0)) AS bbper100 - ,avg(hp.totalProfit)/100.0 AS profitperhand - ,100.0*avg((hp.totalProfit+hp.rake)/(gt.bigBlind+0.0)) AS bb100xr - ,avg((hp.totalProfit+hp.rake)/100.0) AS profhndxr - ,avg(h.seats+0.0) AS avgseats - ,variance(hp.totalProfit/100.0) AS variance - from HandsPlayers hp - inner join Hands h on (h.id = hp.handId) - inner join Gametypes gt on (gt.Id = h.gameTypeId) - inner join Sites s on (s.Id = gt.siteId) - inner join Players p on (p.Id = hp.playerId) - where hp.playerId in - /*and hp.tourneysPlayersId IS NULL*/ - and h.seats - - - and to_char(h.handStart, 'YYYY-MM-DD') - group by hgameTypeId - ,pname - ,gt.base - ,gt.category - - ,plposition - ,upper(gt.limitType) - ,s.name - having 1 = 1 - order by pname - ,gt.base - ,gt.category - - ,case when 'B' then 'B' - when 'S' then 'S' - when '0' then 'Y' - else 'Z'|| - end - - ,upper(gt.limitType) desc - ,maxbigblind desc - ,s.name - """ - elif db_server == 'sqlite': - self.query['playerDetailedStats'] = """ - select AS hgametypeid - ,gt.base - ,gt.category - ,upper(gt.limitType) AS limittype - ,s.name - ,min(gt.bigBlind) AS minbigblind - ,max(gt.bigBlind) AS maxbigblind - /*, AS gtid*/ - , AS plposition - ,count(1) AS n - ,100.0*sum(cast(hp.street0VPI as integer))/count(1) AS vpip - ,100.0*sum(cast(hp.street0Aggr as integer))/count(1) AS pfr - ,case when sum(cast(hp.street0_3Bchance as integer)) = 0 then -999 - else 100.0*sum(cast(hp.street0_3Bdone as integer))/sum(cast(hp.street0_3Bchance as integer)) - end AS pf3 - ,case when sum(cast(hp.stealattemptchance as integer)) = 0 then -999 - else 100.0*sum(cast(hp.stealattempted as integer))/sum(cast(hp.stealattemptchance as integer)) - end AS steals - ,100.0*sum(cast(hp.street1Seen as integer))/count(1) AS saw_f - ,100.0*sum(cast(hp.sawShowdown as integer))/count(1) AS sawsd - ,case when sum(cast(hp.street1Seen as integer)) = 0 then -999 - else 100.0*sum(cast(hp.sawShowdown as integer))/sum(cast(hp.street1Seen as integer)) - end AS wtsdwsf - ,case when sum(cast(hp.sawShowdown as integer)) = 0 then -999 - else 100.0*sum(cast(hp.wonAtSD as integer))/sum(cast(hp.sawShowdown as integer)) - end AS wmsd - ,case when sum(cast(hp.street1Seen as integer)) = 0 then -999 - else 100.0*sum(cast(hp.street1Aggr as integer))/sum(cast(hp.street1Seen as integer)) - end AS flafq - ,case when sum(cast(hp.street2Seen as integer)) = 0 then -999 - else 100.0*sum(cast(hp.street2Aggr as integer))/sum(cast(hp.street2Seen as integer)) - end AS tuafq - ,case when sum(cast(hp.street3Seen as integer)) = 0 then -999 - else 100.0*sum(cast(hp.street3Aggr as integer))/sum(cast(hp.street3Seen as integer)) - end AS rvafq - ,case when sum(cast(hp.street1Seen as integer))+sum(cast(hp.street2Seen as integer))+sum(cast(hp.street3Seen as integer)) = 0 then -999 - else 100.0*(sum(cast(hp.street1Aggr as integer))+sum(cast(hp.street2Aggr as integer))+sum(cast(hp.street3Aggr as integer))) - /(sum(cast(hp.street1Seen as integer))+sum(cast(hp.street2Seen as integer))+sum(cast(hp.street3Seen as integer))) - end AS pofafq - ,sum(hp.totalProfit)/100.0 AS net - ,sum(hp.rake)/100.0 AS rake - ,100.0*avg(hp.totalProfit/(gt.bigBlind+0.0)) AS bbper100 - ,avg(hp.totalProfit)/100.0 AS profitperhand - ,100.0*avg((hp.totalProfit+hp.rake)/(gt.bigBlind+0.0)) AS bb100xr - ,avg((hp.totalProfit+hp.rake)/100.0) AS profhndxr - ,avg(h.seats+0.0) AS avgseats - ,variance(hp.totalProfit/100.0) AS variance - from HandsPlayers hp - inner join Hands h on (h.id = hp.handId) - inner join Gametypes gt on (gt.Id = h.gameTypeId) - inner join Sites s on (s.Id = gt.siteId) - where hp.playerId in - /*and hp.tourneysPlayersId IS NULL*/ - and h.seats - - - and to_char(h.handStart, 'YYYY-MM-DD') - group by hgameTypeId - ,hp.playerId - ,gt.base - ,gt.category - - ,plposition - ,upper(gt.limitType) - ,s.name - order by hp.playerId - ,gt.base - ,gt.category - - ,case when 'B' then 'B' - when 'S' then 'S' - when '0' then 'Y' - else 'Z'|| - end - - ,upper(gt.limitType) desc - ,maxbigblind desc - ,s.name - """ - - if db_server == 'mysql': - self.query['playerStats'] = """ - SELECT - concat(upper(stats.limitType), ' ' - ,concat(upper(substring(stats.category,1,1)),substring(stats.category,2) ), ' ' - ,stats.name, ' ' - ,cast(stats.bigBlindDesc as char) - ) AS Game - ,stats.n - ,stats.vpip - ,stats.pfr - ,stats.pf3 - ,stats.steals - ,stats.saw_f - ,stats.sawsd - ,stats.wtsdwsf - ,stats.wmsd - ,stats.FlAFq - ,stats.TuAFq - ,stats.RvAFq - ,stats.PoFAFq - ,stats.Net - ,stats.BBper100 - ,stats.Profitperhand - ,case when hprof2.variance = -999 then '-' - else format(hprof2.variance, 2) - end AS Variance - ,stats.AvgSeats - FROM - (select /* stats from hudcache */ - gt.base - ,gt.category - ,upper(gt.limitType) as limitType - ,s.name - , AS bigBlindDesc - , AS gtId - ,sum(HDs) AS n - ,format(100.0*sum(street0VPI)/sum(HDs),1) AS vpip - ,format(100.0*sum(street0Aggr)/sum(HDs),1) AS pfr - ,case when sum(street0_3Bchance) = 0 then '0' - else format(100.0*sum(street0_3Bdone)/sum(street0_3Bchance),1) - end AS pf3 - ,case when sum(stealattemptchance) = 0 then '-' - else format(100.0*sum(stealattempted)/sum(stealattemptchance),1) - end AS steals - ,format(100.0*sum(street1Seen)/sum(HDs),1) AS saw_f - ,format(100.0*sum(sawShowdown)/sum(HDs),1) AS sawsd - ,case when sum(street1Seen) = 0 then '-' - else format(100.0*sum(sawShowdown)/sum(street1Seen),1) - end AS wtsdwsf - ,case when sum(sawShowdown) = 0 then '-' - else format(100.0*sum(wonAtSD)/sum(sawShowdown),1) - end AS wmsd - ,case when sum(street1Seen) = 0 then '-' - else format(100.0*sum(street1Aggr)/sum(street1Seen),1) - end AS FlAFq - ,case when sum(street2Seen) = 0 then '-' - else format(100.0*sum(street2Aggr)/sum(street2Seen),1) - end AS TuAFq - ,case when sum(street3Seen) = 0 then '-' - else format(100.0*sum(street3Aggr)/sum(street3Seen),1) - end AS RvAFq - ,case when sum(street1Seen)+sum(street2Seen)+sum(street3Seen) = 0 then '-' - else format(100.0*(sum(street1Aggr)+sum(street2Aggr)+sum(street3Aggr)) - /(sum(street1Seen)+sum(street2Seen)+sum(street3Seen)),1) - end AS PoFAFq - ,format(sum(totalProfit)/100.0,2) AS Net - ,format((sum(totalProfit/(gt.bigBlind+0.0))) / (sum(HDs)/100.0),2) - AS BBper100 - ,format( (sum(totalProfit)/100.0) / sum(HDs), 4) AS Profitperhand - ,format( sum(activeSeats*HDs)/(sum(HDs)+0.0), 2) AS AvgSeats - from Gametypes gt - inner join Sites s on s.Id = gt.siteId - inner join HudCache hc on hc.gameTypeId = gt.Id - where hc.playerId in - and - and hc.activeSeats - and concat( '20', substring(hc.styleKey,2,2), '-', substring(hc.styleKey,4,2), '-' - , substring(hc.styleKey,6,2) ) - group by gt.base + if db_server == 'mysql': + self.query['playerDetailedStats'] = """ + select AS hgametypeid + , AS pname + ,gt.base + ,gt.category + ,upper(gt.limitType) AS limittype + ,s.name + ,min(gt.bigBlind) AS minbigblind + ,max(gt.bigBlind) AS maxbigblind + /*, AS gtid*/ + , AS plposition + ,count(1) AS n + ,100.0*sum(cast(hp.street0VPI as integer))/count(1) AS vpip + ,100.0*sum(cast(hp.street0Aggr as integer))/count(1) AS pfr + ,case when sum(cast(hp.street0_3Bchance as integer)) = 0 then -999 + else 100.0*sum(cast(hp.street0_3Bdone as integer))/sum(cast(hp.street0_3Bchance as integer)) + end AS pf3 + ,case when sum(cast(hp.stealattemptchance as integer)) = 0 then -999 + else 100.0*sum(cast(hp.stealattempted as integer))/sum(cast(hp.stealattemptchance as integer)) + end AS steals + ,100.0*sum(cast(hp.street1Seen as integer))/count(1) AS saw_f + ,100.0*sum(cast(hp.sawShowdown as integer))/count(1) AS sawsd + ,case when sum(cast(hp.street1Seen as integer)) = 0 then -999 + else 100.0*sum(cast(hp.sawShowdown as integer))/sum(cast(hp.street1Seen as integer)) + end AS wtsdwsf + ,case when sum(cast(hp.sawShowdown as integer)) = 0 then -999 + else 100.0*sum(cast(hp.wonAtSD as integer))/sum(cast(hp.sawShowdown as integer)) + end AS wmsd + ,case when sum(cast(hp.street1Seen as integer)) = 0 then -999 + else 100.0*sum(cast(hp.street1Aggr as integer))/sum(cast(hp.street1Seen as integer)) + end AS flafq + ,case when sum(cast(hp.street2Seen as integer)) = 0 then -999 + else 100.0*sum(cast(hp.street2Aggr as integer))/sum(cast(hp.street2Seen as integer)) + end AS tuafq + ,case when sum(cast(hp.street3Seen as integer)) = 0 then -999 + else 100.0*sum(cast(hp.street3Aggr as integer))/sum(cast(hp.street3Seen as integer)) + end AS rvafq + ,case when sum(cast(hp.street1Seen as integer))+sum(cast(hp.street2Seen as integer))+sum(cast(hp.street3Seen as integer)) = 0 then -999 + else 100.0*(sum(cast(hp.street1Aggr as integer))+sum(cast(hp.street2Aggr as integer))+sum(cast(hp.street3Aggr as integer))) + /(sum(cast(hp.street1Seen as integer))+sum(cast(hp.street2Seen as integer))+sum(cast(hp.street3Seen as integer))) + end AS pofafq + ,sum(hp.totalProfit)/100.0 AS net + ,sum(hp.rake)/100.0 AS rake + ,100.0*avg(hp.totalProfit/(gt.bigBlind+0.0)) AS bbper100 + ,avg(hp.totalProfit)/100.0 AS profitperhand + ,100.0*avg((hp.totalProfit+hp.rake)/(gt.bigBlind+0.0)) AS bb100xr + ,avg((hp.totalProfit+hp.rake)/100.0) AS profhndxr + ,avg(h.seats+0.0) AS avgseats + ,variance(hp.totalProfit/100.0) AS variance + from HandsPlayers hp + inner join Hands h on (h.id = hp.handId) + inner join Gametypes gt on (gt.Id = h.gameTypeId) + inner join Sites s on (s.Id = gt.siteId) + inner join Players p on (p.Id = hp.playerId) + where hp.playerId in + /*and hp.tourneysPlayersId IS NULL*/ + and h.seats + + + and date_format(h.handStart, '%Y-%m-%d') + group by hgameTypeId + ,pname + ,gt.base ,gt.category - ,upper(gt.limitType) - ,s.name - - ,gtId - ) stats - inner join - ( select # profit from handsplayers/handsactions - hprof.gtId, sum(hprof.profit) sum_profit, - avg(hprof.profit/100.0) profitperhand, - case when hprof.gtId = -1 then -999 - else variance(hprof.profit/100.0) - end as variance - from - (select hp.handId, as gtId, hp.totalProfit as profit - from HandsPlayers hp - inner join Hands h ON h.id = hp.handId - where hp.playerId in - and hp.tourneysPlayersId IS NULL - and date_format(h.handStart, '%Y-%m-%d') - group by hp.handId, gtId, hp.totalProfit - ) hprof - group by hprof.gtId - ) hprof2 - on hprof2.gtId = stats.gtId - order by stats.category, stats.limittype, stats.bigBlindDesc desc """ - else: # assume postgres - self.query['playerStats'] = """ - SELECT upper(stats.limitType) || ' ' - || initcap(stats.category) || ' ' - || stats.name || ' ' - || stats.bigBlindDesc AS Game - ,stats.n - ,stats.vpip - ,stats.pfr - ,stats.pf3 - ,stats.steals - ,stats.saw_f - ,stats.sawsd - ,stats.wtsdwsf - ,stats.wmsd - ,stats.FlAFq - ,stats.TuAFq - ,stats.RvAFq - ,stats.PoFAFq - ,stats.Net - ,stats.BBper100 - ,stats.Profitperhand - ,case when hprof2.variance = -999 then '-' - else to_char(hprof2.variance, '0D00') - end AS Variance - ,AvgSeats - FROM - (select gt.base - ,gt.category - ,upper(gt.limitType) AS limitType - ,s.name - , AS bigBlindDesc - , AS gtId - ,sum(HDs) as n - ,to_char(100.0*sum(street0VPI)/sum(HDs),'990D0') AS vpip - ,to_char(100.0*sum(street0Aggr)/sum(HDs),'90D0') AS pfr - ,case when sum(street0_3Bchance) = 0 then '0' - else to_char(100.0*sum(street0_3Bdone)/sum(street0_3Bchance),'90D0') - end AS pf3 - ,case when sum(stealattemptchance) = 0 then '-' - else to_char(100.0*sum(stealattempted)/sum(stealattemptchance),'90D0') - end AS steals - ,to_char(100.0*sum(street1Seen)/sum(HDs),'90D0') AS saw_f - ,to_char(100.0*sum(sawShowdown)/sum(HDs),'90D0') AS sawsd - ,case when sum(street1Seen) = 0 then '-' - else to_char(100.0*sum(sawShowdown)/sum(street1Seen),'90D0') - end AS wtsdwsf - ,case when sum(sawShowdown) = 0 then '-' - else to_char(100.0*sum(wonAtSD)/sum(sawShowdown),'90D0') - end AS wmsd - ,case when sum(street1Seen) = 0 then '-' - else to_char(100.0*sum(street1Aggr)/sum(street1Seen),'90D0') - end AS FlAFq - ,case when sum(street2Seen) = 0 then '-' - else to_char(100.0*sum(street2Aggr)/sum(street2Seen),'90D0') - end AS TuAFq - ,case when sum(street3Seen) = 0 then '-' - else to_char(100.0*sum(street3Aggr)/sum(street3Seen),'90D0') - end AS RvAFq - ,case when sum(street1Seen)+sum(street2Seen)+sum(street3Seen) = 0 then '-' - else to_char(100.0*(sum(street1Aggr)+sum(street2Aggr)+sum(street3Aggr)) - /(sum(street1Seen)+sum(street2Seen)+sum(street3Seen)),'90D0') - end AS PoFAFq - ,round(sum(totalProfit)/100.0,2) AS Net - ,to_char((sum(totalProfit/(gt.bigBlind+0.0))) / (sum(HDs)/100.0), '990D00') - AS BBper100 - ,to_char(sum(totalProfit/100.0) / (sum(HDs)+0.0), '990D0000') AS Profitperhand - ,to_char(sum(activeSeats*HDs)/(sum(HDs)+0.0),'90D00') AS AvgSeats - from Gametypes gt - inner join Sites s on s.Id = gt.siteId - inner join HudCache hc on hc.gameTypeId = gt.Id - where hc.playerId in - and - and hc.activeSeats - and '20' || SUBSTR(hc.styleKey,2,2) || '-' || SUBSTR(hc.styleKey,4,2) || '-' - || SUBSTR(hc.styleKey,6,2) - group by gt.base - ,gt.category - ,upper(gt.limitType) - ,s.name - - ,gtId - ) stats - inner join - ( select - hprof.gtId, sum(hprof.profit) AS sum_profit, - avg(hprof.profit/100.0) AS profitperhand, - case when hprof.gtId = -1 then -999 - else variance(hprof.profit/100.0) - end as variance - from - (select hp.handId, as gtId, hp.totalProfit as profit - from HandsPlayers hp - inner join Hands h ON (h.id = hp.handId) - where hp.playerId in - and hp.tourneysPlayersId IS NULL - and to_char(h.handStart, 'YYYY-MM-DD') - group by hp.handId, gtId, hp.totalProfit - ) hprof - group by hprof.gtId - ) hprof2 - on hprof2.gtId = stats.gtId - order by stats.base, stats.limittype, stats.bigBlindDesc desc """ - #elif db_server == 'sqlite': - # self.query['playerStats'] = """ """ - - if db_server == 'mysql': - self.query['playerStatsByPosition'] = """ - SELECT - concat(upper(stats.limitType), ' ' - ,concat(upper(substring(stats.category,1,1)),substring(stats.category,2) ), ' ' - ,stats.name, ' ' - ,cast(stats.bigBlindDesc as char) - ) AS Game - ,case when stats.PlPosition = -2 then 'BB' - when stats.PlPosition = -1 then 'SB' - when stats.PlPosition = 0 then 'Btn' - when stats.PlPosition = 1 then 'CO' - when stats.PlPosition = 2 then 'MP' - when stats.PlPosition = 5 then 'EP' - else 'xx' - end AS PlPosition - ,stats.n - ,stats.vpip - ,stats.pfr - ,stats.pf3 - ,stats.steals - ,stats.saw_f - ,stats.sawsd - ,stats.wtsdwsf - ,stats.wmsd - ,stats.FlAFq - ,stats.TuAFq - ,stats.RvAFq - ,stats.PoFAFq - ,stats.Net - ,stats.BBper100 - ,stats.Profitperhand - ,case when hprof2.variance = -999 then '-' - else format(hprof2.variance, 2) - end AS Variance - ,stats.AvgSeats - FROM - (select /* stats from hudcache */ - gt.base - ,gt.category - ,upper(gt.limitType) AS limitType - ,s.name - , AS bigBlindDesc - , AS gtId - ,case when hc.position = 'B' then -2 - when hc.position = 'S' then -1 - when hc.position = 'D' then 0 - when hc.position = 'C' then 1 - when hc.position = 'M' then 2 - when hc.position = 'E' then 5 - else 9 - end as PlPosition - ,sum(HDs) AS n - ,format(100.0*sum(street0VPI)/sum(HDs),1) AS vpip - ,format(100.0*sum(street0Aggr)/sum(HDs),1) AS pfr - ,case when sum(street0_3Bchance) = 0 then '0' - else format(100.0*sum(street0_3Bdone)/sum(street0_3Bchance),1) - end AS pf3 - ,case when sum(stealattemptchance) = 0 then '-' - else format(100.0*sum(stealattempted)/sum(stealattemptchance),1) - end AS steals - ,format(100.0*sum(street1Seen)/sum(HDs),1) AS saw_f - ,format(100.0*sum(sawShowdown)/sum(HDs),1) AS sawsd - ,case when sum(street1Seen) = 0 then '-' - else format(100.0*sum(sawShowdown)/sum(street1Seen),1) - end AS wtsdwsf - ,case when sum(sawShowdown) = 0 then '-' - else format(100.0*sum(wonAtSD)/sum(sawShowdown),1) - end AS wmsd - ,case when sum(street1Seen) = 0 then '-' - else format(100.0*sum(street1Aggr)/sum(street1Seen),1) - end AS FlAFq - ,case when sum(street2Seen) = 0 then '-' - else format(100.0*sum(street2Aggr)/sum(street2Seen),1) - end AS TuAFq - ,case when sum(street3Seen) = 0 then '-' - else format(100.0*sum(street3Aggr)/sum(street3Seen),1) - end AS RvAFq - ,case when sum(street1Seen)+sum(street2Seen)+sum(street3Seen) = 0 then '-' - else format(100.0*(sum(street1Aggr)+sum(street2Aggr)+sum(street3Aggr)) - /(sum(street1Seen)+sum(street2Seen)+sum(street3Seen)),1) - end AS PoFAFq - ,format(sum(totalProfit)/100.0,2) AS Net - ,format((sum(totalProfit/(gt.bigBlind+0.0))) / (sum(HDs)/100.0),2) - AS BBper100 - ,format( (sum(totalProfit)/100.0) / sum(HDs), 4) AS Profitperhand - ,format( sum(activeSeats*HDs)/(sum(HDs)+0.0), 2) AS AvgSeats - from Gametypes gt - inner join Sites s on s.Id = gt.siteId - inner join HudCache hc on hc.gameTypeId = gt.Id - where hc.playerId in - and - and hc.activeSeats - and concat( '20', substring(hc.styleKey,2,2), '-', substring(hc.styleKey,4,2), '-' - , substring(hc.styleKey,6,2) ) - group by gt.base - ,gt.category - ,upper(gt.limitType) - ,s.name - - ,gtId - ,PlPosition - ) stats - inner join - ( select # profit from handsplayers/handsactions - hprof.gtId, - case when hprof.position = 'B' then -2 - when hprof.position = 'S' then -1 - when hprof.position in ('3','4') then 2 - when hprof.position in ('6','7') then 5 - else hprof.position - end as PlPosition, - sum(hprof.profit) as sum_profit, - avg(hprof.profit/100.0) as profitperhand, - case when hprof.gtId = -1 then -999 - else variance(hprof.profit/100.0) - end as variance - from - (select hp.handId, as gtId, hp.position - , hp.totalProfit as profit - from HandsPlayers hp - inner join Hands h ON (h.id = hp.handId) - where hp.playerId in - and hp.tourneysPlayersId IS NULL - and date_format(h.handStart, '%Y-%m-%d') - group by hp.handId, gtId, hp.position, hp.totalProfit - ) hprof - group by hprof.gtId, PlPosition - ) hprof2 - on ( hprof2.gtId = stats.gtId - and hprof2.PlPosition = stats.PlPosition) - order by stats.category, stats.limitType, stats.bigBlindDesc desc - , cast(stats.PlPosition as signed) - """ - else: # assume postgresql - self.query['playerStatsByPosition'] = """ - select /* stats from hudcache */ - upper(stats.limitType) || ' ' - || upper(substr(stats.category,1,1)) || substr(stats.category,2) || ' ' - || stats.name || ' ' - || stats.bigBlindDesc AS Game - ,case when stats.PlPosition = -2 then 'BB' - when stats.PlPosition = -1 then 'SB' - when stats.PlPosition = 0 then 'Btn' - when stats.PlPosition = 1 then 'CO' - when stats.PlPosition = 2 then 'MP' - when stats.PlPosition = 5 then 'EP' - else 'xx' - end AS PlPosition - ,stats.n - ,stats.vpip - ,stats.pfr - ,stats.pf3 - ,stats.steals - ,stats.saw_f - ,stats.sawsd - ,stats.wtsdwsf - ,stats.wmsd - ,stats.FlAFq - ,stats.TuAFq - ,stats.RvAFq - ,stats.PoFAFq - ,stats.Net - ,stats.BBper100 - ,stats.Profitperhand - ,case when hprof2.variance = -999 then '-' - else to_char(hprof2.variance, '0D00') - end AS Variance - ,stats.AvgSeats - FROM - (select /* stats from hudcache */ - gt.base - ,gt.category - ,upper(gt.limitType) AS limitType - ,s.name - , AS bigBlindDesc - , AS gtId - ,case when hc.position = 'B' then -2 - when hc.position = 'S' then -1 - when hc.position = 'D' then 0 - when hc.position = 'C' then 1 - when hc.position = 'M' then 2 - when hc.position = 'E' then 5 - else 9 - end AS PlPosition - ,sum(HDs) AS n - ,to_char(round(100.0*sum(street0VPI)/sum(HDs)),'990D0') AS vpip - ,to_char(round(100.0*sum(street0Aggr)/sum(HDs)),'90D0') AS pfr - ,case when sum(street0_3Bchance) = 0 then '0' - else to_char(100.0*sum(street0_3Bdone)/sum(street0_3Bchance),'90D0') - end AS pf3 - ,case when sum(stealattemptchance) = 0 then '-' - else to_char(100.0*sum(stealattempted)/sum(stealattemptchance),'90D0') - end AS steals - ,to_char(round(100.0*sum(street1Seen)/sum(HDs)),'90D0') AS saw_f - ,to_char(round(100.0*sum(sawShowdown)/sum(HDs)),'90D0') AS sawsd - ,case when sum(street1Seen) = 0 then '-' - else to_char(round(100.0*sum(sawShowdown)/sum(street1Seen)),'90D0') - end AS wtsdwsf - ,case when sum(sawShowdown) = 0 then '-' - else to_char(round(100.0*sum(wonAtSD)/sum(sawShowdown)),'90D0') - end AS wmsd - ,case when sum(street1Seen) = 0 then '-' - else to_char(round(100.0*sum(street1Aggr)/sum(street1Seen)),'90D0') - end AS FlAFq - ,case when sum(street2Seen) = 0 then '-' - else to_char(round(100.0*sum(street2Aggr)/sum(street2Seen)),'90D0') - end AS TuAFq - ,case when sum(street3Seen) = 0 then '-' - else to_char(round(100.0*sum(street3Aggr)/sum(street3Seen)),'90D0') - end AS RvAFq - ,case when sum(street1Seen)+sum(street2Seen)+sum(street3Seen) = 0 then '-' - else to_char(round(100.0*(sum(street1Aggr)+sum(street2Aggr)+sum(street3Aggr)) - /(sum(street1Seen)+sum(street2Seen)+sum(street3Seen))),'90D0') - end AS PoFAFq - ,to_char(sum(totalProfit)/100.0,'9G999G990D00') AS Net - ,case when sum(HDs) = 0 then '0' - else to_char(sum(totalProfit/(gt.bigBlind+0.0)) / (sum(HDs)/100.0), '990D00') - end AS BBper100 - ,case when sum(HDs) = 0 then '0' - else to_char( (sum(totalProfit)/100.0) / sum(HDs), '90D0000') - end AS Profitperhand - ,to_char(sum(activeSeats*HDs)/(sum(HDs)+0.0),'90D00') AS AvgSeats - from Gametypes gt - inner join Sites s on (s.Id = gt.siteId) - inner join HudCache hc on (hc.gameTypeId = gt.Id) - where hc.playerId in - and - and hc.activeSeats - and '20' || SUBSTR(hc.styleKey,2,2) || '-' || SUBSTR(hc.styleKey,4,2) || '-' - || SUBSTR(hc.styleKey,6,2) - group by gt.base - ,gt.category + ,plposition ,upper(gt.limitType) ,s.name - - ,gtId + having 1 = 1 + order by pname + ,gt.base + ,gt.category + + ,case when 'B' then 'B' + when 'S' then 'S' + else concat('Z', ) + end + + ,upper(gt.limitType) desc + ,maxbigblind desc + ,s.name + """ + elif db_server == 'postgresql': + self.query['playerDetailedStats'] = """ + select AS hgametypeid + , AS pname + ,gt.base + ,gt.category + ,upper(gt.limitType) AS limittype + ,s.name + ,min(gt.bigBlind) AS minbigblind + ,max(gt.bigBlind) AS maxbigblind + /*, AS gtid*/ + , AS plposition + ,count(1) AS n + ,100.0*sum(cast(hp.street0VPI as integer))/count(1) AS vpip + ,100.0*sum(cast(hp.street0Aggr as integer))/count(1) AS pfr + ,case when sum(cast(hp.street0_3Bchance as integer)) = 0 then -999 + else 100.0*sum(cast(hp.street0_3Bdone as integer))/sum(cast(hp.street0_3Bchance as integer)) + end AS pf3 + ,case when sum(cast(hp.stealattemptchance as integer)) = 0 then -999 + else 100.0*sum(cast(hp.stealattempted as integer))/sum(cast(hp.stealattemptchance as integer)) + end AS steals + ,100.0*sum(cast(hp.street1Seen as integer))/count(1) AS saw_f + ,100.0*sum(cast(hp.sawShowdown as integer))/count(1) AS sawsd + ,case when sum(cast(hp.street1Seen as integer)) = 0 then -999 + else 100.0*sum(cast(hp.sawShowdown as integer))/sum(cast(hp.street1Seen as integer)) + end AS wtsdwsf + ,case when sum(cast(hp.sawShowdown as integer)) = 0 then -999 + else 100.0*sum(cast(hp.wonAtSD as integer))/sum(cast(hp.sawShowdown as integer)) + end AS wmsd + ,case when sum(cast(hp.street1Seen as integer)) = 0 then -999 + else 100.0*sum(cast(hp.street1Aggr as integer))/sum(cast(hp.street1Seen as integer)) + end AS flafq + ,case when sum(cast(hp.street2Seen as integer)) = 0 then -999 + else 100.0*sum(cast(hp.street2Aggr as integer))/sum(cast(hp.street2Seen as integer)) + end AS tuafq + ,case when sum(cast(hp.street3Seen as integer)) = 0 then -999 + else 100.0*sum(cast(hp.street3Aggr as integer))/sum(cast(hp.street3Seen as integer)) + end AS rvafq + ,case when sum(cast(hp.street1Seen as integer))+sum(cast(hp.street2Seen as integer))+sum(cast(hp.street3Seen as integer)) = 0 then -999 + else 100.0*(sum(cast(hp.street1Aggr as integer))+sum(cast(hp.street2Aggr as integer))+sum(cast(hp.street3Aggr as integer))) + /(sum(cast(hp.street1Seen as integer))+sum(cast(hp.street2Seen as integer))+sum(cast(hp.street3Seen as integer))) + end AS pofafq + ,sum(hp.totalProfit)/100.0 AS net + ,sum(hp.rake)/100.0 AS rake + ,100.0*avg(hp.totalProfit/(gt.bigBlind+0.0)) AS bbper100 + ,avg(hp.totalProfit)/100.0 AS profitperhand + ,100.0*avg((hp.totalProfit+hp.rake)/(gt.bigBlind+0.0)) AS bb100xr + ,avg((hp.totalProfit+hp.rake)/100.0) AS profhndxr + ,avg(h.seats+0.0) AS avgseats + ,variance(hp.totalProfit/100.0) AS variance + from HandsPlayers hp + inner join Hands h on (h.id = hp.handId) + inner join Gametypes gt on (gt.Id = h.gameTypeId) + inner join Sites s on (s.Id = gt.siteId) + inner join Players p on (p.Id = hp.playerId) + where hp.playerId in + /*and hp.tourneysPlayersId IS NULL*/ + and h.seats + + + and to_char(h.handStart, 'YYYY-MM-DD') + group by hgameTypeId + ,pname + ,gt.base + ,gt.category - ,PlPosition - ) stats - inner join - ( select /* profit from handsplayers/handsactions */ - hprof.gtId, - case when hprof.position = 'B' then -2 - when hprof.position = 'S' then -1 - when hprof.position in ('3','4') then 2 - when hprof.position in ('6','7') then 5 - else cast(hprof.position as smallint) - end as PlPosition, - sum(hprof.profit) as sum_profit, - avg(hprof.profit/100.0) as profitperhand, - case when hprof.gtId = -1 then -999 - else variance(hprof.profit/100.0) - end as variance - from - (select hp.handId, as gtId, hp.position - , hp.totalProfit as profit - from HandsPlayers hp - inner join Hands h ON (h.id = hp.handId) - where hp.playerId in - and hp.tourneysPlayersId IS NULL - and to_char(h.handStart, 'YYYY-MM-DD') - group by hp.handId, gameTypeId, hp.position, hp.totalProfit - ) hprof - group by hprof.gtId, PlPosition - ) hprof2 - on ( hprof2.gtId = stats.gtId - and hprof2.PlPosition = stats.PlPosition) - order by stats.category, stats.limitType, stats.bigBlindDesc desc - , cast(stats.PlPosition as smallint) - """ - #elif db_server == 'sqlite': - # self.query['playerStatsByPosition'] = """ """ + ,plposition + ,upper(gt.limitType) + ,s.name + having 1 = 1 + order by pname + ,gt.base + ,gt.category + + ,case when 'B' then 'B' + when 'S' then 'S' + when '0' then 'Y' + else 'Z'|| + end + + ,upper(gt.limitType) desc + ,maxbigblind desc + ,s.name + """ + elif db_server == 'sqlite': + self.query['playerDetailedStats'] = """ + select AS hgametypeid + ,gt.base + ,gt.category + ,upper(gt.limitType) AS limittype + ,s.name + ,min(gt.bigBlind) AS minbigblind + ,max(gt.bigBlind) AS maxbigblind + /*, AS gtid*/ + , AS plposition + ,count(1) AS n + ,100.0*sum(cast(hp.street0VPI as integer))/count(1) AS vpip + ,100.0*sum(cast(hp.street0Aggr as integer))/count(1) AS pfr + ,case when sum(cast(hp.street0_3Bchance as integer)) = 0 then -999 + else 100.0*sum(cast(hp.street0_3Bdone as integer))/sum(cast(hp.street0_3Bchance as integer)) + end AS pf3 + ,case when sum(cast(hp.stealattemptchance as integer)) = 0 then -999 + else 100.0*sum(cast(hp.stealattempted as integer))/sum(cast(hp.stealattemptchance as integer)) + end AS steals + ,100.0*sum(cast(hp.street1Seen as integer))/count(1) AS saw_f + ,100.0*sum(cast(hp.sawShowdown as integer))/count(1) AS sawsd + ,case when sum(cast(hp.street1Seen as integer)) = 0 then -999 + else 100.0*sum(cast(hp.sawShowdown as integer))/sum(cast(hp.street1Seen as integer)) + end AS wtsdwsf + ,case when sum(cast(hp.sawShowdown as integer)) = 0 then -999 + else 100.0*sum(cast(hp.wonAtSD as integer))/sum(cast(hp.sawShowdown as integer)) + end AS wmsd + ,case when sum(cast(hp.street1Seen as integer)) = 0 then -999 + else 100.0*sum(cast(hp.street1Aggr as integer))/sum(cast(hp.street1Seen as integer)) + end AS flafq + ,case when sum(cast(hp.street2Seen as integer)) = 0 then -999 + else 100.0*sum(cast(hp.street2Aggr as integer))/sum(cast(hp.street2Seen as integer)) + end AS tuafq + ,case when sum(cast(hp.street3Seen as integer)) = 0 then -999 + else 100.0*sum(cast(hp.street3Aggr as integer))/sum(cast(hp.street3Seen as integer)) + end AS rvafq + ,case when sum(cast(hp.street1Seen as integer))+sum(cast(hp.street2Seen as integer))+sum(cast(hp.street3Seen as integer)) = 0 then -999 + else 100.0*(sum(cast(hp.street1Aggr as integer))+sum(cast(hp.street2Aggr as integer))+sum(cast(hp.street3Aggr as integer))) + /(sum(cast(hp.street1Seen as integer))+sum(cast(hp.street2Seen as integer))+sum(cast(hp.street3Seen as integer))) + end AS pofafq + ,sum(hp.totalProfit)/100.0 AS net + ,sum(hp.rake)/100.0 AS rake + ,100.0*avg(hp.totalProfit/(gt.bigBlind+0.0)) AS bbper100 + ,avg(hp.totalProfit)/100.0 AS profitperhand + ,100.0*avg((hp.totalProfit+hp.rake)/(gt.bigBlind+0.0)) AS bb100xr + ,avg((hp.totalProfit+hp.rake)/100.0) AS profhndxr + ,avg(h.seats+0.0) AS avgseats + ,variance(hp.totalProfit/100.0) AS variance + from HandsPlayers hp + inner join Hands h on (h.id = hp.handId) + inner join Gametypes gt on (gt.Id = h.gameTypeId) + inner join Sites s on (s.Id = gt.siteId) + where hp.playerId in + /*and hp.tourneysPlayersId IS NULL*/ + and h.seats + + + and to_char(h.handStart, 'YYYY-MM-DD') + group by hgameTypeId + ,hp.playerId + ,gt.base + ,gt.category + + ,plposition + ,upper(gt.limitType) + ,s.name + order by hp.playerId + ,gt.base + ,gt.category + + ,case when 'B' then 'B' + when 'S' then 'S' + when '0' then 'Y' + else 'Z'|| + end + + ,upper(gt.limitType) desc + ,maxbigblind desc + ,s.name + """ - self.query['getRingProfitAllHandsPlayerIdSite'] = """ - SELECT hp.handId, hp.totalProfit + if db_server == 'mysql': + self.query['playerStats'] = """ + SELECT + concat(upper(stats.limitType), ' ' + ,concat(upper(substring(stats.category,1,1)),substring(stats.category,2) ), ' ' + ,stats.name, ' ' + ,cast(stats.bigBlindDesc as char) + ) AS Game + ,stats.n + ,stats.vpip + ,stats.pfr + ,stats.pf3 + ,stats.steals + ,stats.saw_f + ,stats.sawsd + ,stats.wtsdwsf + ,stats.wmsd + ,stats.FlAFq + ,stats.TuAFq + ,stats.RvAFq + ,stats.PoFAFq + ,stats.Net + ,stats.BBper100 + ,stats.Profitperhand + ,case when hprof2.variance = -999 then '-' + else format(hprof2.variance, 2) + end AS Variance + ,stats.AvgSeats + FROM + (select /* stats from hudcache */ + gt.base + ,gt.category + ,upper(gt.limitType) as limitType + ,s.name + , AS bigBlindDesc + , AS gtId + ,sum(HDs) AS n + ,format(100.0*sum(street0VPI)/sum(HDs),1) AS vpip + ,format(100.0*sum(street0Aggr)/sum(HDs),1) AS pfr + ,case when sum(street0_3Bchance) = 0 then '0' + else format(100.0*sum(street0_3Bdone)/sum(street0_3Bchance),1) + end AS pf3 + ,case when sum(stealattemptchance) = 0 then '-' + else format(100.0*sum(stealattempted)/sum(stealattemptchance),1) + end AS steals + ,format(100.0*sum(street1Seen)/sum(HDs),1) AS saw_f + ,format(100.0*sum(sawShowdown)/sum(HDs),1) AS sawsd + ,case when sum(street1Seen) = 0 then '-' + else format(100.0*sum(sawShowdown)/sum(street1Seen),1) + end AS wtsdwsf + ,case when sum(sawShowdown) = 0 then '-' + else format(100.0*sum(wonAtSD)/sum(sawShowdown),1) + end AS wmsd + ,case when sum(street1Seen) = 0 then '-' + else format(100.0*sum(street1Aggr)/sum(street1Seen),1) + end AS FlAFq + ,case when sum(street2Seen) = 0 then '-' + else format(100.0*sum(street2Aggr)/sum(street2Seen),1) + end AS TuAFq + ,case when sum(street3Seen) = 0 then '-' + else format(100.0*sum(street3Aggr)/sum(street3Seen),1) + end AS RvAFq + ,case when sum(street1Seen)+sum(street2Seen)+sum(street3Seen) = 0 then '-' + else format(100.0*(sum(street1Aggr)+sum(street2Aggr)+sum(street3Aggr)) + /(sum(street1Seen)+sum(street2Seen)+sum(street3Seen)),1) + end AS PoFAFq + ,format(sum(totalProfit)/100.0,2) AS Net + ,format((sum(totalProfit/(gt.bigBlind+0.0))) / (sum(HDs)/100.0),2) + AS BBper100 + ,format( (sum(totalProfit)/100.0) / sum(HDs), 4) AS Profitperhand + ,format( sum(activeSeats*HDs)/(sum(HDs)+0.0), 2) AS AvgSeats + from Gametypes gt + inner join Sites s on s.Id = gt.siteId + inner join HudCache hc on hc.gameTypeId = gt.Id + where hc.playerId in + and + and hc.activeSeats + and concat( '20', substring(hc.styleKey,2,2), '-', substring(hc.styleKey,4,2), '-' + , substring(hc.styleKey,6,2) ) + group by gt.base + ,gt.category + ,upper(gt.limitType) + ,s.name + + ,gtId + ) stats + inner join + ( select # profit from handsplayers/handsactions + hprof.gtId, sum(hprof.profit) sum_profit, + avg(hprof.profit/100.0) profitperhand, + case when hprof.gtId = -1 then -999 + else variance(hprof.profit/100.0) + end as variance + from + (select hp.handId, as gtId, hp.totalProfit as profit + from HandsPlayers hp + inner join Hands h ON h.id = hp.handId + where hp.playerId in + and hp.tourneysPlayersId IS NULL + and date_format(h.handStart, '%Y-%m-%d') + group by hp.handId, gtId, hp.totalProfit + ) hprof + group by hprof.gtId + ) hprof2 + on hprof2.gtId = stats.gtId + order by stats.category, stats.limittype, stats.bigBlindDesc desc """ + else: # assume postgres + self.query['playerStats'] = """ + SELECT upper(stats.limitType) || ' ' + || initcap(stats.category) || ' ' + || stats.name || ' ' + || stats.bigBlindDesc AS Game + ,stats.n + ,stats.vpip + ,stats.pfr + ,stats.pf3 + ,stats.steals + ,stats.saw_f + ,stats.sawsd + ,stats.wtsdwsf + ,stats.wmsd + ,stats.FlAFq + ,stats.TuAFq + ,stats.RvAFq + ,stats.PoFAFq + ,stats.Net + ,stats.BBper100 + ,stats.Profitperhand + ,case when hprof2.variance = -999 then '-' + else to_char(hprof2.variance, '0D00') + end AS Variance + ,AvgSeats + FROM + (select gt.base + ,gt.category + ,upper(gt.limitType) AS limitType + ,s.name + , AS bigBlindDesc + , AS gtId + ,sum(HDs) as n + ,to_char(100.0*sum(street0VPI)/sum(HDs),'990D0') AS vpip + ,to_char(100.0*sum(street0Aggr)/sum(HDs),'90D0') AS pfr + ,case when sum(street0_3Bchance) = 0 then '0' + else to_char(100.0*sum(street0_3Bdone)/sum(street0_3Bchance),'90D0') + end AS pf3 + ,case when sum(stealattemptchance) = 0 then '-' + else to_char(100.0*sum(stealattempted)/sum(stealattemptchance),'90D0') + end AS steals + ,to_char(100.0*sum(street1Seen)/sum(HDs),'90D0') AS saw_f + ,to_char(100.0*sum(sawShowdown)/sum(HDs),'90D0') AS sawsd + ,case when sum(street1Seen) = 0 then '-' + else to_char(100.0*sum(sawShowdown)/sum(street1Seen),'90D0') + end AS wtsdwsf + ,case when sum(sawShowdown) = 0 then '-' + else to_char(100.0*sum(wonAtSD)/sum(sawShowdown),'90D0') + end AS wmsd + ,case when sum(street1Seen) = 0 then '-' + else to_char(100.0*sum(street1Aggr)/sum(street1Seen),'90D0') + end AS FlAFq + ,case when sum(street2Seen) = 0 then '-' + else to_char(100.0*sum(street2Aggr)/sum(street2Seen),'90D0') + end AS TuAFq + ,case when sum(street3Seen) = 0 then '-' + else to_char(100.0*sum(street3Aggr)/sum(street3Seen),'90D0') + end AS RvAFq + ,case when sum(street1Seen)+sum(street2Seen)+sum(street3Seen) = 0 then '-' + else to_char(100.0*(sum(street1Aggr)+sum(street2Aggr)+sum(street3Aggr)) + /(sum(street1Seen)+sum(street2Seen)+sum(street3Seen)),'90D0') + end AS PoFAFq + ,round(sum(totalProfit)/100.0,2) AS Net + ,to_char((sum(totalProfit/(gt.bigBlind+0.0))) / (sum(HDs)/100.0), '990D00') + AS BBper100 + ,to_char(sum(totalProfit/100.0) / (sum(HDs)+0.0), '990D0000') AS Profitperhand + ,to_char(sum(activeSeats*HDs)/(sum(HDs)+0.0),'90D00') AS AvgSeats + from Gametypes gt + inner join Sites s on s.Id = gt.siteId + inner join HudCache hc on hc.gameTypeId = gt.Id + where hc.playerId in + and + and hc.activeSeats + and '20' || SUBSTR(hc.styleKey,2,2) || '-' || SUBSTR(hc.styleKey,4,2) || '-' + || SUBSTR(hc.styleKey,6,2) + group by gt.base + ,gt.category + ,upper(gt.limitType) + ,s.name + + ,gtId + ) stats + inner join + ( select + hprof.gtId, sum(hprof.profit) AS sum_profit, + avg(hprof.profit/100.0) AS profitperhand, + case when hprof.gtId = -1 then -999 + else variance(hprof.profit/100.0) + end as variance + from + (select hp.handId, as gtId, hp.totalProfit as profit + from HandsPlayers hp + inner join Hands h ON (h.id = hp.handId) + where hp.playerId in + and hp.tourneysPlayersId IS NULL + and to_char(h.handStart, 'YYYY-MM-DD') + group by hp.handId, gtId, hp.totalProfit + ) hprof + group by hprof.gtId + ) hprof2 + on hprof2.gtId = stats.gtId + order by stats.base, stats.limittype, stats.bigBlindDesc desc """ + #elif db_server == 'sqlite': + # self.query['playerStats'] = """ """ + + if db_server == 'mysql': + self.query['playerStatsByPosition'] = """ + SELECT + concat(upper(stats.limitType), ' ' + ,concat(upper(substring(stats.category,1,1)),substring(stats.category,2) ), ' ' + ,stats.name, ' ' + ,cast(stats.bigBlindDesc as char) + ) AS Game + ,case when stats.PlPosition = -2 then 'BB' + when stats.PlPosition = -1 then 'SB' + when stats.PlPosition = 0 then 'Btn' + when stats.PlPosition = 1 then 'CO' + when stats.PlPosition = 2 then 'MP' + when stats.PlPosition = 5 then 'EP' + else 'xx' + end AS PlPosition + ,stats.n + ,stats.vpip + ,stats.pfr + ,stats.pf3 + ,stats.steals + ,stats.saw_f + ,stats.sawsd + ,stats.wtsdwsf + ,stats.wmsd + ,stats.FlAFq + ,stats.TuAFq + ,stats.RvAFq + ,stats.PoFAFq + ,stats.Net + ,stats.BBper100 + ,stats.Profitperhand + ,case when hprof2.variance = -999 then '-' + else format(hprof2.variance, 2) + end AS Variance + ,stats.AvgSeats + FROM + (select /* stats from hudcache */ + gt.base + ,gt.category + ,upper(gt.limitType) AS limitType + ,s.name + , AS bigBlindDesc + , AS gtId + ,case when hc.position = 'B' then -2 + when hc.position = 'S' then -1 + when hc.position = 'D' then 0 + when hc.position = 'C' then 1 + when hc.position = 'M' then 2 + when hc.position = 'E' then 5 + else 9 + end as PlPosition + ,sum(HDs) AS n + ,format(100.0*sum(street0VPI)/sum(HDs),1) AS vpip + ,format(100.0*sum(street0Aggr)/sum(HDs),1) AS pfr + ,case when sum(street0_3Bchance) = 0 then '0' + else format(100.0*sum(street0_3Bdone)/sum(street0_3Bchance),1) + end AS pf3 + ,case when sum(stealattemptchance) = 0 then '-' + else format(100.0*sum(stealattempted)/sum(stealattemptchance),1) + end AS steals + ,format(100.0*sum(street1Seen)/sum(HDs),1) AS saw_f + ,format(100.0*sum(sawShowdown)/sum(HDs),1) AS sawsd + ,case when sum(street1Seen) = 0 then '-' + else format(100.0*sum(sawShowdown)/sum(street1Seen),1) + end AS wtsdwsf + ,case when sum(sawShowdown) = 0 then '-' + else format(100.0*sum(wonAtSD)/sum(sawShowdown),1) + end AS wmsd + ,case when sum(street1Seen) = 0 then '-' + else format(100.0*sum(street1Aggr)/sum(street1Seen),1) + end AS FlAFq + ,case when sum(street2Seen) = 0 then '-' + else format(100.0*sum(street2Aggr)/sum(street2Seen),1) + end AS TuAFq + ,case when sum(street3Seen) = 0 then '-' + else format(100.0*sum(street3Aggr)/sum(street3Seen),1) + end AS RvAFq + ,case when sum(street1Seen)+sum(street2Seen)+sum(street3Seen) = 0 then '-' + else format(100.0*(sum(street1Aggr)+sum(street2Aggr)+sum(street3Aggr)) + /(sum(street1Seen)+sum(street2Seen)+sum(street3Seen)),1) + end AS PoFAFq + ,format(sum(totalProfit)/100.0,2) AS Net + ,format((sum(totalProfit/(gt.bigBlind+0.0))) / (sum(HDs)/100.0),2) + AS BBper100 + ,format( (sum(totalProfit)/100.0) / sum(HDs), 4) AS Profitperhand + ,format( sum(activeSeats*HDs)/(sum(HDs)+0.0), 2) AS AvgSeats + from Gametypes gt + inner join Sites s on s.Id = gt.siteId + inner join HudCache hc on hc.gameTypeId = gt.Id + where hc.playerId in + and + and hc.activeSeats + and concat( '20', substring(hc.styleKey,2,2), '-', substring(hc.styleKey,4,2), '-' + , substring(hc.styleKey,6,2) ) + group by gt.base + ,gt.category + ,upper(gt.limitType) + ,s.name + + ,gtId + + ,PlPosition + ) stats + inner join + ( select # profit from handsplayers/handsactions + hprof.gtId, + case when hprof.position = 'B' then -2 + when hprof.position = 'S' then -1 + when hprof.position in ('3','4') then 2 + when hprof.position in ('6','7') then 5 + else hprof.position + end as PlPosition, + sum(hprof.profit) as sum_profit, + avg(hprof.profit/100.0) as profitperhand, + case when hprof.gtId = -1 then -999 + else variance(hprof.profit/100.0) + end as variance + from + (select hp.handId, as gtId, hp.position + , hp.totalProfit as profit + from HandsPlayers hp + inner join Hands h ON (h.id = hp.handId) + where hp.playerId in + and hp.tourneysPlayersId IS NULL + and date_format(h.handStart, '%Y-%m-%d') + group by hp.handId, gtId, hp.position, hp.totalProfit + ) hprof + group by hprof.gtId, PlPosition + ) hprof2 + on ( hprof2.gtId = stats.gtId + and hprof2.PlPosition = stats.PlPosition) + order by stats.category, stats.limitType, stats.bigBlindDesc desc + , cast(stats.PlPosition as signed) + """ + else: # assume postgresql + self.query['playerStatsByPosition'] = """ + select /* stats from hudcache */ + upper(stats.limitType) || ' ' + || upper(substr(stats.category,1,1)) || substr(stats.category,2) || ' ' + || stats.name || ' ' + || stats.bigBlindDesc AS Game + ,case when stats.PlPosition = -2 then 'BB' + when stats.PlPosition = -1 then 'SB' + when stats.PlPosition = 0 then 'Btn' + when stats.PlPosition = 1 then 'CO' + when stats.PlPosition = 2 then 'MP' + when stats.PlPosition = 5 then 'EP' + else 'xx' + end AS PlPosition + ,stats.n + ,stats.vpip + ,stats.pfr + ,stats.pf3 + ,stats.steals + ,stats.saw_f + ,stats.sawsd + ,stats.wtsdwsf + ,stats.wmsd + ,stats.FlAFq + ,stats.TuAFq + ,stats.RvAFq + ,stats.PoFAFq + ,stats.Net + ,stats.BBper100 + ,stats.Profitperhand + ,case when hprof2.variance = -999 then '-' + else to_char(hprof2.variance, '0D00') + end AS Variance + ,stats.AvgSeats + FROM + (select /* stats from hudcache */ + gt.base + ,gt.category + ,upper(gt.limitType) AS limitType + ,s.name + , AS bigBlindDesc + , AS gtId + ,case when hc.position = 'B' then -2 + when hc.position = 'S' then -1 + when hc.position = 'D' then 0 + when hc.position = 'C' then 1 + when hc.position = 'M' then 2 + when hc.position = 'E' then 5 + else 9 + end AS PlPosition + ,sum(HDs) AS n + ,to_char(round(100.0*sum(street0VPI)/sum(HDs)),'990D0') AS vpip + ,to_char(round(100.0*sum(street0Aggr)/sum(HDs)),'90D0') AS pfr + ,case when sum(street0_3Bchance) = 0 then '0' + else to_char(100.0*sum(street0_3Bdone)/sum(street0_3Bchance),'90D0') + end AS pf3 + ,case when sum(stealattemptchance) = 0 then '-' + else to_char(100.0*sum(stealattempted)/sum(stealattemptchance),'90D0') + end AS steals + ,to_char(round(100.0*sum(street1Seen)/sum(HDs)),'90D0') AS saw_f + ,to_char(round(100.0*sum(sawShowdown)/sum(HDs)),'90D0') AS sawsd + ,case when sum(street1Seen) = 0 then '-' + else to_char(round(100.0*sum(sawShowdown)/sum(street1Seen)),'90D0') + end AS wtsdwsf + ,case when sum(sawShowdown) = 0 then '-' + else to_char(round(100.0*sum(wonAtSD)/sum(sawShowdown)),'90D0') + end AS wmsd + ,case when sum(street1Seen) = 0 then '-' + else to_char(round(100.0*sum(street1Aggr)/sum(street1Seen)),'90D0') + end AS FlAFq + ,case when sum(street2Seen) = 0 then '-' + else to_char(round(100.0*sum(street2Aggr)/sum(street2Seen)),'90D0') + end AS TuAFq + ,case when sum(street3Seen) = 0 then '-' + else to_char(round(100.0*sum(street3Aggr)/sum(street3Seen)),'90D0') + end AS RvAFq + ,case when sum(street1Seen)+sum(street2Seen)+sum(street3Seen) = 0 then '-' + else to_char(round(100.0*(sum(street1Aggr)+sum(street2Aggr)+sum(street3Aggr)) + /(sum(street1Seen)+sum(street2Seen)+sum(street3Seen))),'90D0') + end AS PoFAFq + ,to_char(sum(totalProfit)/100.0,'9G999G990D00') AS Net + ,case when sum(HDs) = 0 then '0' + else to_char(sum(totalProfit/(gt.bigBlind+0.0)) / (sum(HDs)/100.0), '990D00') + end AS BBper100 + ,case when sum(HDs) = 0 then '0' + else to_char( (sum(totalProfit)/100.0) / sum(HDs), '90D0000') + end AS Profitperhand + ,to_char(sum(activeSeats*HDs)/(sum(HDs)+0.0),'90D00') AS AvgSeats + from Gametypes gt + inner join Sites s on (s.Id = gt.siteId) + inner join HudCache hc on (hc.gameTypeId = gt.Id) + where hc.playerId in + and + and hc.activeSeats + and '20' || SUBSTR(hc.styleKey,2,2) || '-' || SUBSTR(hc.styleKey,4,2) || '-' + || SUBSTR(hc.styleKey,6,2) + group by gt.base + ,gt.category + ,upper(gt.limitType) + ,s.name + + ,gtId + + ,PlPosition + ) stats + inner join + ( select /* profit from handsplayers/handsactions */ + hprof.gtId, + case when hprof.position = 'B' then -2 + when hprof.position = 'S' then -1 + when hprof.position in ('3','4') then 2 + when hprof.position in ('6','7') then 5 + else cast(hprof.position as smallint) + end as PlPosition, + sum(hprof.profit) as sum_profit, + avg(hprof.profit/100.0) as profitperhand, + case when hprof.gtId = -1 then -999 + else variance(hprof.profit/100.0) + end as variance + from + (select hp.handId, as gtId, hp.position + , hp.totalProfit as profit + from HandsPlayers hp + inner join Hands h ON (h.id = hp.handId) + where hp.playerId in + and hp.tourneysPlayersId IS NULL + and to_char(h.handStart, 'YYYY-MM-DD') + group by hp.handId, gameTypeId, hp.position, hp.totalProfit + ) hprof + group by hprof.gtId, PlPosition + ) hprof2 + on ( hprof2.gtId = stats.gtId + and hprof2.PlPosition = stats.PlPosition) + order by stats.category, stats.limitType, stats.bigBlindDesc desc + , cast(stats.PlPosition as smallint) + """ + #elif db_server == 'sqlite': + # self.query['playerStatsByPosition'] = """ """ + + self.query['getRingProfitAllHandsPlayerIdSite'] = """ + SELECT hp.handId, hp.totalProfit + FROM HandsPlayers hp + INNER JOIN Players pl ON (pl.id = hp.playerId) + INNER JOIN Hands h ON (h.id = hp.handId) + INNER JOIN Gametypes gt ON (gt.id = h.gametypeId) + WHERE pl.id in + AND pl.siteId in + AND h.handStart > '' + AND h.handStart < '' + + AND hp.tourneysPlayersId IS NULL + GROUP BY h.handStart, hp.handId, hp.totalProfit + ORDER BY h.handStart""" + + #################################### + # Session stats query + #################################### + if db_server == 'mysql': + self.query['sessionStats'] = """ + SELECT UNIX_TIMESTAMP(h.handStart) as time, hp.handId, hp.startCash, hp.winnings, hp.totalProfit FROM HandsPlayers hp - INNER JOIN Players pl ON (pl.id = hp.playerId) - INNER JOIN Hands h ON (h.id = hp.handId) - INNER JOIN Gametypes gt ON (gt.id = h.gametypeId) - WHERE pl.id in - AND pl.siteId in - AND h.handStart > '' - AND h.handStart < '' - - AND hp.tourneysPlayersId IS NULL - GROUP BY h.handStart, hp.handId, hp.totalProfit - ORDER BY h.handStart""" + INNER JOIN Hands h on (h.id = hp.handId) + INNER JOIN Gametypes gt on (gt.Id = h.gameTypeId) + INNER JOIN Sites s on (s.Id = gt.siteId) + INNER JOIN Players p on (p.Id = hp.playerId) + WHERE hp.playerId in + AND date_format(h.handStart, '%Y-%m-%d') + ORDER by time""" + elif db_server == 'postgresql': + self.query['sessionStats'] = """ + SELECT EXTRACT(epoch from h.handStart) as time, hp.handId, hp.startCash, hp.winnings, hp.totalProfit + FROM HandsPlayers hp + INNER JOIN Hands h on (h.id = hp.handId) + INNER JOIN Gametypes gt on (gt.Id = h.gameTypeId) + INNER JOIN Sites s on (s.Id = gt.siteId) + INNER JOIN Players p on (p.Id = hp.playerId) + WHERE hp.playerId in + AND h.handStart + ORDER by time""" + elif db_server == 'sqlite': + self.query['sessionStats'] = """ """ - #################################### - # Session stats query - #################################### - if db_server == 'mysql': - self.query['sessionStats'] = """ - SELECT UNIX_TIMESTAMP(h.handStart) as time, hp.handId, hp.startCash, hp.winnings, hp.totalProfit - FROM HandsPlayers hp - INNER JOIN Hands h on (h.id = hp.handId) - INNER JOIN Gametypes gt on (gt.Id = h.gameTypeId) - INNER JOIN Sites s on (s.Id = gt.siteId) - INNER JOIN Players p on (p.Id = hp.playerId) - WHERE hp.playerId in - AND date_format(h.handStart, '%Y-%m-%d') - ORDER by time""" - elif db_server == 'postgresql': - self.query['sessionStats'] = """ - SELECT EXTRACT(epoch from h.handStart) as time, hp.handId, hp.startCash, hp.winnings, hp.totalProfit - FROM HandsPlayers hp - INNER JOIN Hands h on (h.id = hp.handId) - INNER JOIN Gametypes gt on (gt.Id = h.gameTypeId) - INNER JOIN Sites s on (s.Id = gt.siteId) - INNER JOIN Players p on (p.Id = hp.playerId) - WHERE hp.playerId in - AND h.handStart - ORDER by time""" - elif db_server == 'sqlite': - self.query['sessionStats'] = """ """ - - #################################### - # Queries to rebuild/modify hudcache - #################################### - - self.query['clearHudCache'] = """DELETE FROM HudCache""" - - if db_server == 'mysql': - self.query['rebuildHudCache'] = """ - INSERT INTO HudCache - (gametypeId - ,playerId - ,activeSeats - ,position - ,tourneyTypeId - ,styleKey - ,HDs - ,wonWhenSeenStreet1 - ,wonAtSD - ,street0VPI - ,street0Aggr - ,street0_3BChance - ,street0_3BDone - ,street1Seen - ,street2Seen - ,street3Seen - ,street4Seen - ,sawShowdown - ,street1Aggr - ,street2Aggr - ,street3Aggr - ,street4Aggr - ,otherRaisedStreet1 - ,otherRaisedStreet2 - ,otherRaisedStreet3 - ,otherRaisedStreet4 - ,foldToOtherRaisedStreet1 - ,foldToOtherRaisedStreet2 - ,foldToOtherRaisedStreet3 - ,foldToOtherRaisedStreet4 - ,stealAttemptChance - ,stealAttempted - ,foldBbToStealChance - ,foldedBbToSteal - ,foldSbToStealChance - ,foldedSbToSteal - ,street1CBChance - ,street1CBDone - ,street2CBChance - ,street2CBDone - ,street3CBChance - ,street3CBDone - ,street4CBChance - ,street4CBDone - ,foldToStreet1CBChance - ,foldToStreet1CBDone - ,foldToStreet2CBChance - ,foldToStreet2CBDone - ,foldToStreet3CBChance - ,foldToStreet3CBDone - ,foldToStreet4CBChance - ,foldToStreet4CBDone - ,totalProfit - ,street1CheckCallRaiseChance - ,street1CheckCallRaiseDone - ,street2CheckCallRaiseChance - ,street2CheckCallRaiseDone - ,street3CheckCallRaiseChance - ,street3CheckCallRaiseDone - ,street4CheckCallRaiseChance - ,street4CheckCallRaiseDone - ) - SELECT h.gametypeId - ,hp.playerId - ,h.seats - ,case when hp.position = 'B' then 'B' - when hp.position = 'S' then 'S' - when hp.position = '0' then 'D' - when hp.position = '1' then 'C' - when hp.position = '2' then 'M' - when hp.position = '3' then 'M' - when hp.position = '4' then 'M' - when hp.position = '5' then 'E' - when hp.position = '6' then 'E' - when hp.position = '7' then 'E' - when hp.position = '8' then 'E' - when hp.position = '9' then 'E' - else 'E' - end AS hc_position - ,hp.tourneyTypeId - ,date_format(h.handStart, 'd%y%m%d') - ,count(1) - ,sum(wonWhenSeenStreet1) - ,sum(wonAtSD) - ,sum(street0VPI) - ,sum(street0Aggr) - ,sum(street0_3BChance) - ,sum(street0_3BDone) - ,sum(street1Seen) - ,sum(street2Seen) - ,sum(street3Seen) - ,sum(street4Seen) - ,sum(sawShowdown) - ,sum(street1Aggr) - ,sum(street2Aggr) - ,sum(street3Aggr) - ,sum(street4Aggr) - ,sum(otherRaisedStreet1) - ,sum(otherRaisedStreet2) - ,sum(otherRaisedStreet3) - ,sum(otherRaisedStreet4) - ,sum(foldToOtherRaisedStreet1) - ,sum(foldToOtherRaisedStreet2) - ,sum(foldToOtherRaisedStreet3) - ,sum(foldToOtherRaisedStreet4) - ,sum(stealAttemptChance) - ,sum(stealAttempted) - ,sum(foldBbToStealChance) - ,sum(foldedBbToSteal) - ,sum(foldSbToStealChance) - ,sum(foldedSbToSteal) - ,sum(street1CBChance) - ,sum(street1CBDone) - ,sum(street2CBChance) - ,sum(street2CBDone) - ,sum(street3CBChance) - ,sum(street3CBDone) - ,sum(street4CBChance) - ,sum(street4CBDone) - ,sum(foldToStreet1CBChance) - ,sum(foldToStreet1CBDone) - ,sum(foldToStreet2CBChance) - ,sum(foldToStreet2CBDone) - ,sum(foldToStreet3CBChance) - ,sum(foldToStreet3CBDone) - ,sum(foldToStreet4CBChance) - ,sum(foldToStreet4CBDone) - ,sum(totalProfit) - ,sum(street1CheckCallRaiseChance) - ,sum(street1CheckCallRaiseDone) - ,sum(street2CheckCallRaiseChance) - ,sum(street2CheckCallRaiseDone) - ,sum(street3CheckCallRaiseChance) - ,sum(street3CheckCallRaiseDone) - ,sum(street4CheckCallRaiseChance) - ,sum(street4CheckCallRaiseDone) - FROM HandsPlayers hp - INNER JOIN Hands h ON (h.id = hp.handId) - - GROUP BY h.gametypeId - ,hp.playerId - ,h.seats - ,hc_position - ,hp.tourneyTypeId - ,date_format(h.handStart, 'd%y%m%d') + #################################### + # Queries to rebuild/modify hudcache + #################################### + + self.query['clearHudCache'] = """DELETE FROM HudCache""" + + if db_server == 'mysql': + self.query['rebuildHudCache'] = """ + INSERT INTO HudCache + (gametypeId + ,playerId + ,activeSeats + ,position + ,tourneyTypeId + ,styleKey + ,HDs + ,wonWhenSeenStreet1 + ,wonAtSD + ,street0VPI + ,street0Aggr + ,street0_3BChance + ,street0_3BDone + ,street1Seen + ,street2Seen + ,street3Seen + ,street4Seen + ,sawShowdown + ,street1Aggr + ,street2Aggr + ,street3Aggr + ,street4Aggr + ,otherRaisedStreet1 + ,otherRaisedStreet2 + ,otherRaisedStreet3 + ,otherRaisedStreet4 + ,foldToOtherRaisedStreet1 + ,foldToOtherRaisedStreet2 + ,foldToOtherRaisedStreet3 + ,foldToOtherRaisedStreet4 + ,stealAttemptChance + ,stealAttempted + ,foldBbToStealChance + ,foldedBbToSteal + ,foldSbToStealChance + ,foldedSbToSteal + ,street1CBChance + ,street1CBDone + ,street2CBChance + ,street2CBDone + ,street3CBChance + ,street3CBDone + ,street4CBChance + ,street4CBDone + ,foldToStreet1CBChance + ,foldToStreet1CBDone + ,foldToStreet2CBChance + ,foldToStreet2CBDone + ,foldToStreet3CBChance + ,foldToStreet3CBDone + ,foldToStreet4CBChance + ,foldToStreet4CBDone + ,totalProfit + ,street1CheckCallRaiseChance + ,street1CheckCallRaiseDone + ,street2CheckCallRaiseChance + ,street2CheckCallRaiseDone + ,street3CheckCallRaiseChance + ,street3CheckCallRaiseDone + ,street4CheckCallRaiseChance + ,street4CheckCallRaiseDone + ) + SELECT h.gametypeId + ,hp.playerId + ,h.seats + ,case when hp.position = 'B' then 'B' + when hp.position = 'S' then 'S' + when hp.position = '0' then 'D' + when hp.position = '1' then 'C' + when hp.position = '2' then 'M' + when hp.position = '3' then 'M' + when hp.position = '4' then 'M' + when hp.position = '5' then 'E' + when hp.position = '6' then 'E' + when hp.position = '7' then 'E' + when hp.position = '8' then 'E' + when hp.position = '9' then 'E' + else 'E' + end AS hc_position + ,hp.tourneyTypeId + ,date_format(h.handStart, 'd%y%m%d') + ,count(1) + ,sum(wonWhenSeenStreet1) + ,sum(wonAtSD) + ,sum(street0VPI) + ,sum(street0Aggr) + ,sum(street0_3BChance) + ,sum(street0_3BDone) + ,sum(street1Seen) + ,sum(street2Seen) + ,sum(street3Seen) + ,sum(street4Seen) + ,sum(sawShowdown) + ,sum(street1Aggr) + ,sum(street2Aggr) + ,sum(street3Aggr) + ,sum(street4Aggr) + ,sum(otherRaisedStreet1) + ,sum(otherRaisedStreet2) + ,sum(otherRaisedStreet3) + ,sum(otherRaisedStreet4) + ,sum(foldToOtherRaisedStreet1) + ,sum(foldToOtherRaisedStreet2) + ,sum(foldToOtherRaisedStreet3) + ,sum(foldToOtherRaisedStreet4) + ,sum(stealAttemptChance) + ,sum(stealAttempted) + ,sum(foldBbToStealChance) + ,sum(foldedBbToSteal) + ,sum(foldSbToStealChance) + ,sum(foldedSbToSteal) + ,sum(street1CBChance) + ,sum(street1CBDone) + ,sum(street2CBChance) + ,sum(street2CBDone) + ,sum(street3CBChance) + ,sum(street3CBDone) + ,sum(street4CBChance) + ,sum(street4CBDone) + ,sum(foldToStreet1CBChance) + ,sum(foldToStreet1CBDone) + ,sum(foldToStreet2CBChance) + ,sum(foldToStreet2CBDone) + ,sum(foldToStreet3CBChance) + ,sum(foldToStreet3CBDone) + ,sum(foldToStreet4CBChance) + ,sum(foldToStreet4CBDone) + ,sum(totalProfit) + ,sum(street1CheckCallRaiseChance) + ,sum(street1CheckCallRaiseDone) + ,sum(street2CheckCallRaiseChance) + ,sum(street2CheckCallRaiseDone) + ,sum(street3CheckCallRaiseChance) + ,sum(street3CheckCallRaiseDone) + ,sum(street4CheckCallRaiseChance) + ,sum(street4CheckCallRaiseDone) + FROM HandsPlayers hp + INNER JOIN Hands h ON (h.id = hp.handId) + + GROUP BY h.gametypeId + ,hp.playerId + ,h.seats + ,hc_position + ,hp.tourneyTypeId + ,date_format(h.handStart, 'd%y%m%d') """ - elif db_server == 'postgresql': - self.query['rebuildHudCache'] = """ - INSERT INTO HudCache - (gametypeId - ,playerId - ,activeSeats - ,position - ,tourneyTypeId - ,styleKey - ,HDs - ,wonWhenSeenStreet1 - ,wonAtSD - ,street0VPI - ,street0Aggr - ,street0_3BChance - ,street0_3BDone - ,street1Seen - ,street2Seen - ,street3Seen - ,street4Seen - ,sawShowdown - ,street1Aggr - ,street2Aggr - ,street3Aggr - ,street4Aggr - ,otherRaisedStreet1 - ,otherRaisedStreet2 - ,otherRaisedStreet3 - ,otherRaisedStreet4 - ,foldToOtherRaisedStreet1 - ,foldToOtherRaisedStreet2 - ,foldToOtherRaisedStreet3 - ,foldToOtherRaisedStreet4 - ,stealAttemptChance - ,stealAttempted - ,foldBbToStealChance - ,foldedBbToSteal - ,foldSbToStealChance - ,foldedSbToSteal - ,street1CBChance - ,street1CBDone - ,street2CBChance - ,street2CBDone - ,street3CBChance - ,street3CBDone - ,street4CBChance - ,street4CBDone - ,foldToStreet1CBChance - ,foldToStreet1CBDone - ,foldToStreet2CBChance - ,foldToStreet2CBDone - ,foldToStreet3CBChance - ,foldToStreet3CBDone - ,foldToStreet4CBChance - ,foldToStreet4CBDone - ,totalProfit - ,street1CheckCallRaiseChance - ,street1CheckCallRaiseDone - ,street2CheckCallRaiseChance - ,street2CheckCallRaiseDone - ,street3CheckCallRaiseChance - ,street3CheckCallRaiseDone - ,street4CheckCallRaiseChance - ,street4CheckCallRaiseDone - ) - SELECT h.gametypeId - ,hp.playerId - ,h.seats - ,case when hp.position = 'B' then 'B' - when hp.position = 'S' then 'S' - when hp.position = '0' then 'D' - when hp.position = '1' then 'C' - when hp.position = '2' then 'M' - when hp.position = '3' then 'M' - when hp.position = '4' then 'M' - when hp.position = '5' then 'E' - when hp.position = '6' then 'E' - when hp.position = '7' then 'E' - when hp.position = '8' then 'E' - when hp.position = '9' then 'E' - else 'E' - end AS hc_position - ,hp.tourneyTypeId - ,'d' || to_char(h.handStart, 'YYMMDD') - ,count(1) - ,sum(wonWhenSeenStreet1) - ,sum(wonAtSD) - ,sum(CAST(street0VPI as integer)) - ,sum(CAST(street0Aggr as integer)) - ,sum(CAST(street0_3BChance as integer)) - ,sum(CAST(street0_3BDone as integer)) - ,sum(CAST(street1Seen as integer)) - ,sum(CAST(street2Seen as integer)) - ,sum(CAST(street3Seen as integer)) - ,sum(CAST(street4Seen as integer)) - ,sum(CAST(sawShowdown as integer)) - ,sum(CAST(street1Aggr as integer)) - ,sum(CAST(street2Aggr as integer)) - ,sum(CAST(street3Aggr as integer)) - ,sum(CAST(street4Aggr as integer)) - ,sum(CAST(otherRaisedStreet1 as integer)) - ,sum(CAST(otherRaisedStreet2 as integer)) - ,sum(CAST(otherRaisedStreet3 as integer)) - ,sum(CAST(otherRaisedStreet4 as integer)) - ,sum(CAST(foldToOtherRaisedStreet1 as integer)) - ,sum(CAST(foldToOtherRaisedStreet2 as integer)) - ,sum(CAST(foldToOtherRaisedStreet3 as integer)) - ,sum(CAST(foldToOtherRaisedStreet4 as integer)) - ,sum(CAST(stealAttemptChance as integer)) - ,sum(CAST(stealAttempted as integer)) - ,sum(CAST(foldBbToStealChance as integer)) - ,sum(CAST(foldedBbToSteal as integer)) - ,sum(CAST(foldSbToStealChance as integer)) - ,sum(CAST(foldedSbToSteal as integer)) - ,sum(CAST(street1CBChance as integer)) - ,sum(CAST(street1CBDone as integer)) - ,sum(CAST(street2CBChance as integer)) - ,sum(CAST(street2CBDone as integer)) - ,sum(CAST(street3CBChance as integer)) - ,sum(CAST(street3CBDone as integer)) - ,sum(CAST(street4CBChance as integer)) - ,sum(CAST(street4CBDone as integer)) - ,sum(CAST(foldToStreet1CBChance as integer)) - ,sum(CAST(foldToStreet1CBDone as integer)) - ,sum(CAST(foldToStreet2CBChance as integer)) - ,sum(CAST(foldToStreet2CBDone as integer)) - ,sum(CAST(foldToStreet3CBChance as integer)) - ,sum(CAST(foldToStreet3CBDone as integer)) - ,sum(CAST(foldToStreet4CBChance as integer)) - ,sum(CAST(foldToStreet4CBDone as integer)) - ,sum(CAST(totalProfit as integer)) - ,sum(CAST(street1CheckCallRaiseChance as integer)) - ,sum(CAST(street1CheckCallRaiseDone as integer)) - ,sum(CAST(street2CheckCallRaiseChance as integer)) - ,sum(CAST(street2CheckCallRaiseDone as integer)) - ,sum(CAST(street3CheckCallRaiseChance as integer)) - ,sum(CAST(street3CheckCallRaiseDone as integer)) - ,sum(CAST(street4CheckCallRaiseChance as integer)) - ,sum(CAST(street4CheckCallRaiseDone as integer)) - FROM HandsPlayers hp - INNER JOIN Hands h ON (h.id = hp.handId) - - GROUP BY h.gametypeId - ,hp.playerId - ,h.seats - ,hc_position - ,hp.tourneyTypeId - ,to_char(h.handStart, 'YYMMDD') + elif db_server == 'postgresql': + self.query['rebuildHudCache'] = """ + INSERT INTO HudCache + (gametypeId + ,playerId + ,activeSeats + ,position + ,tourneyTypeId + ,styleKey + ,HDs + ,wonWhenSeenStreet1 + ,wonAtSD + ,street0VPI + ,street0Aggr + ,street0_3BChance + ,street0_3BDone + ,street1Seen + ,street2Seen + ,street3Seen + ,street4Seen + ,sawShowdown + ,street1Aggr + ,street2Aggr + ,street3Aggr + ,street4Aggr + ,otherRaisedStreet1 + ,otherRaisedStreet2 + ,otherRaisedStreet3 + ,otherRaisedStreet4 + ,foldToOtherRaisedStreet1 + ,foldToOtherRaisedStreet2 + ,foldToOtherRaisedStreet3 + ,foldToOtherRaisedStreet4 + ,stealAttemptChance + ,stealAttempted + ,foldBbToStealChance + ,foldedBbToSteal + ,foldSbToStealChance + ,foldedSbToSteal + ,street1CBChance + ,street1CBDone + ,street2CBChance + ,street2CBDone + ,street3CBChance + ,street3CBDone + ,street4CBChance + ,street4CBDone + ,foldToStreet1CBChance + ,foldToStreet1CBDone + ,foldToStreet2CBChance + ,foldToStreet2CBDone + ,foldToStreet3CBChance + ,foldToStreet3CBDone + ,foldToStreet4CBChance + ,foldToStreet4CBDone + ,totalProfit + ,street1CheckCallRaiseChance + ,street1CheckCallRaiseDone + ,street2CheckCallRaiseChance + ,street2CheckCallRaiseDone + ,street3CheckCallRaiseChance + ,street3CheckCallRaiseDone + ,street4CheckCallRaiseChance + ,street4CheckCallRaiseDone + ) + SELECT h.gametypeId + ,hp.playerId + ,h.seats + ,case when hp.position = 'B' then 'B' + when hp.position = 'S' then 'S' + when hp.position = '0' then 'D' + when hp.position = '1' then 'C' + when hp.position = '2' then 'M' + when hp.position = '3' then 'M' + when hp.position = '4' then 'M' + when hp.position = '5' then 'E' + when hp.position = '6' then 'E' + when hp.position = '7' then 'E' + when hp.position = '8' then 'E' + when hp.position = '9' then 'E' + else 'E' + end AS hc_position + ,hp.tourneyTypeId + ,'d' || to_char(h.handStart, 'YYMMDD') + ,count(1) + ,sum(wonWhenSeenStreet1) + ,sum(wonAtSD) + ,sum(CAST(street0VPI as integer)) + ,sum(CAST(street0Aggr as integer)) + ,sum(CAST(street0_3BChance as integer)) + ,sum(CAST(street0_3BDone as integer)) + ,sum(CAST(street1Seen as integer)) + ,sum(CAST(street2Seen as integer)) + ,sum(CAST(street3Seen as integer)) + ,sum(CAST(street4Seen as integer)) + ,sum(CAST(sawShowdown as integer)) + ,sum(CAST(street1Aggr as integer)) + ,sum(CAST(street2Aggr as integer)) + ,sum(CAST(street3Aggr as integer)) + ,sum(CAST(street4Aggr as integer)) + ,sum(CAST(otherRaisedStreet1 as integer)) + ,sum(CAST(otherRaisedStreet2 as integer)) + ,sum(CAST(otherRaisedStreet3 as integer)) + ,sum(CAST(otherRaisedStreet4 as integer)) + ,sum(CAST(foldToOtherRaisedStreet1 as integer)) + ,sum(CAST(foldToOtherRaisedStreet2 as integer)) + ,sum(CAST(foldToOtherRaisedStreet3 as integer)) + ,sum(CAST(foldToOtherRaisedStreet4 as integer)) + ,sum(CAST(stealAttemptChance as integer)) + ,sum(CAST(stealAttempted as integer)) + ,sum(CAST(foldBbToStealChance as integer)) + ,sum(CAST(foldedBbToSteal as integer)) + ,sum(CAST(foldSbToStealChance as integer)) + ,sum(CAST(foldedSbToSteal as integer)) + ,sum(CAST(street1CBChance as integer)) + ,sum(CAST(street1CBDone as integer)) + ,sum(CAST(street2CBChance as integer)) + ,sum(CAST(street2CBDone as integer)) + ,sum(CAST(street3CBChance as integer)) + ,sum(CAST(street3CBDone as integer)) + ,sum(CAST(street4CBChance as integer)) + ,sum(CAST(street4CBDone as integer)) + ,sum(CAST(foldToStreet1CBChance as integer)) + ,sum(CAST(foldToStreet1CBDone as integer)) + ,sum(CAST(foldToStreet2CBChance as integer)) + ,sum(CAST(foldToStreet2CBDone as integer)) + ,sum(CAST(foldToStreet3CBChance as integer)) + ,sum(CAST(foldToStreet3CBDone as integer)) + ,sum(CAST(foldToStreet4CBChance as integer)) + ,sum(CAST(foldToStreet4CBDone as integer)) + ,sum(CAST(totalProfit as integer)) + ,sum(CAST(street1CheckCallRaiseChance as integer)) + ,sum(CAST(street1CheckCallRaiseDone as integer)) + ,sum(CAST(street2CheckCallRaiseChance as integer)) + ,sum(CAST(street2CheckCallRaiseDone as integer)) + ,sum(CAST(street3CheckCallRaiseChance as integer)) + ,sum(CAST(street3CheckCallRaiseDone as integer)) + ,sum(CAST(street4CheckCallRaiseChance as integer)) + ,sum(CAST(street4CheckCallRaiseDone as integer)) + FROM HandsPlayers hp + INNER JOIN Hands h ON (h.id = hp.handId) + + GROUP BY h.gametypeId + ,hp.playerId + ,h.seats + ,hc_position + ,hp.tourneyTypeId + ,to_char(h.handStart, 'YYMMDD') """ - else: # assume sqlite - self.query['rebuildHudCache'] = """ - INSERT INTO HudCache - (gametypeId - ,playerId - ,activeSeats - ,position - ,tourneyTypeId - ,styleKey - ,HDs - ,wonWhenSeenStreet1 - ,wonAtSD - ,street0VPI - ,street0Aggr - ,street0_3BChance - ,street0_3BDone - ,street1Seen - ,street2Seen - ,street3Seen - ,street4Seen - ,sawShowdown - ,street1Aggr - ,street2Aggr - ,street3Aggr - ,street4Aggr - ,otherRaisedStreet1 - ,otherRaisedStreet2 - ,otherRaisedStreet3 - ,otherRaisedStreet4 - ,foldToOtherRaisedStreet1 - ,foldToOtherRaisedStreet2 - ,foldToOtherRaisedStreet3 - ,foldToOtherRaisedStreet4 - ,stealAttemptChance - ,stealAttempted - ,foldBbToStealChance - ,foldedBbToSteal - ,foldSbToStealChance - ,foldedSbToSteal - ,street1CBChance - ,street1CBDone - ,street2CBChance - ,street2CBDone - ,street3CBChance - ,street3CBDone - ,street4CBChance - ,street4CBDone - ,foldToStreet1CBChance - ,foldToStreet1CBDone - ,foldToStreet2CBChance - ,foldToStreet2CBDone - ,foldToStreet3CBChance - ,foldToStreet3CBDone - ,foldToStreet4CBChance - ,foldToStreet4CBDone - ,totalProfit - ,street1CheckCallRaiseChance - ,street1CheckCallRaiseDone - ,street2CheckCallRaiseChance - ,street2CheckCallRaiseDone - ,street3CheckCallRaiseChance - ,street3CheckCallRaiseDone - ,street4CheckCallRaiseChance - ,street4CheckCallRaiseDone - ) - SELECT h.gametypeId - ,hp.playerId - ,h.seats - ,case when hp.position = 'B' then 'B' - when hp.position = 'S' then 'S' - when hp.position = '0' then 'D' - when hp.position = '1' then 'C' - when hp.position = '2' then 'M' - when hp.position = '3' then 'M' - when hp.position = '4' then 'M' - when hp.position = '5' then 'E' - when hp.position = '6' then 'E' - when hp.position = '7' then 'E' - when hp.position = '8' then 'E' - when hp.position = '9' then 'E' - else 'E' - end AS hc_position - ,hp.tourneyTypeId - ,'d' || substr(strftime('%Y%m%d', h.handStart),3,7) - ,count(1) - ,sum(wonWhenSeenStreet1) - ,sum(wonAtSD) - ,sum(CAST(street0VPI as integer)) - ,sum(CAST(street0Aggr as integer)) - ,sum(CAST(street0_3BChance as integer)) - ,sum(CAST(street0_3BDone as integer)) - ,sum(CAST(street1Seen as integer)) - ,sum(CAST(street2Seen as integer)) - ,sum(CAST(street3Seen as integer)) - ,sum(CAST(street4Seen as integer)) - ,sum(CAST(sawShowdown as integer)) - ,sum(CAST(street1Aggr as integer)) - ,sum(CAST(street2Aggr as integer)) - ,sum(CAST(street3Aggr as integer)) - ,sum(CAST(street4Aggr as integer)) - ,sum(CAST(otherRaisedStreet1 as integer)) - ,sum(CAST(otherRaisedStreet2 as integer)) - ,sum(CAST(otherRaisedStreet3 as integer)) - ,sum(CAST(otherRaisedStreet4 as integer)) - ,sum(CAST(foldToOtherRaisedStreet1 as integer)) - ,sum(CAST(foldToOtherRaisedStreet2 as integer)) - ,sum(CAST(foldToOtherRaisedStreet3 as integer)) - ,sum(CAST(foldToOtherRaisedStreet4 as integer)) - ,sum(CAST(stealAttemptChance as integer)) - ,sum(CAST(stealAttempted as integer)) - ,sum(CAST(foldBbToStealChance as integer)) - ,sum(CAST(foldedBbToSteal as integer)) - ,sum(CAST(foldSbToStealChance as integer)) - ,sum(CAST(foldedSbToSteal as integer)) - ,sum(CAST(street1CBChance as integer)) - ,sum(CAST(street1CBDone as integer)) - ,sum(CAST(street2CBChance as integer)) - ,sum(CAST(street2CBDone as integer)) - ,sum(CAST(street3CBChance as integer)) - ,sum(CAST(street3CBDone as integer)) - ,sum(CAST(street4CBChance as integer)) - ,sum(CAST(street4CBDone as integer)) - ,sum(CAST(foldToStreet1CBChance as integer)) - ,sum(CAST(foldToStreet1CBDone as integer)) - ,sum(CAST(foldToStreet2CBChance as integer)) - ,sum(CAST(foldToStreet2CBDone as integer)) - ,sum(CAST(foldToStreet3CBChance as integer)) - ,sum(CAST(foldToStreet3CBDone as integer)) - ,sum(CAST(foldToStreet4CBChance as integer)) - ,sum(CAST(foldToStreet4CBDone as integer)) - ,sum(CAST(totalProfit as integer)) - ,sum(CAST(street1CheckCallRaiseChance as integer)) - ,sum(CAST(street1CheckCallRaiseDone as integer)) - ,sum(CAST(street2CheckCallRaiseChance as integer)) - ,sum(CAST(street2CheckCallRaiseDone as integer)) - ,sum(CAST(street3CheckCallRaiseChance as integer)) - ,sum(CAST(street3CheckCallRaiseDone as integer)) - ,sum(CAST(street4CheckCallRaiseChance as integer)) - ,sum(CAST(street4CheckCallRaiseDone as integer)) - FROM HandsPlayers hp - INNER JOIN Hands h ON (h.id = hp.handId) - - GROUP BY h.gametypeId - ,hp.playerId - ,h.seats - ,hc_position - ,hp.tourneyTypeId - ,'d' || substr(strftime('%Y%m%d', h.handStart),3,7) + else: # assume sqlite + self.query['rebuildHudCache'] = """ + INSERT INTO HudCache + (gametypeId + ,playerId + ,activeSeats + ,position + ,tourneyTypeId + ,styleKey + ,HDs + ,wonWhenSeenStreet1 + ,wonAtSD + ,street0VPI + ,street0Aggr + ,street0_3BChance + ,street0_3BDone + ,street1Seen + ,street2Seen + ,street3Seen + ,street4Seen + ,sawShowdown + ,street1Aggr + ,street2Aggr + ,street3Aggr + ,street4Aggr + ,otherRaisedStreet1 + ,otherRaisedStreet2 + ,otherRaisedStreet3 + ,otherRaisedStreet4 + ,foldToOtherRaisedStreet1 + ,foldToOtherRaisedStreet2 + ,foldToOtherRaisedStreet3 + ,foldToOtherRaisedStreet4 + ,stealAttemptChance + ,stealAttempted + ,foldBbToStealChance + ,foldedBbToSteal + ,foldSbToStealChance + ,foldedSbToSteal + ,street1CBChance + ,street1CBDone + ,street2CBChance + ,street2CBDone + ,street3CBChance + ,street3CBDone + ,street4CBChance + ,street4CBDone + ,foldToStreet1CBChance + ,foldToStreet1CBDone + ,foldToStreet2CBChance + ,foldToStreet2CBDone + ,foldToStreet3CBChance + ,foldToStreet3CBDone + ,foldToStreet4CBChance + ,foldToStreet4CBDone + ,totalProfit + ,street1CheckCallRaiseChance + ,street1CheckCallRaiseDone + ,street2CheckCallRaiseChance + ,street2CheckCallRaiseDone + ,street3CheckCallRaiseChance + ,street3CheckCallRaiseDone + ,street4CheckCallRaiseChance + ,street4CheckCallRaiseDone + ) + SELECT h.gametypeId + ,hp.playerId + ,h.seats + ,case when hp.position = 'B' then 'B' + when hp.position = 'S' then 'S' + when hp.position = '0' then 'D' + when hp.position = '1' then 'C' + when hp.position = '2' then 'M' + when hp.position = '3' then 'M' + when hp.position = '4' then 'M' + when hp.position = '5' then 'E' + when hp.position = '6' then 'E' + when hp.position = '7' then 'E' + when hp.position = '8' then 'E' + when hp.position = '9' then 'E' + else 'E' + end AS hc_position + ,hp.tourneyTypeId + ,'d' || substr(strftime('%Y%m%d', h.handStart),3,7) + ,count(1) + ,sum(wonWhenSeenStreet1) + ,sum(wonAtSD) + ,sum(CAST(street0VPI as integer)) + ,sum(CAST(street0Aggr as integer)) + ,sum(CAST(street0_3BChance as integer)) + ,sum(CAST(street0_3BDone as integer)) + ,sum(CAST(street1Seen as integer)) + ,sum(CAST(street2Seen as integer)) + ,sum(CAST(street3Seen as integer)) + ,sum(CAST(street4Seen as integer)) + ,sum(CAST(sawShowdown as integer)) + ,sum(CAST(street1Aggr as integer)) + ,sum(CAST(street2Aggr as integer)) + ,sum(CAST(street3Aggr as integer)) + ,sum(CAST(street4Aggr as integer)) + ,sum(CAST(otherRaisedStreet1 as integer)) + ,sum(CAST(otherRaisedStreet2 as integer)) + ,sum(CAST(otherRaisedStreet3 as integer)) + ,sum(CAST(otherRaisedStreet4 as integer)) + ,sum(CAST(foldToOtherRaisedStreet1 as integer)) + ,sum(CAST(foldToOtherRaisedStreet2 as integer)) + ,sum(CAST(foldToOtherRaisedStreet3 as integer)) + ,sum(CAST(foldToOtherRaisedStreet4 as integer)) + ,sum(CAST(stealAttemptChance as integer)) + ,sum(CAST(stealAttempted as integer)) + ,sum(CAST(foldBbToStealChance as integer)) + ,sum(CAST(foldedBbToSteal as integer)) + ,sum(CAST(foldSbToStealChance as integer)) + ,sum(CAST(foldedSbToSteal as integer)) + ,sum(CAST(street1CBChance as integer)) + ,sum(CAST(street1CBDone as integer)) + ,sum(CAST(street2CBChance as integer)) + ,sum(CAST(street2CBDone as integer)) + ,sum(CAST(street3CBChance as integer)) + ,sum(CAST(street3CBDone as integer)) + ,sum(CAST(street4CBChance as integer)) + ,sum(CAST(street4CBDone as integer)) + ,sum(CAST(foldToStreet1CBChance as integer)) + ,sum(CAST(foldToStreet1CBDone as integer)) + ,sum(CAST(foldToStreet2CBChance as integer)) + ,sum(CAST(foldToStreet2CBDone as integer)) + ,sum(CAST(foldToStreet3CBChance as integer)) + ,sum(CAST(foldToStreet3CBDone as integer)) + ,sum(CAST(foldToStreet4CBChance as integer)) + ,sum(CAST(foldToStreet4CBDone as integer)) + ,sum(CAST(totalProfit as integer)) + ,sum(CAST(street1CheckCallRaiseChance as integer)) + ,sum(CAST(street1CheckCallRaiseDone as integer)) + ,sum(CAST(street2CheckCallRaiseChance as integer)) + ,sum(CAST(street2CheckCallRaiseDone as integer)) + ,sum(CAST(street3CheckCallRaiseChance as integer)) + ,sum(CAST(street3CheckCallRaiseDone as integer)) + ,sum(CAST(street4CheckCallRaiseChance as integer)) + ,sum(CAST(street4CheckCallRaiseDone as integer)) + FROM HandsPlayers hp + INNER JOIN Hands h ON (h.id = hp.handId) + + GROUP BY h.gametypeId + ,hp.playerId + ,h.seats + ,hc_position + ,hp.tourneyTypeId + ,'d' || substr(strftime('%Y%m%d', h.handStart),3,7) """ - self.query['get_hero_hudcache_start'] = """select min(hc.styleKey) - from HudCache hc - where hc.playerId in - and hc.styleKey like 'd%'""" + self.query['get_hero_hudcache_start'] = """select min(hc.styleKey) + from HudCache hc + where hc.playerId in + and hc.styleKey like 'd%'""" - if db_server == 'mysql': - self.query['analyze'] = """ - analyze table Autorates, GameTypes, Hands, HandsPlayers, HudCache, Players - , Settings, Sites, Tourneys, TourneysPlayers, TourneyTypes + if db_server == 'mysql': + self.query['analyze'] = """ + analyze table Autorates, GameTypes, Hands, HandsPlayers, HudCache, Players + , Settings, Sites, Tourneys, TourneysPlayers, TourneyTypes + """ + else: # assume postgres + self.query['analyze'] = "vacuum analyze" + + if db_server == 'mysql': + self.query['lockForInsert'] = """ + lock tables Hands write, HandsPlayers write, HandsActions write, Players write + , HudCache write, GameTypes write, Sites write, Tourneys write + , TourneysPlayers write, TourneyTypes write, Autorates write """ - else: # assume postgres - self.query['analyze'] = "vacuum analyze" + else: # assume postgres + self.query['lockForInsert'] = "" - if db_server == 'mysql': - self.query['lockForInsert'] = """ - lock tables Hands write, HandsPlayers write, HandsActions write, Players write - , HudCache write, GameTypes write, Sites write, Tourneys write - , TourneysPlayers write, TourneyTypes write, Autorates write - """ - else: # assume postgres - self.query['lockForInsert'] = "" + self.query['getGametypeFL'] = """SELECT id + FROM Gametypes + WHERE siteId=%s + AND type=%s + AND category=%s + AND limitType=%s + AND smallBet=%s + AND bigBet=%s + """ - self.query['getGametypeFL'] = """SELECT id - FROM Gametypes - WHERE siteId=%s - AND type=%s - AND category=%s - AND limitType=%s - AND smallBet=%s - AND bigBet=%s - """ + self.query['getGametypeNL'] = """SELECT id + FROM Gametypes + WHERE siteId=%s + AND type=%s + AND category=%s + AND limitType=%s + AND smallBlind=%s + AND bigBlind=%s + """ - self.query['getGametypeNL'] = """SELECT id - FROM Gametypes - WHERE siteId=%s - AND type=%s - AND category=%s - AND limitType=%s - AND smallBlind=%s - AND bigBlind=%s - """ + self.query['insertGameTypes'] = """INSERT INTO Gametypes + (siteId, type, base, category, limitType + ,hiLo, smallBlind, bigBlind, smallBet, bigBet) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""" - self.query['insertGameTypes'] = """INSERT INTO Gametypes - (siteId, type, base, category, limitType - ,hiLo, smallBlind, bigBlind, smallBet, bigBet) - VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""" + self.query['isAlreadyInDB'] = """SELECT id FROM Hands + WHERE gametypeId=%s AND siteHandNo=%s + """ + + self.query['getTourneyTypeIdByTourneyNo'] = """SELECT tt.id, + tt.buyin, + tt.fee, + tt.maxSeats, + tt.knockout, + tt.rebuyOrAddon, + tt.speed, + tt.headsUp, + tt.shootout, + tt.matrix + FROM TourneyTypes tt + INNER JOIN Tourneys t ON (t.tourneyTypeId = tt.id) + WHERE t.siteTourneyNo=%s AND tt.siteId=%s + """ + + self.query['getTourneyTypeId'] = """SELECT id + FROM TourneyTypes + WHERE siteId=%s + AND buyin=%s + AND fee=%s + AND knockout=%s + AND rebuyOrAddon=%s + AND speed=%s + AND headsUp=%s + AND shootout=%s + AND matrix=%s + """ - self.query['isAlreadyInDB'] = """SELECT id FROM Hands - WHERE gametypeId=%s AND siteHandNo=%s - """ - - self.query['getTourneyTypeIdByTourneyNo'] = """SELECT tt.id, - tt.buyin, - tt.fee, - tt.maxSeats, - tt.knockout, - tt.rebuyOrAddon, - tt.speed, - tt.headsUp, - tt.shootout, - tt.matrix - FROM TourneyTypes tt - INNER JOIN Tourneys t ON (t.tourneyTypeId = tt.id) - WHERE t.siteTourneyNo=%s AND tt.siteId=%s - """ - - self.query['getTourneyTypeId'] = """SELECT id - FROM TourneyTypes - WHERE siteId=%s - AND buyin=%s - AND fee=%s - AND knockout=%s - AND rebuyOrAddon=%s - AND speed=%s - AND headsUp=%s - AND shootout=%s - AND matrix=%s - """ + self.query['insertTourneyTypes'] = """INSERT INTO TourneyTypes + (siteId, buyin, fee, knockout, rebuyOrAddon + ,speed, headsUp, shootout, matrix) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) + """ - self.query['insertTourneyTypes'] = """INSERT INTO TourneyTypes - (siteId, buyin, fee, knockout, rebuyOrAddon - ,speed, headsUp, shootout, matrix) - VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) - """ + self.query['getTourney'] = """SELECT t.id, + t.tourneyTypeId, + t.entries, + t.prizepool, + t.startTime, + t.endTime, + t.buyinChips, + t.tourneyName, + t.matrixIdProcessed, + t.rebuyChips, + t.addonChips, + t.rebuyAmount, + t.addonAmount, + t.totalRebuys, + t.totalAddons, + t.koBounty, + t.comment + FROM Tourneys t + INNER JOIN TourneyTypes tt ON (t.tourneyTypeId = tt.id) + WHERE t.siteTourneyNo=%s AND tt.siteId=%s + """ - self.query['getTourney'] = """SELECT t.id, - t.tourneyTypeId, - t.entries, - t.prizepool, - t.startTime, - t.endTime, - t.buyinChips, - t.tourneyName, - t.matrixIdProcessed, - t.rebuyChips, - t.addonChips, - t.rebuyAmount, - t.addonAmount, - t.totalRebuys, - t.totalAddons, - t.koBounty, - t.comment - FROM Tourneys t - INNER JOIN TourneyTypes tt ON (t.tourneyTypeId = tt.id) - WHERE t.siteTourneyNo=%s AND tt.siteId=%s - """ + self.query['insertTourney'] = """INSERT INTO Tourneys + (tourneyTypeId, siteTourneyNo, entries, prizepool, + startTime, endTime, buyinChips, tourneyName, matrixIdProcessed, + rebuyChips, addonChips, rebuyAmount, addonAmount, totalRebuys, + totalAddons, koBounty, comment, commentTs) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, + %s, %s, %s, %s, %s, %s, %s, %s) + """ + + self.query['updateTourney'] = """UPDATE Tourneys + SET tourneyTypeId = %s, + entries = %s, + prizepool = %s, + startTime = %s, + endTime = %s, + buyinChips = %s, + tourneyName = %s, + matrixIdProcessed = %s, + rebuyChips = %s, + addonChips = %s, + rebuyAmount = %s, + addonAmount = %s, + totalRebuys = %s, + totalAddons = %s, + koBounty = %s, + comment = %s, + commentTs = %s + WHERE id=%s + """ + + self.query['getTourneysPlayers'] = """SELECT id, + payinAmount, + rank, + winnings, + nbRebuys, + nbAddons, + nbKO, + comment, + commentTs + FROM TourneysPlayers + WHERE tourneyId=%s AND playerId+0=%s + """ - self.query['insertTourney'] = """INSERT INTO Tourneys - (tourneyTypeId, siteTourneyNo, entries, prizepool, - startTime, endTime, buyinChips, tourneyName, matrixIdProcessed, - rebuyChips, addonChips, rebuyAmount, addonAmount, totalRebuys, - totalAddons, koBounty, comment, commentTs) - VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, - %s, %s, %s, %s, %s, %s, %s, %s) - """ - - self.query['updateTourney'] = """UPDATE Tourneys - SET tourneyTypeId = %s, - entries = %s, - prizepool = %s, - startTime = %s, - endTime = %s, - buyinChips = %s, - tourneyName = %s, - matrixIdProcessed = %s, - rebuyChips = %s, - addonChips = %s, - rebuyAmount = %s, - addonAmount = %s, - totalRebuys = %s, - totalAddons = %s, - koBounty = %s, + self.query['updateTourneysPlayers'] = """UPDATE TourneysPlayers + SET payinAmount = %s, + rank = %s, + winnings = %s, + nbRebuys = %s, + nbAddons = %s, + nbKO = %s, comment = %s, commentTs = %s - WHERE id=%s - """ - - self.query['getTourneysPlayers'] = """SELECT id, - payinAmount, - rank, - winnings, - nbRebuys, - nbAddons, - nbKO, - comment, - commentTs - FROM TourneysPlayers - WHERE tourneyId=%s AND playerId+0=%s - """ + WHERE id=%s + """ - self.query['updateTourneysPlayers'] = """UPDATE TourneysPlayers - SET payinAmount = %s, - rank = %s, - winnings = %s, - nbRebuys = %s, - nbAddons = %s, - nbKO = %s, - comment = %s, - commentTs = %s - WHERE id=%s - """ + self.query['insertTourneysPlayers'] = """INSERT INTO TourneysPlayers + (tourneyId, playerId, payinAmount, rank, winnings, nbRebuys, nbAddons, nbKO, comment, commentTs) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) + """ - self.query['insertTourneysPlayers'] = """INSERT INTO TourneysPlayers - (tourneyId, playerId, payinAmount, rank, winnings, nbRebuys, nbAddons, nbKO, comment, commentTs) - VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) - """ - - self.query['selectHandsPlayersWithWrongTTypeId'] = """SELECT id - FROM HandsPlayers - WHERE tourneyTypeId <> %s AND (TourneysPlayersId+0=%s) - """ + self.query['selectHandsPlayersWithWrongTTypeId'] = """SELECT id + FROM HandsPlayers + WHERE tourneyTypeId <> %s AND (TourneysPlayersId+0=%s) + """ # self.query['updateHandsPlayersForTTypeId2'] = """UPDATE HandsPlayers # SET tourneyTypeId= %s # WHERE (TourneysPlayersId+0=%s) # """ - self.query['updateHandsPlayersForTTypeId'] = """UPDATE HandsPlayers - SET tourneyTypeId= %s - WHERE (id=%s) - """ + self.query['updateHandsPlayersForTTypeId'] = """UPDATE HandsPlayers + SET tourneyTypeId= %s + WHERE (id=%s) + """ - self.query['handsPlayersTTypeId_joiner'] = " OR TourneysPlayersId+0=" - self.query['handsPlayersTTypeId_joiner_id'] = " OR id=" + self.query['handsPlayersTTypeId_joiner'] = " OR TourneysPlayersId+0=" + self.query['handsPlayersTTypeId_joiner_id'] = " OR id=" - self.query['store_hand'] = """INSERT INTO Hands ( - tablename, - gametypeid, - sitehandno, - handstart, - importtime, - seats, - maxseats, - texture, - playersVpi, - boardcard1, - boardcard2, - boardcard3, - boardcard4, - boardcard5, - playersAtStreet1, - playersAtStreet2, - playersAtStreet3, - playersAtStreet4, - playersAtShowdown, - street0Raises, - street1Raises, - street2Raises, - street3Raises, - street4Raises, - street1Pot, - street2Pot, - street3Pot, - street4Pot, - showdownPot - ) - VALUES - (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, - %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, - %s, %s, %s, %s, %s, %s, %s, %s, %s)""" + self.query['store_hand'] = """INSERT INTO Hands ( + tablename, + gametypeid, + sitehandno, + handstart, + importtime, + seats, + maxseats, + texture, + playersVpi, + boardcard1, + boardcard2, + boardcard3, + boardcard4, + boardcard5, + playersAtStreet1, + playersAtStreet2, + playersAtStreet3, + playersAtStreet4, + playersAtShowdown, + street0Raises, + street1Raises, + street2Raises, + street3Raises, + street4Raises, + street1Pot, + street2Pot, + street3Pot, + street4Pot, + showdownPot + ) + VALUES + (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, + %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, + %s, %s, %s, %s, %s, %s, %s, %s, %s)""" - - - if db_server == 'mysql': - self.query['placeholder'] = u'%s' - elif db_server == 'postgresql': - self.query['placeholder'] = u'%s' - elif db_server == 'sqlite': - self.query['placeholder'] = u'?' + + + if db_server == 'mysql': + self.query['placeholder'] = u'%s' + elif db_server == 'postgresql': + self.query['placeholder'] = u'%s' + elif db_server == 'sqlite': + self.query['placeholder'] = u'?' - # If using sqlite, use the ? placeholder instead of %s - if db_server == 'sqlite': - for k,q in self.query.iteritems(): - self.query[k] = re.sub('%s','?',q) + # If using sqlite, use the ? placeholder instead of %s + if db_server == 'sqlite': + for k,q in self.query.iteritems(): + self.query[k] = re.sub('%s','?',q) if __name__== "__main__": # just print the default queries and exit diff --git a/pyfpdb/fpdb.py b/pyfpdb/fpdb.py index 0b3c4f4a..baac9f16 100755 --- a/pyfpdb/fpdb.py +++ b/pyfpdb/fpdb.py @@ -450,7 +450,7 @@ class fpdb: if self.db != None and self.db.fdb != None: self.db.disconnect() - self.sql = SQL.Sql(type = self.settings['db-type'], db_server = self.settings['db-server']) + self.sql = SQL.Sql(db_server = self.settings['db-server']) try: self.db = Database.Database(self.config, sql = self.sql) except FpdbMySQLFailedError: From 0e6254ce0dbc3628f7b733b8badb6ae738dc6969 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 3 Nov 2009 13:49:16 -0500 Subject: [PATCH 31/54] basic cleanup --- pyfpdb/Configuration.py | 23 ++++++++--------------- 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 0fb8e603..624a8666 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -110,25 +110,18 @@ class Site: self.xpad = node.getAttribute("xpad") self.ypad = node.getAttribute("ypad") self.layout = {} - - print self.site_name, self.HH_path + + print "Loading site", self.site_name for layout_node in node.getElementsByTagName('layout'): lo = Layout(layout_node) self.layout[lo.max] = lo # Site defaults - if self.xpad == "": self.xpad = 1 - else: self.xpad = int(self.xpad) - - if self.ypad == "": self.ypad = 0 - else: self.ypad = int(self.ypad) - - if self.font_size == "": self.font_size = 7 - else: self.font_size = int(self.font_size) - - if self.hudopacity == "": self.hudopacity = 1.0 - else: self.hudopacity = float(self.hudopacity) + self.xpad = 1 if self.xpad == "" else int(self.xpad) + self.ypad = 0 if self.ypad == "" else int(self.ypad) + self.font_size = 7 if self.font_size == "" else int(self.font_size) + self.hudopacity = 1.0 if self.hud_opacity == "" else float(self.hudopacity) if self.use_frames == "": self.use_frames = False if self.font == "": self.font = "Sans" @@ -436,7 +429,7 @@ class Config: db = self.get_db_parameters() if db['db-password'] == 'YOUR MYSQL PASSWORD': df_file = self.find_default_conf() - if df_file == None: # this is bad + if df_file is None: # this is bad pass else: df_parms = self.read_default_conf(df_file) @@ -769,7 +762,7 @@ class Config: return locations def get_aux_locations(self, aux = "mucked", max = "9"): - + try: locations = self.aux_windows[aux].layout[max].location except: From 6bf1824ee7e956634619f16c185af89422a4aa3e Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 3 Nov 2009 13:56:26 -0500 Subject: [PATCH 32/54] clarify where some logged or printed messages were coming from exactly --- pyfpdb/BetfairToFpdb.py | 2 +- pyfpdb/CarbonToFpdb.py | 2 +- pyfpdb/Database.py | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/pyfpdb/BetfairToFpdb.py b/pyfpdb/BetfairToFpdb.py index f4d8bf9b..b308d071 100755 --- a/pyfpdb/BetfairToFpdb.py +++ b/pyfpdb/BetfairToFpdb.py @@ -191,7 +191,7 @@ class Betfair(HandHistoryConverter): elif action.group('ATYPE') == 'checks': hand.addCheck( street, action.group('PNAME')) else: - print "DEBUG: unimplemented readAction: '%s' '%s'" %(action.group('PNAME'),action.group('ATYPE'),) + sys.stderr.write( "DEBUG: unimplemented readAction: '%s' '%s'" %(action.group('PNAME'),action.group('ATYPE'),)) def readShowdownActions(self, hand): diff --git a/pyfpdb/CarbonToFpdb.py b/pyfpdb/CarbonToFpdb.py index fa1ad6fd..cc7afb81 100644 --- a/pyfpdb/CarbonToFpdb.py +++ b/pyfpdb/CarbonToFpdb.py @@ -67,7 +67,7 @@ class CarbonPoker(HandHistoryConverter): if(type == "Holdem"): gametype = gametype + ["hold"] else: - print "Unknown gametype: '%s'" % (type) + print "Carbon: Unknown gametype: '%s'" % (type) stakes = desc_node[0].getAttribute("stakes") #TODO: no examples of anything except nlhe diff --git a/pyfpdb/Database.py b/pyfpdb/Database.py index 5bf7f488..7ebc98b2 100755 --- a/pyfpdb/Database.py +++ b/pyfpdb/Database.py @@ -395,7 +395,7 @@ class Database: row = c.fetchone() except: # TODO: what error is a database error?! err = traceback.extract_tb(sys.exc_info()[2])[-1] - print "*** Error: " + err[2] + "(" + str(err[1]) + "): " + str(sys.exc_info()[1]) + print "*** Database Error: " + err[2] + "(" + str(err[1]) + "): " + str(sys.exc_info()[1]) else: if row and row[0]: self.hand_1day_ago = int(row[0]) @@ -421,10 +421,10 @@ class Database: if row and row[0]: self.date_nhands_ago[str(playerid)] = row[0] c.close() - print "date n hands ago = " + self.date_nhands_ago[str(playerid)] + "(playerid "+str(playerid)+")" + print "Database: date n hands ago = " + self.date_nhands_ago[str(playerid)] + "(playerid "+str(playerid)+")" except: err = traceback.extract_tb(sys.exc_info()[2])[-1] - print "***Error: "+err[2]+"("+str(err[1])+"): "+str(sys.exc_info()[1]) + print "*** Database Error: "+err[2]+"("+str(err[1])+"): "+str(sys.exc_info()[1]) def get_stats_from_hand( self, hand, type # type is "ring" or "tour" , hud_params = {'aggregate_tour':False, 'aggregate_ring':False, 'hud_style':'A', 'hud_days':30, 'agg_bb_mult':100 @@ -657,7 +657,7 @@ class Database: except: ret = -1 err = traceback.extract_tb(sys.exc_info()[2]) - print "***get_last_insert_id error: " + str(sys.exc_info()[1]) + print "*** Database get_last_insert_id error: " + str(sys.exc_info()[1]) print "\n".join( [e[0]+':'+str(e[1])+" "+e[2] for e in err] ) raise return ret From 7667a39deddc873afc870dc215461b67fb9a97e1 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 3 Nov 2009 14:04:22 -0500 Subject: [PATCH 33/54] cleanup --- pyfpdb/FulltiltToFpdb.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pyfpdb/FulltiltToFpdb.py b/pyfpdb/FulltiltToFpdb.py index 5ce0a5c8..dfff5508 100755 --- a/pyfpdb/FulltiltToFpdb.py +++ b/pyfpdb/FulltiltToFpdb.py @@ -376,7 +376,7 @@ class Fulltilt(HandHistoryConverter): elif action.group('ATYPE') == ' checks': hand.addCheck( street, action.group('PNAME')) else: - print "DEBUG: unimplemented readAction: '%s' '%s'" %(action.group('PNAME'),action.group('ATYPE'),) + print "FullTilt: DEBUG: unimplemented readAction: '%s' '%s'" %(action.group('PNAME'),action.group('ATYPE'),) def readShowdownActions(self, hand): @@ -654,7 +654,7 @@ class Fulltilt(HandHistoryConverter): tourney.addPlayer(rank, a.group('PNAME'), winnings, 0, 0, 0, 0) else: - print "Player finishing stats unreadable : %s" % a + print "FullTilt: Player finishing stats unreadable : %s" % a # Find Hero n = self.re_TourneyHeroFinishingP.search(playersText) @@ -663,9 +663,9 @@ class Fulltilt(HandHistoryConverter): tourney.hero = heroName # Is this really useful ? if heroName not in tourney.finishPositions: - print heroName, "not found in tourney.finishPositions ..." + print "FullTilt:", heroName, "not found in tourney.finishPositions ..." elif (tourney.finishPositions[heroName] != Decimal(n.group('HERO_FINISHING_POS'))): - print "Bad parsing : finish position incoherent : %s / %s" % (tourney.finishPositions[heroName], n.group('HERO_FINISHING_POS')) + print "FullTilt: Bad parsing : finish position incoherent : %s / %s" % (tourney.finishPositions[heroName], n.group('HERO_FINISHING_POS')) return True From a6b7292943363b4a2f616873491643fd3a1502f7 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 3 Nov 2009 14:30:52 -0500 Subject: [PATCH 34/54] mostly None checkings fixed (== to is != to is not) --- pyfpdb/Configuration.py | 64 ++++++++++++++++------------------ pyfpdb/Database.py | 6 ++-- pyfpdb/Filters.py | 8 ++--- pyfpdb/FulltiltToFpdb.py | 27 +++++++------- pyfpdb/GuiAutoImport.py | 23 ++++++------ pyfpdb/GuiBulkImport.py | 2 +- pyfpdb/GuiSessionViewer.py | 2 +- pyfpdb/HUD_main.py | 4 +-- pyfpdb/Hand.py | 12 +++---- pyfpdb/HandHistoryConverter.py | 2 +- pyfpdb/Hud.py | 9 ++--- pyfpdb/Mucked.py | 2 +- pyfpdb/PokerStarsToFpdb.py | 15 ++++---- pyfpdb/Stats.py | 4 +-- pyfpdb/TableWindow.py | 6 ++-- pyfpdb/Tables.py | 4 +-- pyfpdb/TournamentTracker.py | 2 +- pyfpdb/fpdb.py | 4 +-- pyfpdb/fpdb_import.py | 4 +-- pyfpdb/fpdb_parse_logic.py | 4 +-- 20 files changed, 101 insertions(+), 103 deletions(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 624a8666..1da3e9f7 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -316,22 +316,20 @@ class Config: # we check the existence of "file" and try to recover if it doesn't exist self.default_config_path = self.get_default_config_path() - if file != None: # configuration file path has been passed + if file is not None: # config file path passed in file = os.path.expanduser(file) if not os.path.exists(file): print "Configuration file %s not found. Using defaults." % (file) sys.stderr.write("Configuration file %s not found. Using defaults." % (file)) file = None - if file == None: # configuration file path not passed or invalid + if file is None: # configuration file path not passed or invalid file = self.find_config() #Look for a config file in the normal places - if file == None: # no config file in the normal places + if file is None: # no config file in the normal places file = self.find_example_config() #Look for an example file to edit - if file != None: - pass - if file == None: # that didn't work either, just die + if file is None: # that didn't work either, just die print "No HUD_config_xml found after looking in current directory and "+self.default_config_path+"\nExiting" sys.stderr.write("No HUD_config_xml found after looking in current directory and "+self.default_config_path+"\nExiting") print "press enter to continue" @@ -520,7 +518,7 @@ class Config: def get_layout_node(self, site_node, layout): for layout_node in site_node.getElementsByTagName("layout"): - if layout_node.getAttribute("max") == None: + if layout_node.getAttribute("max") is None: return None if int( layout_node.getAttribute("max") ) == int( layout ): return layout_node @@ -536,7 +534,7 @@ class Config: return location_node def save(self, file = None): - if file != None: + if file is not None: with open(file, 'w') as f: self.doc.writexml(f) else: @@ -549,7 +547,7 @@ class Config: site_node = self.get_site_node(site_name) layout_node = self.get_layout_node(site_node, max) # TODO: how do we support inserting new layouts? - if layout_node == None: + if layout_node is None: return for i in range(1, max + 1): location_node = self.get_location_node(layout_node, i) @@ -560,7 +558,7 @@ class Config: def edit_aux_layout(self, aux_name, max, width = None, height = None, locations = None): aux_node = self.get_aux_node(aux_name) layout_node = self.get_layout_node(aux_node, max) - if layout_node == None: + if layout_node is None: print "aux node not found" return print "editing locations =", locations @@ -608,17 +606,17 @@ class Config: db_pass = None, db_server = None, db_type = None): db_node = self.get_db_node(db_name) if db_node != None: - if db_ip != None: db_node.setAttribute("db_ip", db_ip) - if db_user != None: db_node.setAttribute("db_user", db_user) - if db_pass != None: db_node.setAttribute("db_pass", db_pass) - if db_server != None: db_node.setAttribute("db_server", db_server) - if db_type != None: db_node.setAttribute("db_type", db_type) + if db_ip is not None: db_node.setAttribute("db_ip", db_ip) + if db_user is not None: db_node.setAttribute("db_user", db_user) + if db_pass is not None: db_node.setAttribute("db_pass", db_pass) + if db_server is not None: db_node.setAttribute("db_server", db_server) + if db_type is not None: db_node.setAttribute("db_type", db_type) if self.supported_databases.has_key(db_name): - if db_ip != None: self.supported_databases[db_name].dp_ip = db_ip - if db_user != None: self.supported_databases[db_name].dp_user = db_user - if db_pass != None: self.supported_databases[db_name].dp_pass = db_pass - if db_server != None: self.supported_databases[db_name].dp_server = db_server - if db_type != None: self.supported_databases[db_name].dp_type = db_type + if db_ip is not None: self.supported_databases[db_name].dp_ip = db_ip + if db_user is not None: self.supported_databases[db_name].dp_user = db_user + if db_pass is not None: self.supported_databases[db_name].dp_pass = db_pass + if db_server is not None: self.supported_databases[db_name].dp_server = db_server + if db_type is not None: self.supported_databases[db_name].dp_type = db_type return def getDefaultSite(self): @@ -809,19 +807,19 @@ class Config: font = None, font_size = None): """Sets the specified site parameters for the specified site.""" site_node = self.get_site_node(site_name) - if db_node != None: - if converter != None: site_node.setAttribute("converter", converter) - if decoder != None: site_node.setAttribute("decoder", decoder) - if hudbgcolor != None: site_node.setAttribute("hudbgcolor", hudbgcolor) - if hudfgcolor != None: site_node.setAttribute("hudfgcolor", hudfgcolor) - if hudopacity != None: site_node.setAttribute("hudopacity", hudopacity) - if screen_name != None: site_node.setAttribute("screen_name", screen_name) - if site_path != None: site_node.setAttribute("site_path", site_path) - if table_finder != None: site_node.setAttribute("table_finder", table_finder) - if HH_path != None: site_node.setAttribute("HH_path", HH_path) - if enabled != None: site_node.setAttribute("enabled", enabled) - if font != None: site_node.setAttribute("font", font) - if font_size != None: site_node.setAttribute("font_size", font_size) + if db_node is not None: + if converter is not None: site_node.setAttribute("converter", converter) + if decoder is not None: site_node.setAttribute("decoder", decoder) + if hudbgcolor is not None: site_node.setAttribute("hudbgcolor", hudbgcolor) + if hudfgcolor is not None: site_node.setAttribute("hudfgcolor", hudfgcolor) + if hudopacity is not None: site_node.setAttribute("hudopacity", hudopacity) + if screen_name is not None: site_node.setAttribute("screen_name", screen_name) + if site_path is not None: site_node.setAttribute("site_path", site_path) + if table_finder is not None: site_node.setAttribute("table_finder", table_finder) + if HH_path is not None: site_node.setAttribute("HH_path", HH_path) + if enabled is not None: site_node.setAttribute("enabled", enabled) + if font is not None: site_node.setAttribute("font", font) + if font_size is not None: site_node.setAttribute("font_size", font_size) return def get_aux_windows(self): diff --git a/pyfpdb/Database.py b/pyfpdb/Database.py index 7ebc98b2..15294bbb 100755 --- a/pyfpdb/Database.py +++ b/pyfpdb/Database.py @@ -353,7 +353,7 @@ class Database: # else: # cards += ranks[d['card' + str(i) + 'Value']] + d['card' +str(i) + 'Suit'] cv = "card%dvalue" % i - if cv not in d or d[cv] == None: + if cv not in d or d[cv] is None: break elif d[cv] == 0: cards += "xx" @@ -551,7 +551,7 @@ class Database: def get_player_names(self, config, site_id=None, like_player_name="%"): """Fetch player names from players. Use site_id and like_player_name if provided""" - if site_id == None: + if site_id is None: site_id = -1 c = self.get_cursor() c.execute(self.sql.query['get_player_names'], (like_player_name, site_id, site_id)) @@ -1183,7 +1183,7 @@ class Database: if p_id: self.hero_ids[site_id] = int(p_id) - if start == None: + if start is None: start = self.hero_hudstart_def if self.hero_ids == {}: where = "" diff --git a/pyfpdb/Filters.py b/pyfpdb/Filters.py index 08581c83..4ee2bdf1 100644 --- a/pyfpdb/Filters.py +++ b/pyfpdb/Filters.py @@ -305,10 +305,10 @@ class Filters(threading.Thread): print "self.limit[%s] set to %s" %(limit, self.limits[limit]) if limit.isdigit() or (len(limit) > 2 and limit[-2:] == 'nl'): if self.limits[limit]: - if self.cbNoLimits != None: + if self.cbNoLimits is not None: self.cbNoLimits.set_active(False) else: - if self.cbAllLimits != None: + if self.cbAllLimits is not None: self.cbAllLimits.set_active(False) if not self.limits[limit]: if limit.isdigit(): @@ -319,9 +319,9 @@ class Filters(threading.Thread): if self.limits[limit]: #for cb in self.cbLimits.values(): # cb.set_active(True) - if self.cbFL != None: + if self.cbFL is not None: self.cbFL.set_active(True) - if self.cbNL != None: + if self.cbNL is not None: self.cbNL.set_active(True) elif limit == "none": if self.limits[limit]: diff --git a/pyfpdb/FulltiltToFpdb.py b/pyfpdb/FulltiltToFpdb.py index dfff5508..1721236a 100755 --- a/pyfpdb/FulltiltToFpdb.py +++ b/pyfpdb/FulltiltToFpdb.py @@ -184,11 +184,11 @@ class Fulltilt(HandHistoryConverter): info['limitType'] = limits[mg['LIMIT']] info['sb'] = mg['SB'] info['bb'] = mg['BB'] - if mg['GAME'] != None: + if mg['GAME'] is not None: (info['base'], info['category']) = games[mg['GAME']] - if mg['CURRENCY'] != None: + if mg['CURRENCY'] is not None: info['currency'] = currencies[mg['CURRENCY']] - if mg['TOURNO'] == None: info['type'] = "ring" + if mg['TOURNO'] is None: info['type'] = "ring" else: info['type'] = "tour" # NB: SB, BB must be interpreted as blinds or bets depending on limit type. # if info['type'] == "tour": return None # importer is screwed on tournies, pass on those hands so we don't interrupt other autoimporting @@ -196,7 +196,7 @@ class Fulltilt(HandHistoryConverter): def readHandInfo(self, hand): m = self.re_HandInfo.search(hand.handText) - if(m == None): + if m is None: logging.info("Didn't match re_HandInfo") logging.info(hand.handText) return None @@ -212,7 +212,7 @@ class Fulltilt(HandHistoryConverter): if m2: hand.maxseats = int(m2.group('MAX')) hand.tourNo = m.group('TOURNO') - if m.group('PLAY') != None: + if m.group('PLAY') is not None: hand.gametype['currency'] = 'play' # Done: if there's a way to figure these out, we should.. otherwise we have to stuff it with unknowns @@ -240,9 +240,9 @@ class Fulltilt(HandHistoryConverter): hand.isShootout = True - if hand.buyin == None: + if hand.buyin is None: hand.buyin = "$0.00+$0.00" - if hand.level == None: + if hand.level is None: hand.level = "0" # These work, but the info is already in the Hand class - should be used for tourneys though. @@ -343,11 +343,11 @@ class Fulltilt(HandHistoryConverter): m = self.re_HeroCards.finditer(hand.streets[street]) for found in m: player = found.group('PNAME') - if found.group('NEWCARDS') == None: + if found.group('NEWCARDS') is None: newcards = [] else: newcards = found.group('NEWCARDS').split(' ') - if found.group('OLDCARDS') == None: + if found.group('OLDCARDS') is None: oldcards = [] else: oldcards = found.group('OLDCARDS').split(' ') @@ -416,7 +416,8 @@ class Fulltilt(HandHistoryConverter): def readOther(self, hand): m = self.re_Mixed.search(self.in_path) - if m == None: hand.mixed = None + if m is None: + hand.mixed = None else: hand.mixed = self.mixes[m.groupdict()['MIXED']] @@ -472,8 +473,10 @@ class Fulltilt(HandHistoryConverter): (info['base'], info['category']) = games[mg['GAME']] if mg['CURRENCY'] is not None: info['currency'] = currencies[mg['CURRENCY']] - if mg['TOURNO'] == None: info['type'] = "ring" - else: info['type'] = "tour" + if mg['TOURNO'] is None: + info['type'] = "ring" + else: + info['type'] = "tour" # NB: SB, BB must be interpreted as blinds or bets depending on limit type. # Info is now ready to be copied in the tourney object diff --git a/pyfpdb/GuiAutoImport.py b/pyfpdb/GuiAutoImport.py index 9e99908b..eddd3619 100755 --- a/pyfpdb/GuiAutoImport.py +++ b/pyfpdb/GuiAutoImport.py @@ -41,8 +41,8 @@ class GuiAutoImport (threading.Thread): imp = self.config.get_import_parameters() - print "Import parameters" - print imp +# print "Import parameters" +# print imp self.input_settings = {} self.pipe_to_hud = None @@ -130,7 +130,8 @@ class GuiAutoImport (threading.Thread): data[1].set_text(dia_chooser.get_filename()) self.input_settings[data[0]][0] = dia_chooser.get_filename() elif response == gtk.RESPONSE_CANCEL: - print 'Closed, no files selected' + #print 'Closed, no files selected' + pass dia_chooser.destroy() #end def GuiAutoImport.browseClicked @@ -184,22 +185,24 @@ class GuiAutoImport (threading.Thread): command = os.path.join(sys.path[0], 'HUD_main.py') command = [command, ] + string.split(self.settings['cl_options']) bs = 1 + try: - self.pipe_to_hud = subprocess.Popen(command, bufsize = bs, stdin = subprocess.PIPE, - universal_newlines = True) + self.pipe_to_hud = subprocess.Popen(command, bufsize=bs, + stdin=subprocess.PIPE, + universal_newlines=True) except: err = traceback.extract_tb(sys.exc_info()[2])[-1] - print "*** Error: " + err[2] + "(" + str(err[1]) + "): " + str(sys.exc_info()[1]) + print "*** GuiAutoImport Error opening pipe: " + err[2] + "(" + str(err[1]) + "): " + str(sys.exc_info()[1]) else: for site in self.input_settings: self.importer.addImportDirectory(self.input_settings[site][0], True, site, self.input_settings[site][1]) + print " * Add", site, " import directory", str(self.input_settings[site][0]) print "+Import directory - Site: " + site + " dir: " + str(self.input_settings[site][0]) - self.do_import() - + self.do_import() interval = int(self.intervalEntry.get_text()) if self.importtimer != 0: gobject.source_remove(self.importtimer) - self.importtimer = gobject.timeout_add(interval*1000, self.do_import) + self.importtimer = gobject.timeout_add(interval * 1000, self.do_import) else: print "auto-import aborted - global lock not available" @@ -209,7 +212,7 @@ class GuiAutoImport (threading.Thread): self.doAutoImportBool = False # do_import will return this and stop the gobject callback timer print "Stopping autoimport - global lock released." if self.pipe_to_hud.poll() is not None: - print "HUD already terminated" + print " * Stop Autoimport: HUD already terminated" else: #print >>self.pipe_to_hud.stdin, "\n" self.pipe_to_hud.communicate('\n') # waits for process to terminate diff --git a/pyfpdb/GuiBulkImport.py b/pyfpdb/GuiBulkImport.py index 9cb54d50..a637e6f4 100755 --- a/pyfpdb/GuiBulkImport.py +++ b/pyfpdb/GuiBulkImport.py @@ -118,7 +118,7 @@ class GuiBulkImport(): self.progressbar.set_fraction(0) except: err = traceback.extract_tb(sys.exc_info()[2])[-1] - print "***Error: "+err[2]+"("+str(err[1])+"): "+str(sys.exc_info()[1]) + print "*** BulkImport Error: "+err[2]+"("+str(err[1])+"): "+str(sys.exc_info()[1]) self.settings['global_lock'].release() else: print "bulk-import aborted - global lock not available" diff --git a/pyfpdb/GuiSessionViewer.py b/pyfpdb/GuiSessionViewer.py index 79fe3191..d8cd7042 100755 --- a/pyfpdb/GuiSessionViewer.py +++ b/pyfpdb/GuiSessionViewer.py @@ -310,7 +310,7 @@ class GuiSessionViewer (threading.Thread): except: pass - if self.fig != None: + if self.fig is not None: self.fig.clear() self.fig = Figure(figsize=(5,4), dpi=100) if self.canvas is not None: diff --git a/pyfpdb/HUD_main.py b/pyfpdb/HUD_main.py index 8ccc194e..56a6e021 100755 --- a/pyfpdb/HUD_main.py +++ b/pyfpdb/HUD_main.py @@ -270,11 +270,11 @@ class HUD_main(object): tablewindow = Tables.discover_tournament_table(self.config, tour_number, tab_number) else: tablewindow = Tables.discover_table_by_name(self.config, table_name) - if tablewindow == None: + if tablewindow is None: # If no client window is found on the screen, complain and continue if type == "tour": table_name = "%s %s" % (tour_number, tab_number) - sys.stderr.write("table name "+table_name+" not found, skipping.\n") + sys.stderr.write("HUD create: table name "+table_name+" not found, skipping.\n") else: self.create_HUD(new_hand_id, tablewindow, temp_key, max, poker_game, type, stat_dict, cards) self.db_connection.connection.rollback() diff --git a/pyfpdb/Hand.py b/pyfpdb/Hand.py index 602a6a1a..a5ea87ec 100644 --- a/pyfpdb/Hand.py +++ b/pyfpdb/Hand.py @@ -550,12 +550,12 @@ Map the tuple self.gametype onto the pokerstars string describing it """Return the first HH line for the current hand.""" gs = "PokerStars Game #%s: " % self.handid - if self.tourNo != None and self.mixed != None: # mixed tournament + if self.tourNo is not None and self.mixed is not None: # mixed tournament gs = gs + "Tournament #%s, %s %s (%s) - Level %s (%s) - " % (self.tourNo, self.buyin, self.MS[self.mixed], self.getGameTypeAsString(), self.level, self.getStakesAsString()) - elif self.tourNo != None: # all other tournaments + elif self.tourNo is not None: # all other tournaments gs = gs + "Tournament #%s, %s %s - Level %s (%s) - " % (self.tourNo, self.buyin, self.getGameTypeAsString(), self.level, self.getStakesAsString()) - elif self.mixed != None: # all other mixed games + elif self.mixed is not None: # all other mixed games gs = gs + " %s (%s, %s) - " % (self.MS[self.mixed], self.getGameTypeAsString(), self.getStakesAsString()) else: # non-mixed cash games @@ -628,7 +628,7 @@ class HoldemOmahaHand(Hand): hhc.readShownCards(self) self.totalPot() # finalise it (total the pot) hhc.getRake(self) - if self.maxseats == None: + if self.maxseats is None: self.maxseats = hhc.guessMaxSeats(self) hhc.readOther(self) elif builtFrom == "DB": @@ -897,7 +897,7 @@ class DrawHand(Hand): hhc.readShownCards(self) self.totalPot() # finalise it (total the pot) hhc.getRake(self) - if self.maxseats == None: + if self.maxseats is None: self.maxseats = hhc.guessMaxSeats(self) hhc.readOther(self) elif builtFrom == "DB": @@ -1073,7 +1073,7 @@ class StudHand(Hand): hhc.readShownCards(self) # not done yet self.totalPot() # finalise it (total the pot) hhc.getRake(self) - if self.maxseats == None: + if self.maxseats is None: self.maxseats = hhc.guessMaxSeats(self) hhc.readOther(self) elif builtFrom == "DB": diff --git a/pyfpdb/HandHistoryConverter.py b/pyfpdb/HandHistoryConverter.py index 0024cfe5..6edb9029 100644 --- a/pyfpdb/HandHistoryConverter.py +++ b/pyfpdb/HandHistoryConverter.py @@ -256,7 +256,7 @@ which it expects to find at self.re_TailSplitHands -- see for e.g. Everleaf.py. self.readFile() self.obs = self.obs.strip() self.obs = self.obs.replace('\r\n', '\n') - if self.obs == "" or self.obs == None: + if self.obs is None or self.obs == "": log.info("Read no hands.") return [] return re.split(self.re_SplitHands, self.obs) diff --git a/pyfpdb/Hud.py b/pyfpdb/Hud.py index 60fc29be..f0f47898 100644 --- a/pyfpdb/Hud.py +++ b/pyfpdb/Hud.py @@ -61,7 +61,7 @@ class Hud: def __init__(self, parent, table, max, poker_game, config, db_connection): # __init__ is (now) intended to be called from the stdin thread, so it # cannot touch the gui - if parent == None: # running from cli .. + if parent is None: # running from cli .. self.parent = self self.parent = parent self.table = table @@ -87,11 +87,6 @@ class Hud: self.backgroundcolor = gtk.gdk.color_parse(self.colors['hudbgcolor']) self.foregroundcolor = gtk.gdk.color_parse(self.colors['hudfgcolor']) - - if font == None: - font = "Sans" - if font_size == None: - font_size = "8" self.font = pango.FontDescription("%s %s" % (font, font_size)) # do we need to add some sort of condition here for dealing with a request for a font that doesn't exist? @@ -136,7 +131,7 @@ class Hud: killitem = gtk.MenuItem('Kill This HUD') menu.append(killitem) - if self.parent != None: + if self.parent is not None: killitem.connect("activate", self.parent.kill_hud, self.table_name) saveitem = gtk.MenuItem('Save HUD Layout') diff --git a/pyfpdb/Mucked.py b/pyfpdb/Mucked.py index 6da35f6d..dd424e63 100755 --- a/pyfpdb/Mucked.py +++ b/pyfpdb/Mucked.py @@ -479,7 +479,7 @@ class Flop_Mucked(Aux_Seats): if i != "common": id = self.get_id_from_seat(i) # sc: had KeyError here with new table so added id != None test as a guess: - if id != None: + if id is not None: self.m_windows[i].eb.set_tooltip_text(self.hud.stat_dict[id]['screen_name']) def update_gui(self, new_hand_id): diff --git a/pyfpdb/PokerStarsToFpdb.py b/pyfpdb/PokerStarsToFpdb.py index 9085f3dd..d9e652d9 100755 --- a/pyfpdb/PokerStarsToFpdb.py +++ b/pyfpdb/PokerStarsToFpdb.py @@ -164,7 +164,7 @@ class PokerStars(HandHistoryConverter): if 'CURRENCY' in mg: info['currency'] = currencies[mg['CURRENCY']] - if 'TOURNO' in mg and mg['TOURNO'] == None: + if 'TOURNO' in mg and mg['TOURNO'] is None: info['type'] = 'ring' else: info['type'] = 'tour' @@ -172,7 +172,6 @@ class PokerStars(HandHistoryConverter): # NB: SB, BB must be interpreted as blinds or bets depending on limit type. return info - def readHandInfo(self, hand): info = {} m = self.re_HandInfo.search(hand.handText,re.DOTALL) @@ -182,7 +181,8 @@ class PokerStars(HandHistoryConverter): else: pass # throw an exception here, eh? m = self.re_GameInfo.search(hand.handText) - if m: info.update(m.groupdict()) + if m: + info.update(m.groupdict()) # m = self.re_Button.search(hand.handText) # if m: info.update(m.groupdict()) # TODO : I rather like the idea of just having this dict as hand.info @@ -205,8 +205,7 @@ class PokerStars(HandHistoryConverter): hand.maxseats = int(info[key]) if key == 'MIXED': - if info[key] == None: hand.mixed = None - else: hand.mixed = self.mixes[info[key]] + hand.mixed = self.mixes[info[key]] if info[key] is not None else None if key == 'TOURNO': hand.tourNo = info[key] @@ -214,7 +213,7 @@ class PokerStars(HandHistoryConverter): hand.buyin = info[key] if key == 'LEVEL': hand.level = info[key] - if key == 'PLAY' and info['PLAY'] != None: + if key == 'PLAY' and info['PLAY'] is not None: # hand.currency = 'play' # overrides previously set value hand.gametype['currency'] = 'play' @@ -304,11 +303,11 @@ class PokerStars(HandHistoryConverter): m = self.re_HeroCards.finditer(hand.streets[street]) for found in m: player = found.group('PNAME') - if found.group('NEWCARDS') == None: + if found.group('NEWCARDS') is None: newcards = [] else: newcards = found.group('NEWCARDS').split(' ') - if found.group('OLDCARDS') == None: + if found.group('OLDCARDS') is None: oldcards = [] else: oldcards = found.group('OLDCARDS').split(' ') diff --git a/pyfpdb/Stats.py b/pyfpdb/Stats.py index d54ccf12..86caaea5 100755 --- a/pyfpdb/Stats.py +++ b/pyfpdb/Stats.py @@ -68,14 +68,14 @@ def do_tip(widget, tip): def do_stat(stat_dict, player = 24, stat = 'vpip'): match = re_Places.search(stat) - if match == None: + if match is None: result = eval("%(stat)s(stat_dict, %(player)d)" % {'stat': stat, 'player': player}) else: base = stat[0:-2] places = int(stat[-1:]) result = eval("%(stat)s(stat_dict, %(player)d)" % {'stat': base, 'player': player}) match = re_Percent.search(result[1]) - if match == None: + if match is None: result = (result[0], "%.*f" % (places, result[0]), result[2], result[3], result[4], result[5]) else: result = (result[0], "%.*f%%" % (places, 100*result[0]), result[2], result[3], result[4], result[5]) diff --git a/pyfpdb/TableWindow.py b/pyfpdb/TableWindow.py index bf62a69c..0fa2bf22 100644 --- a/pyfpdb/TableWindow.py +++ b/pyfpdb/TableWindow.py @@ -95,12 +95,12 @@ gobject.signal_new("client_destroyed", gtk.Window, class Table_Window(object): def __init__(self, table_name = None, tournament = None, table_number = None): - if table_name != None: + if table_name is not None: search_string = table_name self.name = table_name self.tournament = None self.table = None - elif tournament != None and table_number != None: + elif tournament is not None and table_number is not None: print "tournament %s, table %s" % (tournament, table_number) self.tournament = int(tournament) self.table = int(table_number) @@ -133,7 +133,7 @@ class Table_Window(object): def check_geometry(self): new_geo = self.get_geometry() - if new_geo == None: # window destroyed + if new_geo is None: # window destroyed return "client_destroyed" elif self.x != new_geo['x'] or self.y != new_geo['y']: # window moved diff --git a/pyfpdb/Tables.py b/pyfpdb/Tables.py index 46addabc..ea5dfc4c 100755 --- a/pyfpdb/Tables.py +++ b/pyfpdb/Tables.py @@ -105,7 +105,7 @@ def discover_table_by_name(c, tablename): info = discover_mac_by_name(c, tablename) else: return None - if info == None: + if info is None: return None return Table_Window(info) @@ -141,7 +141,7 @@ def discover_posix(c): if 'History for table:' in listing: continue if 'has no name' in listing: continue info = decode_xwininfo(c, listing) - if info['site'] == None: continue + if info['site'] is None: continue if info['title'] == info['exe']: continue # this appears to be a poker client, so make a table object for it tw = Table_Window(info) diff --git a/pyfpdb/TournamentTracker.py b/pyfpdb/TournamentTracker.py index 2ac95b24..fd63d11c 100644 --- a/pyfpdb/TournamentTracker.py +++ b/pyfpdb/TournamentTracker.py @@ -289,7 +289,7 @@ class ttracker_main(object): tablewindow = Tables.discover_tournament_table(self.config, tour_number, tab_number) else: tablewindow = Tables.discover_table_by_name(self.config, table_name) - if tablewindow == None: + if tablewindow is None: # If no client window is found on the screen, complain and continue if type == "tour": table_name = "%s %s" % (tour_number, tab_number) diff --git a/pyfpdb/fpdb.py b/pyfpdb/fpdb.py index ad1798c2..1fbaed02 100755 --- a/pyfpdb/fpdb.py +++ b/pyfpdb/fpdb.py @@ -447,7 +447,7 @@ class fpdb: self.settings.update(self.config.get_import_parameters()) self.settings.update(self.config.get_default_paths()) - if self.db != None and self.db.fdb != None: + if self.db is not None and self.db.fdb is not None: self.db.disconnect() self.sql = SQL.Sql(type = self.settings['db-type'], db_server = self.settings['db-server']) @@ -487,7 +487,7 @@ class fpdb: response = diaDbVersionWarning.run() diaDbVersionWarning.destroy() - if self.status_bar == None: + if self.status_bar is None: self.status_bar = gtk.Label("Status: Connected to %s database named %s on host %s"%(self.db.get_backend_name(),self.db.database, self.db.host)) self.main_vbox.pack_end(self.status_bar, False, True, 0) self.status_bar.show() diff --git a/pyfpdb/fpdb_import.py b/pyfpdb/fpdb_import.py index 4d384372..a262e62e 100644 --- a/pyfpdb/fpdb_import.py +++ b/pyfpdb/fpdb_import.py @@ -400,7 +400,7 @@ class Importer: file = file.decode(fpdb_simple.LOCALE_ENCODING) # Load filter, process file, pass returned filename to import_fpdb_file - if self.settings['threads'] > 0 and self.writeq != None: + if self.settings['threads'] > 0 and self.writeq is not None: log.info("Converting " + file + " (" + str(q.qsize()) + ")") else: log.info("Converting " + file) @@ -475,7 +475,7 @@ class Importer: db.commit() ttime = time() - starttime - if q == None: + if q is None: log.info("Total stored: %(stored)d\tduplicates:%(duplicates)d\terrors:%(errors)d\ttime:%(ttime)s" % locals()) if not stored: diff --git a/pyfpdb/fpdb_parse_logic.py b/pyfpdb/fpdb_parse_logic.py index 02300315..6fac3669 100644 --- a/pyfpdb/fpdb_parse_logic.py +++ b/pyfpdb/fpdb_parse_logic.py @@ -30,7 +30,7 @@ def mainParser(settings, siteID, category, hand, config, db = None, writeq = Non backend = settings['db-backend'] # Ideally db connection is passed in, if not use sql list if passed in, # otherwise start from scratch - if db == None: + if db is None: db = Database.Database(c = config, sql = None) category = fpdb_simple.recogniseCategory(hand[0]) @@ -222,7 +222,7 @@ def mainParser(settings, siteID, category, hand, config, db = None, writeq = Non , actionNos, hudImportData, maxSeats, tableName, seatNos) # save hand in db via direct call or via q if in a thread - if writeq == None: + if writeq is None: result = db.store_the_hand(htw) else: writeq.put(htw) From 0759ded78fba761971cb3308acab0d3022a8928e Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 3 Nov 2009 14:43:12 -0500 Subject: [PATCH 35/54] fix typo --- pyfpdb/Configuration.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 1da3e9f7..dee245e6 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -121,7 +121,7 @@ class Site: self.xpad = 1 if self.xpad == "" else int(self.xpad) self.ypad = 0 if self.ypad == "" else int(self.ypad) self.font_size = 7 if self.font_size == "" else int(self.font_size) - self.hudopacity = 1.0 if self.hud_opacity == "" else float(self.hudopacity) + self.hudopacity = 1.0 if self.hudopacity == "" else float(self.hudopacity) if self.use_frames == "": self.use_frames = False if self.font == "": self.font = "Sans" From d008eceaefbbb7a4ec915d1c9f43024f6b53c496 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 3 Nov 2009 15:06:48 -0500 Subject: [PATCH 36/54] mostly formatting cleanups --- pyfpdb/GuiAutoImport.py | 22 +++++++------- pyfpdb/GuiBulkImport.py | 63 +++++++++++++++++++++++++++-------------- 2 files changed, 51 insertions(+), 34 deletions(-) diff --git a/pyfpdb/GuiAutoImport.py b/pyfpdb/GuiAutoImport.py index eddd3619..299c8075 100755 --- a/pyfpdb/GuiAutoImport.py +++ b/pyfpdb/GuiAutoImport.py @@ -33,10 +33,9 @@ import string class GuiAutoImport (threading.Thread): def __init__(self, settings, config, sql): - """Constructor for GuiAutoImport""" self.importtimer = 0 - self.settings=settings - self.config=config + self.settings = settings + self.config = config self.sql = sql imp = self.config.get_import_parameters() @@ -55,12 +54,12 @@ class GuiAutoImport (threading.Thread): self.importer.setHandCount(0) # self.importer.setWatchTime() - self.server=settings['db-host'] - self.user=settings['db-user'] - self.password=settings['db-password'] - self.database=settings['db-databaseName'] + self.server = settings['db-host'] + self.user = settings['db-user'] + self.password = settings['db-password'] + self.database = settings['db-databaseName'] - self.mainVBox=gtk.VBox(False,1) + self.mainVBox = gtk.VBox(False,1) hbox = gtk.HBox(True, 0) # contains 2 equal vboxes self.mainVBox.pack_start(hbox, False, False, 0) @@ -144,8 +143,7 @@ class GuiAutoImport (threading.Thread): sys.stdout.flush() gobject.timeout_add(1000, self.reset_startbutton) return True - else: - return False + return False def reset_startbutton(self): if self.pipe_to_hud is not None: @@ -230,7 +228,7 @@ class GuiAutoImport (threading.Thread): #enabling and disabling sites from this interface not possible #expects a box to layout the line horizontally def createSiteLine(self, hbox1, hbox2, site, iconpath, hhpath, filter_name, active = True): - label = gtk.Label(site + " auto-import:") + label = gtk.Label("%s auto-import:" % site) hbox1.pack_start(label, False, False, 3) label.show() @@ -244,7 +242,7 @@ class GuiAutoImport (threading.Thread): hbox2.pack_start(browseButton, False, False, 3) browseButton.show() - label = gtk.Label(' ' + site + " filter:") + label = gtk.Label("%s filter:" % site) hbox2.pack_start(label, False, False, 3) label.show() diff --git a/pyfpdb/GuiBulkImport.py b/pyfpdb/GuiBulkImport.py index a637e6f4..3300b73f 100755 --- a/pyfpdb/GuiBulkImport.py +++ b/pyfpdb/GuiBulkImport.py @@ -142,32 +142,38 @@ class GuiBulkImport(): self.chooser.show() # Table widget to hold the settings - self.table = gtk.Table(rows = 5, columns = 5, homogeneous = False) + self.table = gtk.Table(rows=5, columns=5, homogeneous=False) self.vbox.add(self.table) self.table.show() # checkbox - print start/stop? self.chk_st_st = gtk.CheckButton('Print Start/Stop Info') - self.table.attach(self.chk_st_st, 0, 1, 0, 1, xpadding = 10, ypadding = 0, yoptions=gtk.SHRINK) + self.table.attach(self.chk_st_st, 0, 1, 0, 1, xpadding=10, ypadding=0, + yoptions=gtk.SHRINK) self.chk_st_st.show() self.chk_st_st.set_active(True) # label - status self.lab_status = gtk.Label("Hands/status print:") - self.table.attach(self.lab_status, 1, 2, 0, 1, xpadding = 0, ypadding = 0, yoptions=gtk.SHRINK) + self.table.attach(self.lab_status, 1, 2, 0, 1, xpadding=0, ypadding=0, + yoptions=gtk.SHRINK) self.lab_status.show() self.lab_status.set_justify(gtk.JUSTIFY_RIGHT) self.lab_status.set_alignment(1.0, 0.5) # spin button - status - status_adj = gtk.Adjustment(value=100, lower=0, upper=300, step_incr=10, page_incr=1, page_size=0) #not sure what upper value should be! - self.spin_status = gtk.SpinButton(adjustment=status_adj, climb_rate=0.0, digits=0) - self.table.attach(self.spin_status, 2, 3, 0, 1, xpadding = 10, ypadding = 0, yoptions=gtk.SHRINK) + status_adj = gtk.Adjustment(value=100, lower=0, upper=300, step_incr=10, + page_incr=1, page_size=0) #not sure what upper value should be! + self.spin_status = gtk.SpinButton(adjustment=status_adj, climb_rate=0.0, + digits=0) + self.table.attach(self.spin_status, 2, 3, 0, 1, xpadding=10, ypadding=0, + yoptions=gtk.SHRINK) self.spin_status.show() # label - threads self.lab_threads = gtk.Label("Number of threads:") - self.table.attach(self.lab_threads, 3, 4, 0, 1, xpadding = 0, ypadding = 0, yoptions=gtk.SHRINK) + self.table.attach(self.lab_threads, 3, 4, 0, 1, xpadding=0, ypadding=0, + yoptions=gtk.SHRINK) self.lab_threads.show() if not self.allowThreads: self.lab_threads.set_sensitive(False) @@ -175,34 +181,39 @@ class GuiBulkImport(): self.lab_threads.set_alignment(1.0, 0.5) # spin button - threads - threads_adj = gtk.Adjustment(value=0, lower=0, upper=32, step_incr=1, page_incr=1, page_size=0) #not sure what upper value should be! + threads_adj = gtk.Adjustment(value=0, lower=0, upper=32, step_incr=1, + page_incr=1, page_size=0) #not sure what upper value should be! self.spin_threads = gtk.SpinButton(adjustment=threads_adj, climb_rate=0.0, digits=0) - self.table.attach(self.spin_threads, 4, 5, 0, 1, xpadding = 10, ypadding = 0, yoptions=gtk.SHRINK) + self.table.attach(self.spin_threads, 4, 5, 0, 1, xpadding=10, ypadding=0, + yoptions=gtk.SHRINK) self.spin_threads.show() if not self.allowThreads: self.spin_threads.set_sensitive(False) # checkbox - fail on error? self.chk_fail = gtk.CheckButton('Fail on error') - self.table.attach(self.chk_fail, 0, 1, 1, 2, xpadding = 10, ypadding = 0, yoptions=gtk.SHRINK) + self.table.attach(self.chk_fail, 0, 1, 1, 2, xpadding=10, ypadding=0, yoptions=gtk.SHRINK) self.chk_fail.show() # label - hands self.lab_hands = gtk.Label("Hands/file:") - self.table.attach(self.lab_hands, 1, 2, 1, 2, xpadding = 0, ypadding = 0, yoptions=gtk.SHRINK) + self.table.attach(self.lab_hands, 1, 2, 1, 2, xpadding=0, ypadding=0, yoptions=gtk.SHRINK) self.lab_hands.show() self.lab_hands.set_justify(gtk.JUSTIFY_RIGHT) self.lab_hands.set_alignment(1.0, 0.5) # spin button - hands to import - hands_adj = gtk.Adjustment(value=0, lower=0, upper=10, step_incr=1, page_incr=1, page_size=0) #not sure what upper value should be! + hands_adj = gtk.Adjustment(value=0, lower=0, upper=10, step_incr=1, + page_incr=1, page_size=0) #not sure what upper value should be! self.spin_hands = gtk.SpinButton(adjustment=hands_adj, climb_rate=0.0, digits=0) - self.table.attach(self.spin_hands, 2, 3, 1, 2, xpadding = 10, ypadding = 0, yoptions=gtk.SHRINK) + self.table.attach(self.spin_hands, 2, 3, 1, 2, xpadding=10, ypadding=0, + yoptions=gtk.SHRINK) self.spin_hands.show() # label - drop indexes self.lab_drop = gtk.Label("Drop indexes:") - self.table.attach(self.lab_drop, 3, 4, 1, 2, xpadding = 0, ypadding = 0, yoptions=gtk.SHRINK) + self.table.attach(self.lab_drop, 3, 4, 1, 2, xpadding=0, ypadding=0, + yoptions=gtk.SHRINK) self.lab_drop.show() self.lab_drop.set_justify(gtk.JUSTIFY_RIGHT) self.lab_drop.set_alignment(1.0, 0.5) @@ -213,12 +224,14 @@ class GuiBulkImport(): self.cb_dropindexes.append_text("don't drop") self.cb_dropindexes.append_text('drop') self.cb_dropindexes.set_active(0) - self.table.attach(self.cb_dropindexes, 4, 5, 1, 2, xpadding = 10, ypadding = 0, yoptions=gtk.SHRINK) + self.table.attach(self.cb_dropindexes, 4, 5, 1, 2, xpadding=10, + ypadding=0, yoptions=gtk.SHRINK) self.cb_dropindexes.show() # label - filter self.lab_filter = gtk.Label("Site filter:") - self.table.attach(self.lab_filter, 1, 2, 2, 3, xpadding = 0, ypadding = 0, yoptions=gtk.SHRINK) + self.table.attach(self.lab_filter, 1, 2, 2, 3, xpadding=0, ypadding=0, + yoptions=gtk.SHRINK) self.lab_filter.show() self.lab_filter.set_justify(gtk.JUSTIFY_RIGHT) self.lab_filter.set_alignment(1.0, 0.5) @@ -229,12 +242,14 @@ class GuiBulkImport(): print w self.cbfilter.append_text(w) self.cbfilter.set_active(0) - self.table.attach(self.cbfilter, 2, 3, 2, 3, xpadding = 10, ypadding = 1, yoptions=gtk.SHRINK) + self.table.attach(self.cbfilter, 2, 3, 2, 3, xpadding=10, ypadding=1, + yoptions=gtk.SHRINK) self.cbfilter.show() # label - drop hudcache self.lab_hdrop = gtk.Label("Drop HudCache:") - self.table.attach(self.lab_hdrop, 3, 4, 2, 3, xpadding = 0, ypadding = 0, yoptions=gtk.SHRINK) + self.table.attach(self.lab_hdrop, 3, 4, 2, 3, xpadding=0, ypadding=0, + yoptions=gtk.SHRINK) self.lab_hdrop.show() self.lab_hdrop.set_justify(gtk.JUSTIFY_RIGHT) self.lab_hdrop.set_alignment(1.0, 0.5) @@ -245,19 +260,22 @@ class GuiBulkImport(): self.cb_drophudcache.append_text("don't drop") self.cb_drophudcache.append_text('drop') self.cb_drophudcache.set_active(0) - self.table.attach(self.cb_drophudcache, 4, 5, 2, 3, xpadding = 10, ypadding = 0, yoptions=gtk.SHRINK) + self.table.attach(self.cb_drophudcache, 4, 5, 2, 3, xpadding=10, + ypadding=0, yoptions=gtk.SHRINK) self.cb_drophudcache.show() # button - Import self.load_button = gtk.Button('Import') # todo: rename variables to import too self.load_button.connect('clicked', self.load_clicked, 'Import clicked') - self.table.attach(self.load_button, 2, 3, 4, 5, xpadding = 0, ypadding = 0, yoptions=gtk.SHRINK) + self.table.attach(self.load_button, 2, 3, 4, 5, xpadding=0, ypadding=0, + yoptions=gtk.SHRINK) self.load_button.show() # label - spacer (keeps rows 3 & 5 apart) self.lab_spacer = gtk.Label() - self.table.attach(self.lab_spacer, 3, 5, 3, 4, xpadding = 0, ypadding = 0, yoptions=gtk.SHRINK) + self.table.attach(self.lab_spacer, 3, 5, 3, 4, xpadding=0, ypadding=0, + yoptions=gtk.SHRINK) self.lab_spacer.show() # label - info @@ -265,7 +283,8 @@ class GuiBulkImport(): # self.table.attach(self.lab_info, 3, 5, 4, 5, xpadding = 0, ypadding = 0, yoptions=gtk.SHRINK) # self.lab_info.show() self.progressbar = gtk.ProgressBar() - self.table.attach(self.progressbar, 3, 5, 4, 5, xpadding = 0, ypadding = 0, yoptions = gtk.SHRINK) + self.table.attach(self.progressbar, 3, 5, 4, 5, xpadding=0, ypadding=0, + yoptions=gtk.SHRINK) self.progressbar.set_text("Waiting...") self.progressbar.set_fraction(0) self.progressbar.show() From a5de7c9b6b1416bbef62aab5ae51a1c0170a97b3 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 3 Nov 2009 15:14:20 -0500 Subject: [PATCH 37/54] cleanup --- pyfpdb/HandHistoryConverter.py | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/pyfpdb/HandHistoryConverter.py b/pyfpdb/HandHistoryConverter.py index 6edb9029..bced9d93 100644 --- a/pyfpdb/HandHistoryConverter.py +++ b/pyfpdb/HandHistoryConverter.py @@ -150,9 +150,9 @@ Otherwise, finish at EOF. for handText in self.tailHands(): try: self.processHand(handText) - numHands+=1 + numHands += 1 except FpdbParseError, e: - numErrors+=1 + numErrors += 1 log.warning("Failed to convert hand %s" % e.hid) log.debug(handText) else: @@ -166,7 +166,7 @@ Otherwise, finish at EOF. try: self.processedHands.append(self.processHand(handText)) except FpdbParseError, e: - numErrors+=1 + numErrors += 1 log.warning("Failed to convert hand %s" % e.hid) log.debug(handText) numHands = len(handsList) @@ -195,7 +195,8 @@ This requires a regex that greedily groups and matches the 'splitter' between ha which it expects to find at self.re_TailSplitHands -- see for e.g. Everleaf.py. """ - if self.in_path == '-': raise StopIteration + if self.in_path == '-': + raise StopIteration interval = 1.0 # seconds to sleep between reads for new data fd = codecs.open(self.in_path,'r', self.codepage) data = '' @@ -396,7 +397,7 @@ or None if we fail to get the info """ if True: # basically.. I don't know sane = True - if(self.in_path != '-' and self.out_path == self.in_path): + if self.in_path != '-' and self.out_path == self.in_path: print "HH Sanity Check: output and input files are the same, check config" sane = False @@ -417,16 +418,19 @@ or None if we fail to get the info """ for l in list: # print "'" + l + "'" hands = hands + [Hand.Hand(self.sitename, self.gametype, l)] + # TODO: This looks like it could be replaced with a list comp.. ? return hands def __listof(self, x): - if isinstance(x, list) or isinstance(x, tuple): return x - else: return [x] + if isinstance(x, list) or isinstance(x, tuple): + return x + else: + return [x] def readFile(self): """Open in_path according to self.codepage. Exceptions caught further up""" - if(self.filetype == "text"): + if self.filetype == "text": if self.in_path == '-': # read from stdin log.debug("Reading stdin with %s" % self.codepage) # is this necessary? or possible? or what? @@ -446,7 +450,7 @@ or None if we fail to get the info """ pass else: print "unable to read file with any codec in list!", self.in_path - elif(self.filetype == "xml"): + elif self.filetype == "xml": doc = xml.dom.minidom.parse(filename) self.doc = doc @@ -474,7 +478,8 @@ or None if we fail to get the info """ def maxOccSeat(self, hand): max = 0 for player in hand.players: - if player[0] > max: max = player[0] + if player[0] > max: + max = player[0] return max def getStatus(self): From 51da6fb68788af8341956f1faa77a2c96e06bc96 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 3 Nov 2009 15:29:05 -0500 Subject: [PATCH 38/54] cleaner --- pyfpdb/fpdb_import.py | 47 +++++++++++++++++++++++-------------------- 1 file changed, 25 insertions(+), 22 deletions(-) diff --git a/pyfpdb/fpdb_import.py b/pyfpdb/fpdb_import.py index a262e62e..e43dccf5 100644 --- a/pyfpdb/fpdb_import.py +++ b/pyfpdb/fpdb_import.py @@ -182,14 +182,15 @@ class Importer: if os.path.isdir(inputPath): for subdir in os.walk(inputPath): for file in subdir[2]: - self.addImportFile(os.path.join(subdir[0], file), site=site, filter=filter) + self.addImportFile(os.path.join(subdir[0], file), site=site, + filter=filter) else: self.addImportFile(inputPath, site=site, filter=filter) #Add a directory of files to filelist #Only one import directory per site supported. #dirlist is a hash of lists: #dirlist{ 'PokerStars' => ["/path/to/import/", "filtername"] } - def addImportDirectory(self,dir,monitor = False, site = "default", filter = "passthrough"): + def addImportDirectory(self,dir,monitor=False, site="default", filter="passthrough"): #gets called by GuiAutoImport. #This should really be using os.walk #http://docs.python.org/library/os.html @@ -203,7 +204,7 @@ class Importer: #print " adding file ", file self.addImportFile(os.path.join(dir, file), site, filter) else: - log.warning("Attempted to add non-directory: '" + str(dir) + "' as an import directory") + log.warning("Attempted to add non-directory: '%s' as an import directory" % str(dir)) def runImport(self): """"Run full import on self.filelist. This is called from GuiBulkImport.py""" @@ -250,6 +251,9 @@ class Importer: #self.writeq.join() #using empty() might be more reliable: while not self.writeq.empty() and len(threading.enumerate()) > 1: + # TODO: Do we need to actually tell the progress indicator to move, or is it already moving, and we just need to process events... + while gtk.events_pending(): # see http://faq.pygtk.org/index.py?req=index for more hints (3.7) + gtk.main_iteration(False) sleep(0.5) print " ... writers finished" @@ -418,9 +422,9 @@ class Importer: obj = getattr(mod, filter_name, None) if callable(obj): hhc = obj(in_path = file, out_path = out_path, index = 0) # Index into file 0 until changeover - if(hhc.getStatus() and self.NEWIMPORT == False): + if hhc.getStatus() and self.NEWIMPORT == False: (stored, duplicates, partial, errors, ttime) = self.import_fpdb_file(db, out_path, site, q) - elif (hhc.getStatus() and self.NEWIMPORT == True): + elif hhc.getStatus() and self.NEWIMPORT == True: #This code doesn't do anything yet handlist = hhc.getProcessedHands() self.pos_in_file[file] = hhc.getLastCharacterRead() @@ -458,7 +462,7 @@ class Importer: loc = self.pos_in_file[file] #size = os.path.getsize(file) #print "loc =", loc, 'size =', size - except: + except IndexError: pass # Read input file into class and close file inputFile.seek(loc) @@ -481,14 +485,14 @@ class Importer: if not stored: if duplicates: for line_no in xrange(len(self.lines)): - if self.lines[line_no].find("Game #")!=-1: - final_game_line=self.lines[line_no] + if self.lines[line_no].find("Game #") != -1: + final_game_line = self.lines[line_no] handsId=fpdb_simple.parseSiteHandNo(final_game_line) else: print "failed to read a single hand from file:", inputFile - handsId=0 + handsId = 0 #todo: this will cause return of an unstored hand number if the last hand was error - self.handsId=handsId + self.handsId = handsId return (stored, duplicates, partial, errors, ttime) # end def import_fpdb_file @@ -508,13 +512,13 @@ class Importer: #print "DEBUG: import_fpdb_file: failed on lines[0]: '%s' '%s' '%s' '%s' " %( file, site, lines, loc) return (0,0,0,1,0,0) - if firstline.find("Tournament Summary")!=-1: + if "Tournament Summary" in firstline: print "TODO: implement importing tournament summaries" #self.faobs = readfile(inputFile) #self.parseTourneyHistory() return (0,0,0,1,0,0) - category=fpdb_simple.recogniseCategory(firstline) + category = fpdb_simple.recogniseCategory(firstline) startpos = 0 stored = 0 #counter @@ -524,24 +528,23 @@ class Importer: ttime = 0 handsId = 0 - for i in xrange (len(lines)): - if (len(lines[i])<2): #Wierd way to detect for '\r\n' or '\n' - endpos=i - hand=lines[startpos:endpos] + for i in xrange(len(lines)): + if len(lines[i]) < 2: #Wierd way to detect for '\r\n' or '\n' + endpos = i + hand = lines[startpos:endpos] - if (len(hand[0])<2): + if len(hand[0]) < 2: hand=hand[1:] - - if (len(hand)<3): + if len(hand) < 3: pass #TODO: This is ugly - we didn't actually find the start of the # hand with the outer loop so we test again... else: - isTourney=fpdb_simple.isTourney(hand[0]) + isTourney = fpdb_simple.isTourney(hand[0]) if not isTourney: hand = fpdb_simple.filterAnteBlindFold(hand) - self.hand=hand + self.hand = hand try: handsId = fpdb_parse_logic.mainParser( self.settings, self.siteIds[site] @@ -553,7 +556,7 @@ class Importer: if self.callHud: #print "call to HUD here. handsId:",handsId #pipe the Hands.id out to the HUD - print "sending hand to hud", handsId, "pipe =", self.caller.pipe_to_hud + print "fpdb_import: sending hand to hud", handsId, "pipe =", self.caller.pipe_to_hud self.caller.pipe_to_hud.stdin.write("%s" % (handsId) + os.linesep) except Exceptions.DuplicateError: duplicates += 1 From 0a563cad53ecf58ad4e4c706730312760bb5beb8 Mon Sep 17 00:00:00 2001 From: Eratosthenes Date: Tue, 3 Nov 2009 21:51:10 -0500 Subject: [PATCH 39/54] Added get_table_info method. --- pyfpdb/Database.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/pyfpdb/Database.py b/pyfpdb/Database.py index ba71310b..2cee8336 100755 --- a/pyfpdb/Database.py +++ b/pyfpdb/Database.py @@ -292,6 +292,21 @@ class Database: row = c.fetchone() return row + def get_table_info(self, hand_id): + c = self.connection.cursor() + c.execute(self.sql.query['get_table_name'], (hand_id, )) + row = c.fetchone() + l = list(row) + if row[3] == "ring": # cash game + l.append(None) + l.append(None) + return l + else: # tournament + tour_no, tab_no = re.split(" ", row[0]) + l.append(tour_no) + l.append(tab_no) + return l + def get_last_hand(self): c = self.connection.cursor() c.execute(self.sql.query['get_last_hand']) From 3265766c77fcbd59786a62c340174a1473a4e880 Mon Sep 17 00:00:00 2001 From: Eratosthenes Date: Tue, 3 Nov 2009 21:52:40 -0500 Subject: [PATCH 40/54] Cleanup of HUD_main prior to integrating newTables code. --- pyfpdb/HUD_main.py | 65 ++++++++++++++++------------------------------ 1 file changed, 23 insertions(+), 42 deletions(-) diff --git a/pyfpdb/HUD_main.py b/pyfpdb/HUD_main.py index 8ccc194e..001d0034 100755 --- a/pyfpdb/HUD_main.py +++ b/pyfpdb/HUD_main.py @@ -109,7 +109,7 @@ class HUD_main(object): self.main_window.set_title("HUD Main Window") self.main_window.show_all() - def destroy(*args): # call back for terminating the main eventloop + def destroy(self, *args): # call back for terminating the main eventloop gtk.main_quit() def kill_hud(self, event, table): @@ -190,7 +190,6 @@ class HUD_main(object): # need their own access to the database, but should open their own # if it is required. self.db_connection = Database.Database(self.config) - tourny_finder = re.compile('(\d+) (\d+)') # get hero's screen names and player ids self.hero, self.hero_ids = {}, {} @@ -207,65 +206,47 @@ class HUD_main(object): if new_hand_id == "": # blank line means quit self.destroy() break # this thread is not always killed immediately with gtk.main_quit() + # get basic info about the new hand from the db # if there is a db error, complain, skip hand, and proceed try: - (table_name, max, poker_game, type, site_id) = self.db_connection.get_table_name(new_hand_id) - - cards = self.db_connection.get_cards(new_hand_id) - comm_cards = self.db_connection.get_common_cards(new_hand_id) - if comm_cards != {}: # stud! - cards['common'] = comm_cards['common'] + (table_name, max, poker_game, type, site_id, tour_number, tab_number) = \ + self.db_connection.get_table_info(new_hand_id) except Exception, err: - err = traceback.extract_tb(sys.exc_info()[2])[-1] - print "db error: skipping "+str(new_hand_id)+" "+err[2]+"("+str(err[1])+"): "+str(sys.exc_info()[1]) - if new_hand_id: # new_hand_id is none if we had an error prior to the store - sys.stderr.write("Database error %s in hand %d. Skipping.\n" % (err, int(new_hand_id))) + print "db error: skipping %s" % new_hand_id + sys.stderr.write("Database error: could not find hand %s.\n" % new_hand_id) continue if type == "tour": # hand is from a tournament - mat_obj = tourny_finder.search(table_name) - if mat_obj: - (tour_number, tab_number) = mat_obj.group(1, 2) - temp_key = tour_number - else: # tourney, but can't get number and table - print "could not find tournament: skipping " - #sys.stderr.write("Could not find tournament %d in hand %d. Skipping.\n" % (int(tour_number), int(new_hand_id))) - continue - + temp_key = tour_number else: temp_key = table_name # Update an existing HUD if temp_key in self.hud_dict: - try: - # get stats using hud's specific params - self.db_connection.init_hud_stat_vars( self.hud_dict[temp_key].hud_params['hud_days'] - , self.hud_dict[temp_key].hud_params['h_hud_days']) - stat_dict = self.db_connection.get_stats_from_hand(new_hand_id, type, self.hud_dict[temp_key].hud_params, self.hero_ids[site_id]) - except: - err = traceback.extract_tb(sys.exc_info()[2])[-1] - print "db get_stats error: skipping "+str(new_hand_id)+" "+err[2]+"("+str(err[1])+"): "+str(sys.exc_info()[1]) - if new_hand_id: # new_hand_id is none if we had an error prior to the store - sys.stderr.write("Database get_stats error %s in hand %d. Skipping.\n" % (err, int(new_hand_id))) - continue + # get stats using hud's specific params and get cards + self.db_connection.init_hud_stat_vars( self.hud_dict[temp_key].hud_params['hud_days'] + , self.hud_dict[temp_key].hud_params['h_hud_days']) + stat_dict = self.db_connection.get_stats_from_hand(new_hand_id, type, self.hud_dict[temp_key].hud_params, self.hero_ids[site_id]) self.hud_dict[temp_key].stat_dict = stat_dict + cards = self.db_connection.get_cards(new_hand_id) + comm_cards = self.db_connection.get_common_cards(new_hand_id) + if comm_cards != {}: # stud! + cards['common'] = comm_cards['common'] self.hud_dict[temp_key].cards = cards [aw.update_data(new_hand_id, self.db_connection) for aw in self.hud_dict[temp_key].aux_windows] self.update_HUD(new_hand_id, temp_key, self.config) # Or create a new HUD else: - try: - # get stats using default params - self.db_connection.init_hud_stat_vars( self.hud_params['hud_days'], self.hud_params['h_hud_days'] ) - stat_dict = self.db_connection.get_stats_from_hand(new_hand_id, type, self.hud_params, self.hero_ids[site_id]) - except: - err = traceback.extract_tb(sys.exc_info()[2])[-1] - print "db get_stats error: skipping "+str(new_hand_id)+" "+err[2]+"("+str(err[1])+"): "+str(sys.exc_info()[1]) - if new_hand_id: # new_hand_id is none if we had an error prior to the store - sys.stderr.write("Database get_stats error %s in hand %d. Skipping.\n" % (err, int(new_hand_id))) - continue + # get stats using default params--also get cards + self.db_connection.init_hud_stat_vars( self.hud_params['hud_days'], self.hud_params['h_hud_days'] ) + stat_dict = self.db_connection.get_stats_from_hand(new_hand_id, type, self.hud_params, self.hero_ids[site_id]) + cards = self.db_connection.get_cards(new_hand_id) + comm_cards = self.db_connection.get_common_cards(new_hand_id) + if comm_cards != {}: # stud! + cards['common'] = comm_cards['common'] + if type == "tour": tablewindow = Tables.discover_tournament_table(self.config, tour_number, tab_number) else: From ab1c37ead2331f54b6cc8007af4c345be6e7f55d Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 4 Nov 2009 10:46:36 -0500 Subject: [PATCH 41/54] IndexError -> KeyError .. doh. --- pyfpdb/fpdb_import.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyfpdb/fpdb_import.py b/pyfpdb/fpdb_import.py index e43dccf5..fcad30be 100644 --- a/pyfpdb/fpdb_import.py +++ b/pyfpdb/fpdb_import.py @@ -462,7 +462,7 @@ class Importer: loc = self.pos_in_file[file] #size = os.path.getsize(file) #print "loc =", loc, 'size =', size - except IndexError: + except KeyError: pass # Read input file into class and close file inputFile.seek(loc) From c60dfda64ccc8c350c15e3eb8d0ee1c19d9b2e2c Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Wed, 4 Nov 2009 18:58:01 +0100 Subject: [PATCH 42/54] put in former logging setup again, removed excepthook --- pyfpdb/Configuration.py | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index cdbc5f8f..4bf5cccb 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -36,6 +36,14 @@ from xml.dom.minidom import Node import logging, logging.config import ConfigParser + +try: # local path + logging.config.fileConfig(os.path.join(sys.path[0],"logging.conf")) +except ConfigParser.NoSectionError: # debian package path + logging.config.fileConfig('/usr/share/python-fpdb/logging.conf') + +log = logging.getLogger("config") +log.debug("config logger initialised") ######################################################################## # application wide consts @@ -55,18 +63,6 @@ DATABASE_TYPES = ( DATABASE_TYPE_MYSQL, ) -# setup logging -logging.config.fileConfig(os.path.join(DIR_SELF,"logging.conf")) -log = logging.getLogger("config") - -# setup application wide exception handler -def excepthook(Type, value, tb): - p = traceback.format_exception(type, value, tb) - log.critical(p) - raise Type(value) - -sys.excepthook = excepthook - ######################################################################## def string_to_bool(string, default=True): """converts a string representation of a boolean value to boolean True or False From efefae4941f5cc192fd1607240c5ed1a5417a549 Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Wed, 4 Nov 2009 19:01:12 +0100 Subject: [PATCH 43/54] fix: db_type is actually db_server --- pyfpdb/DatabaseManager.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pyfpdb/DatabaseManager.py b/pyfpdb/DatabaseManager.py index 7164a6e0..1269f540 100644 --- a/pyfpdb/DatabaseManager.py +++ b/pyfpdb/DatabaseManager.py @@ -50,10 +50,10 @@ class DatabaseManager(gobject.GObject): #TODO: fpdb stores databases in no particular order. this has to be fixed somehow databases = [] for name, fpdbDatabase in config.supported_databases.items(): - databaseKlass = klass.DatabaseTypes.get(fpdbDatabase.db_type, None) + databaseKlass = klass.DatabaseTypes.get(fpdbDatabase.db_server, None) #NOTE: Config does not seem to validate user input, so anything may end up here if databaseKlass is None: - raise ValueError('Unknown databasetype: %s' % fpdbDatabase.db_type) + raise ValueError('Unknown databasetype: %s' % fpdbDatabase.db_server) database = databaseKlass() if database.Type == 'sqlite': From 5c656625fd24c31b77bcd4f5f11c287b5187b231 Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Wed, 4 Nov 2009 23:41:09 +0100 Subject: [PATCH 44/54] combed a bit over Config.get_default_font() --- pyfpdb/Configuration.py | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 4bf5cccb..489774e9 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -762,20 +762,16 @@ class Config: colors['hudfgcolor'] = self.supported_sites[site].hudfgcolor return colors - def get_default_font(self, site = 'PokerStars'): - (font, font_size) = ("Sans", "8") - if site not in self.supported_sites: - return ("Sans", "8") - if self.supported_sites[site].font == "": - font = "Sans" - else: - font = self.supported_sites[site].font - - if self.supported_sites[site].font_size == "": - font_size = "8" - else: - font_size = self.supported_sites[site].font_size - return (font, font_size) + def get_default_font(self, site='PokerStars'): + font = "Sans" + font_size = "8" + site = self.supported_sites.get(site, None) + if site is not None: + if site.font: + font = site.font + if site.font_size: + font_size = site.font_size + return font, font_size def get_locations(self, site = "PokerStars", max = "8"): From 7e8ed08a28118f7f25e0efa4d18701ea76a6020a Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Wed, 4 Nov 2009 23:58:48 +0100 Subject: [PATCH 45/54] simplified Config.get_aux_windows() --- pyfpdb/Configuration.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 489774e9..706af8e1 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -848,10 +848,7 @@ class Config: def get_aux_windows(self): """Gets the list of mucked window formats in the configuration.""" - mw = [] - for w in self.aux_windows.keys(): - mw.append(w) - return mw + return self.aux_windows.keys() def get_aux_parameters(self, name): """Gets a dict of mucked window parameters from the named mw.""" From 5a8f794057b825c76cdfa3838becac07704883dc Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Thu, 5 Nov 2009 00:11:43 +0100 Subject: [PATCH 46/54] simplified Config.get_supported_sites() --- pyfpdb/Configuration.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 706af8e1..3083ee9f 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -793,15 +793,13 @@ class Config: ( 0, 280), (121, 280), ( 46, 30) ) return locations - def get_supported_sites(self, all = False): + def get_supported_sites(self, all=False): """Returns the list of supported sites.""" - the_sites = [] - for site in self.supported_sites.keys(): - params = self.get_site_parameters(site) - if all or params['enabled']: - the_sites.append(site) - return the_sites - + if all: + return self.supported_sites.keys() + else: + return [site_name for (site_name, site) in self.supported_sites.items() if site.enabled] + def get_site_parameters(self, site): """Returns a dict of the site parameters for the specified site""" parms = {} From 7a602846ff1cfacf8cab2dd4165da591a0977c50 Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Thu, 5 Nov 2009 00:34:02 +0100 Subject: [PATCH 47/54] combed over Config.get_tv_parameters() there was a bit much of unconditional exception handling note: some parts of the application call Config.get_tv_parameters() but afaics the actual parameters are never used anywhere. so maybe its leftover code. someone drop a note if or not to remove tv related stuff --- pyfpdb/Configuration.py | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 3083ee9f..3f9b9e8a 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -328,9 +328,9 @@ class HudUI: class Tv: def __init__(self, node): - self.combinedStealFold = node.getAttribute("combinedStealFold") - self.combined2B3B = node.getAttribute("combined2B3B") - self.combinedPostflop = node.getAttribute("combinedPostflop") + self.combinedStealFold = string_to_bool(node.getAttribute("combinedStealFold"), default=True) + self.combined2B3B = string_to_bool(node.getAttribute("combined2B3B"), default=True) + self.combinedPostflop = string_to_bool(node.getAttribute("combinedPostflop"), default=True) def __str__(self): return (" combinedStealFold = %s\n combined2B3B = %s\n combinedPostflop = %s\n" % @@ -392,6 +392,8 @@ class Config: self.hhcs = {} self.popup_windows = {} self.db_selected = None # database the user would like to use + self.tv = None + # s_sites = doc.getElementsByTagName("supported_sites") for site_node in doc.getElementsByTagName("site"): @@ -448,8 +450,7 @@ class Config: self.ui = hui for tv_node in doc.getElementsByTagName("tv"): - tv = Tv(node = tv_node) - self.tv = tv + self.tv = Tv(node = tv_node) db = self.get_db_parameters() if db['db-password'] == 'YOUR MYSQL PASSWORD': @@ -655,16 +656,13 @@ class Config: return None def get_tv_parameters(self): - tv = {} - try: tv['combinedStealFold'] = self.tv.combinedStealFold - except: tv['combinedStealFold'] = True - - try: tv['combined2B3B'] = self.tv.combined2B3B - except: tv['combined2B3B'] = True - - try: tv['combinedPostflop'] = self.tv.combinedPostflop - except: tv['combinedPostflop'] = True - return tv + if self.tv is not None: + return { + 'combinedStealFold': self.tv.combinedStealFold, + 'combined2B3B': self.tv.combined2B3B, + 'combinedPostflop': self.tv.combinedPostflop + } + return {} # Allow to change the menu appearance def get_hud_ui_parameters(self): From 14200c5a504edf0915a62707eec6ad9cfad5889e Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Thu, 5 Nov 2009 00:39:42 +0100 Subject: [PATCH 48/54] simplified code a bit --- pyfpdb/Configuration.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 3f9b9e8a..736d6761 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -561,15 +561,13 @@ class Config: if int( location_node.getAttribute("seat") ) == int( seat ): return location_node - def save(self, file = None): - if file != None: - with open(file, 'w') as f: - self.doc.writexml(f) - else: + def save(self, file=None): + if file is None: + file = self.file shutil.move(self.file, self.file+".backup") - with open(self.file, 'w') as f: - self.doc.writexml(f) - + with open(file, 'w') as f: + self.doc.writexml(f) + def edit_layout(self, site_name, max, width = None, height = None, fav_seat = None, locations = None): site_node = self.get_site_node(site_name) From 2199d165f1026488985d6ef242ef23705d6230cf Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Thu, 5 Nov 2009 01:21:32 +0100 Subject: [PATCH 49/54] removed unconditional exception handling + kwarg max should be int --- pyfpdb/Configuration.py | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py index 736d6761..0f80a9db 100755 --- a/pyfpdb/Configuration.py +++ b/pyfpdb/Configuration.py @@ -769,16 +769,18 @@ class Config: font_size = site.font_size return font, font_size - def get_locations(self, site = "PokerStars", max = "8"): - - try: - locations = self.supported_sites[site].layout[max].location - except: - locations = ( ( 0, 0), (684, 61), (689, 239), (692, 346), - (586, 393), (421, 440), (267, 440), ( 0, 361), - ( 0, 280), (121, 280), ( 46, 30) ) - return locations - + def get_locations(self, site_name="PokerStars", max=8): + site = self.supported_sites.get(site_name, None) + if site is not None: + location = site.layout.get(max, None) + if location is not None: + return location.location + return ( + ( 0, 0), (684, 61), (689, 239), (692, 346), + (586, 393), (421, 440), (267, 440), ( 0, 361), + ( 0, 280), (121, 280), ( 46, 30) + ) + def get_aux_locations(self, aux = "mucked", max = "9"): try: From 4a6213e32e4f7fa680f771030ce11c41d86692c4 Mon Sep 17 00:00:00 2001 From: fpdb-mme Date: Thu, 5 Nov 2009 01:26:32 +0100 Subject: [PATCH 50/54] now sample code it works as expected grrr, soewhere down the line the exception got swallowed. this is evil!!! -x must die --- pyfpdb/HUD_run_me.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pyfpdb/HUD_run_me.py b/pyfpdb/HUD_run_me.py index 53e79d42..00819322 100755 --- a/pyfpdb/HUD_run_me.py +++ b/pyfpdb/HUD_run_me.py @@ -37,7 +37,8 @@ if __name__== "__main__": HUD_main.config = Configuration.Config() gobject.threads_init() # this is required - thread.start_new_thread(HUD_main.read_stdin, ()) # starts the thread + hud = HUD_main.HUD_main() + thread.start_new_thread(hud.read_stdin, ()) # starts the thread HUD_main.main_window = gtk.Window() HUD_main.main_window.connect("destroy", destroy) From 5aef7b60549b01c8189a5195ef24ba168183e7c3 Mon Sep 17 00:00:00 2001 From: Worros Date: Fri, 6 Nov 2009 18:39:59 +0800 Subject: [PATCH 51/54] [NEWIMPORT] Insert winnings column into HandsPlayers --- pyfpdb/Database.py | 5 +++-- pyfpdb/DerivedStats.py | 22 +++++++++++++++++++--- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/pyfpdb/Database.py b/pyfpdb/Database.py index 61b91729..38bd04cc 100755 --- a/pyfpdb/Database.py +++ b/pyfpdb/Database.py @@ -1393,6 +1393,7 @@ class Database: pids[p], pdata[p]['startCash'], pdata[p]['seatNo'], + pdata[p]['winnings'], pdata[p]['street0Aggr'], pdata[p]['street1Aggr'], pdata[p]['street2Aggr'], @@ -1405,6 +1406,7 @@ class Database: playerId, startCash, seatNo, + winnings, street0Aggr, street1Aggr, street2Aggr, @@ -1413,7 +1415,7 @@ class Database: ) VALUES ( %s, %s, %s, %s, %s, - %s, %s, %s, %s + %s, %s, %s, %s, %s )""" # position, @@ -1423,7 +1425,6 @@ class Database: # card3, # card4, # startCards, -# winnings, # rake, # totalProfit, # street0VPI, diff --git a/pyfpdb/DerivedStats.py b/pyfpdb/DerivedStats.py index 56b0d489..86aa92fb 100644 --- a/pyfpdb/DerivedStats.py +++ b/pyfpdb/DerivedStats.py @@ -18,6 +18,13 @@ #fpdb modules import Card +DEBUG = True + +if DEBUG: + import pprint + pp = pprint.PrettyPrinter(indent=4) + + class DerivedStats(): def __init__(self, hand): self.hand = hand @@ -30,13 +37,17 @@ class DerivedStats(): for player in hand.players: self.handsplayers[player[1]] = {} #Init vars that may not be used, but still need to be inserted. + self.handsplayers[player[1]]['winnings'] = 0 self.handsplayers[player[1]]['street4Aggr'] = False self.assembleHands(self.hand) self.assembleHandsPlayers(self.hand) - - print "hands =", self.hands - print "handsplayers =", self.handsplayers + + if DEBUG: + print "Hands:" + pp.pprint(self.hands) + print "HandsPlayers:" + pp.pprint(self.handsplayers) def getHands(self): return self.hands @@ -90,6 +101,11 @@ class DerivedStats(): self.handsplayers[player[1]]['seatNo'] = player[0] self.handsplayers[player[1]]['startCash'] = player[2] + # Winnings is a non-negative value of money collected from the pot, which already includes the + # rake taken out. hand.collectees is Decimal, database requires cents + for player in hand.collectees: + self.handsplayers[player]['winnings'] = int(100 * hand.collectees[player]) + for i, street in enumerate(hand.actionStreets[1:]): self.aggr(self.hand, i) From 006d7164eaaf567d151356062b3b54326cf20862 Mon Sep 17 00:00:00 2001 From: Worros Date: Fri, 6 Nov 2009 19:13:52 +0800 Subject: [PATCH 52/54] [NEWIMPORT] Insert streetXSeen col into HandsPlayers --- pyfpdb/Database.py | 13 +++++++++---- pyfpdb/DerivedStats.py | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/pyfpdb/Database.py b/pyfpdb/Database.py index 38bd04cc..8a1060a6 100755 --- a/pyfpdb/Database.py +++ b/pyfpdb/Database.py @@ -1394,6 +1394,10 @@ class Database: pdata[p]['startCash'], pdata[p]['seatNo'], pdata[p]['winnings'], + pdata[p]['street1Seen'], + pdata[p]['street2Seen'], + pdata[p]['street3Seen'], + pdata[p]['street4Seen'], pdata[p]['street0Aggr'], pdata[p]['street1Aggr'], pdata[p]['street2Aggr'], @@ -1407,6 +1411,10 @@ class Database: startCash, seatNo, winnings, + street1Seen, + street2Seen, + street3Seen, + street4Seen, street0Aggr, street1Aggr, street2Aggr, @@ -1414,6 +1422,7 @@ class Database: street4Aggr ) VALUES ( + %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s )""" @@ -1430,10 +1439,6 @@ class Database: # street0VPI, # street0_3BChance, # street0_3BDone, -# street1Seen, -# street2Seen, -# street3Seen, -# street4Seen, # sawShowdown, # otherRaisedStreet1, # otherRaisedStreet2, diff --git a/pyfpdb/DerivedStats.py b/pyfpdb/DerivedStats.py index 86aa92fb..1e23e600 100644 --- a/pyfpdb/DerivedStats.py +++ b/pyfpdb/DerivedStats.py @@ -37,7 +37,9 @@ class DerivedStats(): for player in hand.players: self.handsplayers[player[1]] = {} #Init vars that may not be used, but still need to be inserted. + # All stud street4 need this when importing holdem self.handsplayers[player[1]]['winnings'] = 0 + self.handsplayers[player[1]]['street4Seen'] = False self.handsplayers[player[1]]['street4Aggr'] = False self.assembleHands(self.hand) @@ -106,6 +108,9 @@ class DerivedStats(): for player in hand.collectees: self.handsplayers[player]['winnings'] = int(100 * hand.collectees[player]) + for i, street in enumerate(hand.actionStreets[2:]): + self.seen(self.hand, i+2) + for i, street in enumerate(hand.actionStreets[1:]): self.aggr(self.hand, i) @@ -849,6 +854,17 @@ class DerivedStats(): self.hands['street3Raises'] = 0 # /* num big bets paid to see sd/street7 */ self.hands['street4Raises'] = 0 # /* num big bets paid to see showdown */ + def seen(self, hand, i): + pas = set() + for act in hand.actions[hand.actionStreets[i]]: + pas.add(act[0]) + + for player in hand.players: + if player[1] in pas: + self.handsplayers[player[1]]['street%sSeen' % i] = True + else: + self.handsplayers[player[1]]['street%sSeen' % i] = False + def aggr(self, hand, i): aggrers = set() for act in hand.actions[hand.actionStreets[i]]: From 5c7cce090e2beb3968c46e4d59241932d3705af8 Mon Sep 17 00:00:00 2001 From: Worros Date: Fri, 6 Nov 2009 19:30:50 +0800 Subject: [PATCH 53/54] [NEWIMPORT] Added street0VPI to HandsPlayers Also fixed last patch for streetXSeen --- pyfpdb/Database.py | 5 +++-- pyfpdb/DerivedStats.py | 9 +++++---- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/pyfpdb/Database.py b/pyfpdb/Database.py index 8a1060a6..f7e873bc 100755 --- a/pyfpdb/Database.py +++ b/pyfpdb/Database.py @@ -1394,6 +1394,7 @@ class Database: pdata[p]['startCash'], pdata[p]['seatNo'], pdata[p]['winnings'], + pdata[p]['street0VPI'], pdata[p]['street1Seen'], pdata[p]['street2Seen'], pdata[p]['street3Seen'], @@ -1411,6 +1412,7 @@ class Database: startCash, seatNo, winnings, + street0VPI, street1Seen, street2Seen, street3Seen, @@ -1422,7 +1424,7 @@ class Database: street4Aggr ) VALUES ( - %s, %s, %s, %s, + %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s )""" @@ -1436,7 +1438,6 @@ class Database: # startCards, # rake, # totalProfit, -# street0VPI, # street0_3BChance, # street0_3BDone, # sawShowdown, diff --git a/pyfpdb/DerivedStats.py b/pyfpdb/DerivedStats.py index 1e23e600..4b48f618 100644 --- a/pyfpdb/DerivedStats.py +++ b/pyfpdb/DerivedStats.py @@ -98,6 +98,7 @@ class DerivedStats(): # commentTs DATETIME def assembleHandsPlayers(self, hand): + #street0VPI/vpip already called in Hand #hand.players = [[seat, name, chips],[seat, name, chips]] for player in hand.players: self.handsplayers[player[1]]['seatNo'] = player[0] @@ -109,7 +110,7 @@ class DerivedStats(): self.handsplayers[player]['winnings'] = int(100 * hand.collectees[player]) for i, street in enumerate(hand.actionStreets[2:]): - self.seen(self.hand, i+2) + self.seen(self.hand, i+1) for i, street in enumerate(hand.actionStreets[1:]): self.aggr(self.hand, i) @@ -815,9 +816,9 @@ class DerivedStats(): for player in hand.players: if player[1] in vpipers: - self.handsplayers[player[1]]['vpip'] = True + self.handsplayers[player[1]]['street0VPI'] = True else: - self.handsplayers[player[1]]['vpip'] = False + self.handsplayers[player[1]]['street0VPI'] = False def playersAtStreetX(self, hand): """ playersAtStreet1 SMALLINT NOT NULL, /* num of players seeing flop/street4/draw1 */""" @@ -856,7 +857,7 @@ class DerivedStats(): def seen(self, hand, i): pas = set() - for act in hand.actions[hand.actionStreets[i]]: + for act in hand.actions[hand.actionStreets[i+1]]: pas.add(act[0]) for player in hand.players: From 15ea852d76c6a73c11c26b9a01163c7de343b69d Mon Sep 17 00:00:00 2001 From: Worros Date: Sat, 7 Nov 2009 10:17:28 +0800 Subject: [PATCH 54/54] Extend the tablename field in sql to 22 characters --- pyfpdb/SQL.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pyfpdb/SQL.py b/pyfpdb/SQL.py index 84b4e9bd..3522b890 100644 --- a/pyfpdb/SQL.py +++ b/pyfpdb/SQL.py @@ -212,7 +212,7 @@ class Sql: if db_server == 'mysql': self.query['createHandsTable'] = """CREATE TABLE Hands ( id BIGINT UNSIGNED AUTO_INCREMENT NOT NULL, PRIMARY KEY (id), - tableName VARCHAR(20) NOT NULL, + tableName VARCHAR(22) NOT NULL, siteHandNo BIGINT NOT NULL, gametypeId SMALLINT UNSIGNED NOT NULL, FOREIGN KEY (gametypeId) REFERENCES Gametypes(id), handStart DATETIME NOT NULL, @@ -247,7 +247,7 @@ class Sql: elif db_server == 'postgresql': self.query['createHandsTable'] = """CREATE TABLE Hands ( id BIGSERIAL, PRIMARY KEY (id), - tableName VARCHAR(20) NOT NULL, + tableName VARCHAR(22) NOT NULL, siteHandNo BIGINT NOT NULL, gametypeId INT NOT NULL, FOREIGN KEY (gametypeId) REFERENCES Gametypes(id), handStart timestamp without time zone NOT NULL, @@ -281,7 +281,7 @@ class Sql: elif db_server == 'sqlite': self.query['createHandsTable'] = """CREATE TABLE Hands ( id INTEGER PRIMARY KEY, - tableName TEXT(20) NOT NULL, + tableName TEXT(22) NOT NULL, siteHandNo INT NOT NULL, gametypeId INT NOT NULL, handStart REAL NOT NULL,