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

This commit is contained in:
Worros 2008-12-09 23:50:35 +09:00
commit f607b3ff63
15 changed files with 2619 additions and 2376 deletions

0
pyfpdb/CliFpdb.py Executable file → Normal file
View File

0
pyfpdb/Configuration.py Executable file → Normal file
View File

View File

@ -699,7 +699,6 @@ class FpdbSQLQueries:
,round(100*sum(street2Aggr)/sum(street2Seen)) AS TuAFq ,round(100*sum(street2Aggr)/sum(street2Seen)) AS TuAFq
,round(100*sum(street3Aggr)/sum(street3Seen)) AS RvAFq ,round(100*sum(street3Aggr)/sum(street3Seen)) AS RvAFq
,round(100*(sum(street1Aggr)+sum(street2Aggr)+sum(street3Aggr)) ,round(100*(sum(street1Aggr)+sum(street2Aggr)+sum(street3Aggr))
/(sum(street1Seen)+sum(street2Seen)+sum(street3Seen))) AS PFAFq /(sum(street1Seen)+sum(street2Seen)+sum(street3Seen))) AS PFAFq
from Gametypes gt from Gametypes gt
inner join Sites s on s.Id = gt.siteId inner join Sites s on s.Id = gt.siteId

View File

@ -321,4 +321,3 @@ class GuiGraphViewer (threading.Thread):
self.leftPanelBox.show() self.leftPanelBox.show()
self.graphBox.show() self.graphBox.show()

1
pyfpdb/HUD_main.py Executable file → Normal file
View File

@ -169,4 +169,3 @@ if __name__== "__main__":
main_window.show_all() main_window.show_all()
gtk.main() gtk.main()

View File

@ -229,12 +229,11 @@ class Sql:
sum(street3CheckCallRaiseDone) AS ccr_3, sum(street3CheckCallRaiseDone) AS ccr_3,
sum(street4CheckCallRaiseChance) AS ccr_opp_4, sum(street4CheckCallRaiseChance) AS ccr_opp_4,
sum(street4CheckCallRaiseDone) AS ccr_4 sum(street4CheckCallRaiseDone) AS ccr_4
FROM HudCache, Hands FROM Hands
WHERE HudCache.PlayerId in INNER JOIN HandsPlayers ON (HandsPlayers.handId = %s)
(SELECT PlayerId FROM HandsPlayers INNER JOIN HudCache ON ( HudCache.PlayerId = HandsPlayers.PlayerId+0
WHERE handId = %s) AND HudCache.gametypeId+0 = Hands.gametypeId+0)
AND Hands.id = %s WHERE Hands.id = %s
AND Hands.gametypeId = HudCache.gametypeId
GROUP BY HudCache.PlayerId GROUP BY HudCache.PlayerId
""" """

View File

@ -71,6 +71,7 @@ def do_stat(stat_dict, player = 24, stat = 'vpip'):
# functions that return individual stats # functions that return individual stats
def playername(stat_dict, player): def playername(stat_dict, player):
""" Player Name."""
return (stat_dict[player]['screen_name'], return (stat_dict[player]['screen_name'],
stat_dict[player]['screen_name'], stat_dict[player]['screen_name'],
stat_dict[player]['screen_name'], stat_dict[player]['screen_name'],
@ -98,6 +99,26 @@ def vpip(stat_dict, player):
'Voluntarily Put In Pot %' 'Voluntarily Put In Pot %'
) )
def vpip_0(stat_dict, player):
""" Voluntarily put $ in the pot (no decimals)."""
stat = 0.0
try:
stat = float(stat_dict[player]['vpip'])/float(stat_dict[player]['n'])
return (stat,
'%2.0f' % (100*stat) + '%',
'v=%2.0f' % (100*stat) + '%',
'vpip=%2.0f' % (100*stat) + '%',
'(%d/%d)' % (stat_dict[player]['vpip'], stat_dict[player]['n']),
'vpip'
)
except: return (stat,
'%2.0f' % (0) + '%',
'w=%2.0f' % (0) + '%',
'wtsd=%2.0f' % (0) + '%',
'(%d/%d)' % (0, 0),
'wtsd'
)
def pfr(stat_dict, player): def pfr(stat_dict, player):
""" Preflop (3rd street) raise.""" """ Preflop (3rd street) raise."""
stat = 0.0 stat = 0.0
@ -119,6 +140,27 @@ def pfr(stat_dict, player):
'Pre-Flop Raise %' 'Pre-Flop Raise %'
) )
def pfr_0(stat_dict, player):
""" Preflop (3rd street) raise (no decimals)."""
stat = 0.0
try:
stat = float(stat_dict[player]['pfr'])/float(stat_dict[player]['n'])
return (stat,
'%2.0f' % (100*stat) + '%',
'p=%2.0f' % (100*stat) + '%',
'pfr=%2.0f' % (100*stat) + '%',
'(%d/%d)' % (stat_dict[player]['pfr'], stat_dict[player]['n']),
'pfr'
)
except:
return (stat,
'%2.0f' % (0) + '%',
'p=%2.0f' % (0) + '%',
'pfr=%2.0f' % (0) + '%',
'(%d/%d)' % (0, 0),
'pfr'
)
def wtsd(stat_dict, player): def wtsd(stat_dict, player):
""" Went to SD when saw flop/4th.""" """ Went to SD when saw flop/4th."""
stat = 0.0 stat = 0.0
@ -149,7 +191,7 @@ def wmsd(stat_dict, player):
'%3.1f' % (100*stat) + '%', '%3.1f' % (100*stat) + '%',
'w=%3.1f' % (100*stat) + '%', 'w=%3.1f' % (100*stat) + '%',
'wmsd=%3.1f' % (100*stat) + '%', 'wmsd=%3.1f' % (100*stat) + '%',
'(%f5.0/%d)' % (stat_dict[player]['wmsd'], stat_dict[player]['sd']), '(%5.1f/%d)' % (float(stat_dict[player]['wmsd']), stat_dict[player]['sd']),
'% won money at showdown' '% won money at showdown'
) )
except: except:
@ -413,6 +455,61 @@ def a_freq_4(stat_dict, player):
'Aggression Freq 7th' 'Aggression Freq 7th'
) )
def a_freq_123(stat_dict, player):
""" Post-Flop aggression frequency."""
stat = 0.0
try:
stat = float( stat_dict[player]['aggr_1'] + stat_dict[player]['aggr_2'] + stat_dict[player]['aggr_3']
) / float( stat_dict[player]['saw_1'] + stat_dict[player]['saw_2'] + stat_dict[player]['saw_3']);
return (stat,
'%3.1f' % (100*stat) + '%',
'afq=%3.1f' % (100*stat) + '%',
'postf_aggfq=%3.1f' % (100*stat) + '%',
'(%d/%d)' % ( stat_dict[player]['aggr_1']
+ stat_dict[player]['aggr_2']
+ stat_dict[player]['aggr_3']
, stat_dict[player]['saw_1']
+ stat_dict[player]['saw_2']
+ stat_dict[player]['saw_3']
),
'Post-Flop Aggression Freq'
)
except:
return (stat,
'%2.0f' % (0) + '%',
'a3=%2.0f' % (0) + '%',
'a_fq_3=%2.0f' % (0) + '%',
'(%d/%d)' % (0, 0),
'Post-Flop Aggression Freq'
)
def a_freq_123_0(stat_dict, player):
""" Post-Flop aggression frequency (no decimals)."""
stat = 0.0
try:
stat = float( stat_dict[player]['aggr_1'] + stat_dict[player]['aggr_2'] + stat_dict[player]['aggr_3']) / float( stat_dict[player]['saw_1'] + stat_dict[player]['saw_2'] + stat_dict[player]['saw_3']);
return (stat,
'%2.0f' % (100*stat) + '%',
'afq=%2.0f' % (100*stat) + '%',
'postf_aggfq=%2.0f' % (100*stat) + '%',
'(%d/%d)' % ( stat_dict[player]['aggr_1']
+ stat_dict[player]['aggr_2']
+ stat_dict[player]['aggr_3']
, stat_dict[player]['saw_1']
+ stat_dict[player]['saw_2']
+ stat_dict[player]['saw_3']
),
'Post-Flop Aggression Freq'
)
except:
return (stat,
'%2.0f' % (0) + '%',
'a3=%2.0f' % (0) + '%',
'a_fq_3=%2.0f' % (0) + '%',
'(%d/%d)' % (0, 0),
'Post-Flop Aggression Freq'
)
def cb_1(stat_dict, player): def cb_1(stat_dict, player):
""" Flop continuation bet.""" """ Flop continuation bet."""
stat = 0.0 stat = 0.0
@ -589,7 +686,9 @@ if __name__== "__main__":
for player in stat_dict.keys(): for player in stat_dict.keys():
print "player = ", player, do_stat(stat_dict, player = player, stat = 'vpip') print "player = ", player, do_stat(stat_dict, player = player, stat = 'vpip')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'vpip_0')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'pfr') print "player = ", player, do_stat(stat_dict, player = player, stat = 'pfr')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'pfr_0')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'wtsd') print "player = ", player, do_stat(stat_dict, player = player, stat = 'wtsd')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'saw_f') print "player = ", player, do_stat(stat_dict, player = player, stat = 'saw_f')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'n') print "player = ", player, do_stat(stat_dict, player = player, stat = 'n')
@ -604,6 +703,8 @@ if __name__== "__main__":
print "player = ", player, do_stat(stat_dict, player = player, stat = 'a_freq_2') print "player = ", player, do_stat(stat_dict, player = player, stat = 'a_freq_2')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'a_freq_3') print "player = ", player, do_stat(stat_dict, player = player, stat = 'a_freq_3')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'a_freq_4') print "player = ", player, do_stat(stat_dict, player = player, stat = 'a_freq_4')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'a_freq_123')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'a_freq_123_0')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'cb_1') print "player = ", player, do_stat(stat_dict, player = player, stat = 'cb_1')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'cb_2') print "player = ", player, do_stat(stat_dict, player = player, stat = 'cb_2')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'cb_3') print "player = ", player, do_stat(stat_dict, player = player, stat = 'cb_3')
@ -612,6 +713,7 @@ if __name__== "__main__":
print "player = ", player, do_stat(stat_dict, player = player, stat = 'ffreq_2') print "player = ", player, do_stat(stat_dict, player = player, stat = 'ffreq_2')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'ffreq_3') print "player = ", player, do_stat(stat_dict, player = player, stat = 'ffreq_3')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'ffreq_4') print "player = ", player, do_stat(stat_dict, player = player, stat = 'ffreq_4')
print "\n"
print "\n\nLegal stats:" print "\n\nLegal stats:"
for attr in dir(): for attr in dir():
@ -619,8 +721,8 @@ if __name__== "__main__":
if attr in ("Configuration", "Database", "GInitiallyUnowned", "gtk", "pygtk", if attr in ("Configuration", "Database", "GInitiallyUnowned", "gtk", "pygtk",
"player", "c", "db_connection", "do_stat", "do_tip", "stat_dict", "player", "c", "db_connection", "do_stat", "do_tip", "stat_dict",
"h"): continue "h"): continue
print attr, eval("%s.__doc__" % (attr)) print "%-14s %s" % (attr, eval("%s.__doc__" % (attr)))
# print " <pu_stat pu_stat_name = \"%s\"> </pu_stat>" % (attr) # print " <pu_stat pu_stat_name = \"%s\"> </pu_stat>" % (attr)
db_connection.close db_connection.close_connection

0
pyfpdb/fpdb.py Executable file → Normal file
View File

3
pyfpdb/fpdb_db.py Executable file → Normal file
View File

@ -48,7 +48,8 @@ class fpdb_db:
import psycopg2 import psycopg2
# If DB connection is made over TCP, then the variables # If DB connection is made over TCP, then the variables
# host, user and password are required # host, user and password are required
if self.host or self.user: print "host=%s user=%s pass=%s." % (host, user, password)
if self.host and self.user and self.password:
self.db = psycopg2.connect(host = host, self.db = psycopg2.connect(host = host,
user = user, user = user,
password = password, password = password,

7
pyfpdb/fpdb_import.py Executable file → Normal file
View File

@ -75,8 +75,8 @@ class Importer:
if not pgsqlLibFound: if not pgsqlLibFound:
raise fpdb_simple.FpdbError("interface library psycopg2 not found but PostgreSQL selected as backend - please install the library or change the config file") raise fpdb_simple.FpdbError("interface library psycopg2 not found but PostgreSQL selected as backend - please install the library or change the config file")
print self.settings print self.settings
if not self.settings.has_key('db-host') or \ if self.settings.has_key('db-host') and \
not self.settings.has_key('db-user'): self.settings.has_key('db-user'):
self.db = psycopg2.connect(host = self.settings['db-host'], self.db = psycopg2.connect(host = self.settings['db-host'],
user = self.settings['db-user'], user = self.settings['db-user'],
password = self.settings['db-password'], password = self.settings['db-password'],
@ -243,7 +243,8 @@ class Importer:
self.hand=hand self.hand=hand
try: try:
handsId=fpdb_parse_logic.mainParser(self.db, self.cursor, site, category, hand) handsId=fpdb_parse_logic.mainParser(self.settings['db-backend'], self.db
,self.cursor, site, category, hand)
self.db.commit() self.db.commit()
stored+=1 stored+=1

View File

@ -21,7 +21,7 @@ import fpdb_simple
import fpdb_save_to_db import fpdb_save_to_db
#parses a holdem hand #parses a holdem hand
def mainParser(db, cursor, site, category, hand): def mainParser(backend, db, cursor, site, category, hand):
if (category=="holdem" or category=="omahahi" or category=="omahahilo"): if (category=="holdem" or category=="omahahi" or category=="omahahilo"):
base="hold" base="hold"
else: else:
@ -48,7 +48,7 @@ def mainParser(db, cursor, site, category, hand):
#print "found small blind line:",smallBlindLine #print "found small blind line:",smallBlindLine
break break
#print "small blind line:",smallBlindLine #print "small blind line:",smallBlindLine
gametypeID=fpdb_simple.recogniseGametypeID(cursor, hand[0], hand[smallBlindLine], siteID, category, isTourney) gametypeID=fpdb_simple.recogniseGametypeID(backend, db, cursor, hand[0], hand[smallBlindLine], siteID, category, isTourney)
if isTourney: if isTourney:
if site!="ps": if site!="ps":
raise fpdb_simple.FpdbError("tourneys are only supported on PS right now") raise fpdb_simple.FpdbError("tourneys are only supported on PS right now")
@ -133,9 +133,13 @@ def mainParser(db, cursor, site, category, hand):
totalWinnings+=winnings[i] totalWinnings+=winnings[i]
if base=="hold": if base=="hold":
hudImportData=fpdb_simple.generateHudCacheData(playerIDs, base, category, actionTypes, allIns, actionTypeByNo, winnings, totalWinnings, positions) hudImportData=fpdb_simple.generateHudCacheData(playerIDs, base, category, actionTypes
, allIns, actionTypeByNo, winnings, totalWinnings, positions
, actionTypes, actionAmounts)
else: else:
hudImportData=fpdb_simple.generateHudCacheData(playerIDs, base, category, actionTypes, allIns, actionTypeByNo, winnings, totalWinnings, None) hudImportData=fpdb_simple.generateHudCacheData(playerIDs, base, category, actionTypes
, allIns, actionTypeByNo, winnings, totalWinnings, None
, actionTypes, actionAmounts)
if isTourney: if isTourney:
ranks=[] ranks=[]
@ -144,20 +148,41 @@ def mainParser(db, cursor, site, category, hand):
payin_amounts=fpdb_simple.calcPayin(len(names), buyin, fee) payin_amounts=fpdb_simple.calcPayin(len(names), buyin, fee)
if base=="hold": if base=="hold":
result = fpdb_save_to_db.tourney_holdem_omaha(cursor, base, category, siteTourneyNo, buyin, fee, knockout, entries, prizepool, tourneyStartTime, payin_amounts, ranks, tourneyTypeId, siteID, result = fpdb_save_to_db.tourney_holdem_omaha(
siteHandNo, gametypeID, handStartTime, names, playerIDs, startCashes, positions, cardValues, cardSuits, boardValues, boardSuits, winnings, rakes, actionTypes, allIns, actionAmounts, actionNos, hudImportData, maxSeats, tableName, seatNos) backend, db, cursor, base, category, siteTourneyNo, buyin
, fee, knockout, entries, prizepool, tourneyStartTime
, payin_amounts, ranks, tourneyTypeId, siteID, siteHandNo
, gametypeID, handStartTime, names, playerIDs, startCashes
, positions, cardValues, cardSuits, boardValues, boardSuits
, winnings, rakes, actionTypes, allIns, actionAmounts
, actionNos, hudImportData, maxSeats, tableName, seatNos)
elif base=="stud": elif base=="stud":
result = fpdb_save_to_db.tourney_stud(cursor, base, category, siteTourneyNo, buyin, fee, knockout, entries, prizepool, tourneyStartTime, payin_amounts, ranks, tourneyTypeId, siteID, result = fpdb_save_to_db.tourney_stud(
siteHandNo, gametypeID, handStartTime, names, playerIDs, startCashes, antes, cardValues, cardSuits, winnings, rakes, actionTypes, allIns, actionAmounts, actionNos, hudImportData, maxSeats, tableName, seatNos) backend, db, cursor, base, category, siteTourneyNo
, buyin, fee, knockout, entries, prizepool, tourneyStartTime
, payin_amounts, ranks, tourneyTypeId, siteID, siteHandNo
, gametypeID, handStartTime, names, playerIDs, startCashes
, antes, cardValues, cardSuits, winnings, rakes, actionTypes
, allIns, actionAmounts, actionNos, hudImportData, maxSeats
, tableName, seatNos)
else: else:
raise fpdb_simple.FpdbError ("unrecognised category") raise fpdb_simple.FpdbError ("unrecognised category")
else: else:
if base=="hold": if base=="hold":
result = fpdb_save_to_db.ring_holdem_omaha(cursor, base, category, siteHandNo, gametypeID, handStartTime, names, playerIDs, startCashes, positions, cardValues, cardSuits, boardValues, boardSuits, winnings, rakes, actionTypes, allIns, actionAmounts, actionNos, hudImportData, maxSeats, tableName, seatNos) result = fpdb_save_to_db.ring_holdem_omaha(
backend, db, cursor, base, category, siteHandNo
, gametypeID, handStartTime, names, playerIDs
, startCashes, positions, cardValues, cardSuits
, boardValues, boardSuits, winnings, rakes
, actionTypes, allIns, actionAmounts, actionNos
, hudImportData, maxSeats, tableName, seatNos)
elif base=="stud": elif base=="stud":
result = fpdb_save_to_db.ring_stud(cursor, base, category, siteHandNo, gametypeID, result = fpdb_save_to_db.ring_stud(
handStartTime, names, playerIDs, startCashes, antes, cardValues, backend, db, cursor, base, category, siteHandNo, gametypeID
cardSuits, winnings, rakes, actionTypes, allIns, actionAmounts, actionNos, hudImportData, maxSeats, tableName, seatNos) , handStartTime, names, playerIDs, startCashes, antes
, cardValues, cardSuits, winnings, rakes, actionTypes, allIns
, actionAmounts, actionNos, hudImportData, maxSeats, tableName
, seatNos)
else: else:
raise fpdb_simple.FpdbError ("unrecognised category") raise fpdb_simple.FpdbError ("unrecognised category")
db.commit() db.commit()

View File

@ -18,43 +18,68 @@
#This file contains methods to store hands into the db. decides to move this #This file contains methods to store hands into the db. decides to move this
#into a seperate file since its ugly, fairly long and just generally in the way. #into a seperate file since its ugly, fairly long and just generally in the way.
from time import time
import fpdb_simple import fpdb_simple
#stores a stud/razz hand into the database #stores a stud/razz hand into the database
def ring_stud(cursor, base, category, site_hand_no, gametype_id, hand_start_time, names, player_ids, start_cashes, antes, card_values, card_suits, winnings, rakes, action_types, allIns, action_amounts, actionNos, hudImportData, maxSeats, tableName, seatNos): def ring_stud(backend, db, cursor, base, category, site_hand_no, gametype_id, hand_start_time
,names, player_ids, start_cashes, antes, card_values, card_suits, winnings, rakes
,action_types, allIns, action_amounts, actionNos, hudImportData, maxSeats, tableName
,seatNos):
fpdb_simple.fillCardArrays(len(names), base, category, card_values, card_suits) fpdb_simple.fillCardArrays(len(names), base, category, card_values, card_suits)
hands_id=fpdb_simple.storeHands(cursor, site_hand_no, gametype_id, hand_start_time, names, tableName, maxSeats) hands_id=fpdb_simple.storeHands(backend, db, cursor, site_hand_no, gametype_id
,hand_start_time, names, tableName, maxSeats)
#print "before calling store_hands_players_stud, antes:", antes #print "before calling store_hands_players_stud, antes:", antes
hands_players_ids=fpdb_simple.store_hands_players_stud(cursor, hands_id, player_ids, hands_players_ids=fpdb_simple.store_hands_players_stud(backend, db, cursor, hands_id, player_ids
start_cashes, antes, card_values, card_suits, winnings, rakes, seatNos) ,start_cashes, antes, card_values
,card_suits, winnings, rakes, seatNos)
fpdb_simple.storeHudCache(cursor, base, category, gametype_id, player_ids, hudImportData) fpdb_simple.storeHudCache(cursor, base, category, gametype_id, player_ids, hudImportData)
fpdb_simple.storeActions(cursor, hands_players_ids, action_types, allIns, action_amounts, actionNos) fpdb_simple.storeActions(cursor, hands_players_ids, action_types
,allIns, action_amounts, actionNos)
return hands_id return hands_id
#end def ring_stud #end def ring_stud
def ring_holdem_omaha(cursor, base, category, site_hand_no, gametype_id, hand_start_time, names, player_ids, start_cashes, positions, card_values, card_suits, board_values, board_suits, winnings, rakes, action_types, allIns, action_amounts, actionNos, hudImportData, maxSeats, tableName, seatNos): def ring_holdem_omaha(backend, db, cursor, base, category, site_hand_no, gametype_id
,hand_start_time, names, player_ids, start_cashes, positions, card_values
,card_suits, board_values, board_suits, winnings, rakes, action_types, allIns
,action_amounts, actionNos, hudImportData, maxSeats, tableName, seatNos):
"""stores a holdem/omaha hand into the database""" """stores a holdem/omaha hand into the database"""
t0 = time()
fpdb_simple.fillCardArrays(len(names), base, category, card_values, card_suits) fpdb_simple.fillCardArrays(len(names), base, category, card_values, card_suits)
t1 = time()
fpdb_simple.fill_board_cards(board_values, board_suits) fpdb_simple.fill_board_cards(board_values, board_suits)
t2 = time()
hands_id=fpdb_simple.storeHands(cursor, site_hand_no, gametype_id, hand_start_time, names, tableName, maxSeats) hands_id=fpdb_simple.storeHands(backend, db, cursor, site_hand_no, gametype_id
,hand_start_time, names, tableName, maxSeats)
hands_players_ids=fpdb_simple.store_hands_players_holdem_omaha(cursor, category, hands_id, player_ids, start_cashes, positions, card_values, card_suits, winnings, rakes, seatNos) t3 = time()
hands_players_ids=fpdb_simple.store_hands_players_holdem_omaha(
backend, db, cursor, category, hands_id, player_ids, start_cashes
, positions, card_values, card_suits, winnings, rakes, seatNos)
t4 = time()
fpdb_simple.storeHudCache(cursor, base, category, gametype_id, player_ids, hudImportData) fpdb_simple.storeHudCache(cursor, base, category, gametype_id, player_ids, hudImportData)
t5 = time()
fpdb_simple.store_board_cards(cursor, hands_id, board_values, board_suits) fpdb_simple.store_board_cards(cursor, hands_id, board_values, board_suits)
t6 = time()
fpdb_simple.storeActions(cursor, hands_players_ids, action_types, allIns, action_amounts, actionNos) fpdb_simple.storeActions(cursor, hands_players_ids, action_types, allIns, action_amounts, actionNos)
t7 = time()
print "cards=%4.3f board=%4.3f hands=%4.3f plyrs=%4.3f hudcache=%4.3f board=%4.3f actions=%4.3f" \
% (t1-t0, t2-t1, t3-t2, t4-t3, t5-t4, t6-t5, t7-t6)
return hands_id return hands_id
#end def ring_holdem_omaha #end def ring_holdem_omaha
def tourney_holdem_omaha(cursor, base, category, siteTourneyNo, buyin, fee, knockout, entries, prizepool, tourney_start, payin_amounts, ranks, tourneyTypeId, siteId, #end of tourney specific params def tourney_holdem_omaha(backend, db, cursor, base, category, siteTourneyNo, buyin, fee, knockout
site_hand_no, gametype_id, hand_start_time, names, player_ids, start_cashes, positions, card_values, card_suits, board_values, board_suits, winnings, rakes, action_types, allIns, action_amounts, actionNos, hudImportData, maxSeats, tableName, seatNos): ,entries, prizepool, tourney_start, payin_amounts, ranks, tourneyTypeId
,siteId #end of tourney specific params
,site_hand_no, gametype_id, hand_start_time, names, player_ids
,start_cashes, positions, card_values, card_suits, board_values
,board_suits, winnings, rakes, action_types, allIns, action_amounts
,actionNos, hudImportData, maxSeats, tableName, seatNos):
"""stores a tourney holdem/omaha hand into the database""" """stores a tourney holdem/omaha hand into the database"""
fpdb_simple.fillCardArrays(len(names), base, category, card_values, card_suits) fpdb_simple.fillCardArrays(len(names), base, category, card_values, card_suits)
fpdb_simple.fill_board_cards(board_values, board_suits) fpdb_simple.fill_board_cards(board_values, board_suits)
@ -62,9 +87,12 @@ def tourney_holdem_omaha(cursor, base, category, siteTourneyNo, buyin, fee, knoc
tourney_id=fpdb_simple.store_tourneys(cursor, tourneyTypeId, siteTourneyNo, entries, prizepool, tourney_start) tourney_id=fpdb_simple.store_tourneys(cursor, tourneyTypeId, siteTourneyNo, entries, prizepool, tourney_start)
tourneys_players_ids=fpdb_simple.store_tourneys_players(cursor, tourney_id, player_ids, payin_amounts, ranks, winnings) tourneys_players_ids=fpdb_simple.store_tourneys_players(cursor, tourney_id, player_ids, payin_amounts, ranks, winnings)
hands_id=fpdb_simple.storeHands(cursor, site_hand_no, gametype_id, hand_start_time, names, tableName, maxSeats) hands_id=fpdb_simple.storeHands(backend, db, cursor, site_hand_no, gametype_id
,hand_start_time, names, tableName, maxSeats)
hands_players_ids=fpdb_simple.store_hands_players_holdem_omaha_tourney(cursor, category, hands_id, player_ids, start_cashes, positions, card_values, card_suits, winnings, rakes, seatNos, tourneys_players_ids) hands_players_ids=fpdb_simple.store_hands_players_holdem_omaha_tourney(
backend, db, cursor, category, hands_id, player_ids, start_cashes, positions
, card_values, card_suits, winnings, rakes, seatNos, tourneys_players_ids)
fpdb_simple.storeHudCache(cursor, base, category, gametype_id, player_ids, hudImportData) fpdb_simple.storeHudCache(cursor, base, category, gametype_id, player_ids, hudImportData)
@ -74,8 +102,11 @@ def tourney_holdem_omaha(cursor, base, category, siteTourneyNo, buyin, fee, knoc
return hands_id return hands_id
#end def tourney_holdem_omaha #end def tourney_holdem_omaha
def tourney_stud(cursor, base, category, siteTourneyNo, buyin, fee, knockout, entries, prizepool, tourneyStartTime, payin_amounts, ranks, tourneyTypeId, siteId, def tourney_stud(backend, db, cursor, base, category, siteTourneyNo, buyin, fee, knockout, entries
siteHandNo, gametypeId, handStartTime, names, playerIds, startCashes, antes, cardValues, cardSuits, winnings, rakes, actionTypes, allIns, actionAmounts, actionNos, hudImportData, maxSeats, tableName, seatNos): ,prizepool, tourneyStartTime, payin_amounts, ranks, tourneyTypeId, siteId
,siteHandNo, gametypeId, handStartTime, names, playerIds, startCashes, antes
,cardValues, cardSuits, winnings, rakes, actionTypes, allIns, actionAmounts
,actionNos, hudImportData, maxSeats, tableName, seatNos):
#stores a tourney stud/razz hand into the database #stores a tourney stud/razz hand into the database
fpdb_simple.fillCardArrays(len(names), base, category, cardValues, cardSuits) fpdb_simple.fillCardArrays(len(names), base, category, cardValues, cardSuits)
@ -83,9 +114,11 @@ def tourney_stud(cursor, base, category, siteTourneyNo, buyin, fee, knockout, en
tourneys_players_ids=fpdb_simple.store_tourneys_players(cursor, tourney_id, playerIds, payin_amounts, ranks, winnings) tourneys_players_ids=fpdb_simple.store_tourneys_players(cursor, tourney_id, playerIds, payin_amounts, ranks, winnings)
hands_id=fpdb_simple.storeHands(cursor, siteHandNo, gametypeId, handStartTime, names, tableName, maxSeats) hands_id=fpdb_simple.storeHands(backend, db, cursor, siteHandNo, gametypeId, handStartTime, names, tableName, maxSeats)
hands_players_ids=fpdb_simple.store_hands_players_stud_tourney(cursor, hands_id, playerIds, startCashes, antes, cardValues, cardSuits, winnings, rakes, seatNos, tourneys_players_ids) hands_players_ids=fpdb_simple.store_hands_players_stud_tourney(backend, db, cursor, hands_id
, playerIds, startCashes, antes, cardValues, cardSuits
, winnings, rakes, seatNos, tourneys_players_ids)
fpdb_simple.storeHudCache(cursor, base, category, gametypeId, playerIds, hudImportData) fpdb_simple.storeHudCache(cursor, base, category, gametypeId, playerIds, hudImportData)

180
pyfpdb/fpdb_simple.py Normal file → Executable file
View File

@ -23,6 +23,11 @@ import re
PS=1 PS=1
FTP=2 FTP=2
MYSQL_INNODB=2
PGSQL=3
SQLITE=4
class DuplicateError(Exception): class DuplicateError(Exception):
def __init__(self, value): def __init__(self, value):
self.value = value self.value = value
@ -35,6 +40,37 @@ class FpdbError(Exception):
def __str__(self): def __str__(self):
return repr(self.value) return repr(self.value)
# gets value for last auto-increment key generated
# returns -1 if a problem occurs
def getLastInsertId(backend, conn, cursor):
if backend == MYSQL_INNODB:
ret = conn.insert_id()
if ret < 1 or ret > 999999999:
print "getLastInsertId(): problem fetching insert_id? ret=", ret
ret = -1
elif backend == PGSQL:
# some options:
# currval(hands_id_seq) - use name of implicit seq here
# lastval() - still needs sequences set up?
# insert ... returning is useful syntax (but postgres specific?)
# see rules (fancy trigger type things)
cursor.execute ("SELECT lastval()")
row = cursor.fetchone()
if not row:
print "getLastInsertId(%s): problem fetching lastval? row=" % seq, row
ret = -1
else:
ret = row[0]
elif backend == SQLITE:
# don't know how to do this in sqlite
print "getLastInsertId(): not coded for sqlite yet"
ret = -1
else:
print "getLastInsertId(): unknown backend ", backend
ret = -1
return ret
#end def getLastInsertId
#returns an array of the total money paid. intending to add rebuys/addons here #returns an array of the total money paid. intending to add rebuys/addons here
def calcPayin(count, buyin, fee): def calcPayin(count, buyin, fee):
result=[] result=[]
@ -54,8 +90,7 @@ def checkPositions(positions):
pass pass
### RHH modified to allow for "position 9" here (pos==9 is when you're a dead hand before the BB ### RHH modified to allow for "position 9" here (pos==9 is when you're a dead hand before the BB
### eric - position 8 could be valid - if only one blind is posted, but there's still 10 people, ie a sitout is present, and the small is dead... if (pos!="B" and pos!="S" and pos!=0 and pos!=1 and pos!=2 and pos!=3 and pos!=4 and pos!=5 and pos!=6 and pos!=7 and pos!=9):
if not (pos == "B" or pos == "S" or (pos >= 0 and pos <= 9)):
raise FpdbError("invalid position found in checkPositions. i: "+str(i)+" position: "+str(pos)) raise FpdbError("invalid position found in checkPositions. i: "+str(i)+" position: "+str(pos))
#end def fpdb_simple.checkPositions #end def fpdb_simple.checkPositions
@ -485,6 +520,7 @@ def isActionLine(line):
#returns whether this is a duplicate #returns whether this is a duplicate
def isAlreadyInDB(cursor, gametypeID, siteHandNo): def isAlreadyInDB(cursor, gametypeID, siteHandNo):
#print "isAlreadyInDB gtid,shand:",gametypeID, siteHandNo
cursor.execute ("SELECT id FROM Hands WHERE gametypeId=%s AND siteHandNo=%s", (gametypeID, siteHandNo)) cursor.execute ("SELECT id FROM Hands WHERE gametypeId=%s AND siteHandNo=%s", (gametypeID, siteHandNo))
result=cursor.fetchall() result=cursor.fetchall()
if (len(result)>=1): if (len(result)>=1):
@ -735,7 +771,7 @@ def parseCardLine(site, category, street, line, names, cardValues, cardSuits, bo
print "line:",line,"cardValues[playerNo]:",cardValues[playerNo] print "line:",line,"cardValues[playerNo]:",cardValues[playerNo]
raise FpdbError("read too many/too few holecards in parseCardLine") raise FpdbError("read too many/too few holecards in parseCardLine")
elif (category=="razz" or category=="studhi" or category=="studhilo"): elif (category=="razz" or category=="studhi" or category=="studhilo"):
if (line.find("shows")==-1 and line.find("mucked") == -1): if (line.find("shows")==-1):
#print "parseCardLine(in stud if), street:", street #print "parseCardLine(in stud if), street:", street
if line[pos+2]=="]": #-> not (hero and 3rd street) if line[pos+2]=="]": #-> not (hero and 3rd street)
cardValues[playerNo][street+2]=line[pos:pos+1] cardValues[playerNo][street+2]=line[pos:pos+1]
@ -832,16 +868,14 @@ def parseHandStartTime(topline, site):
tmp=topline[pos1:pos2] tmp=topline[pos1:pos2]
isUTC=True isUTC=True
else: else:
tmp=topline tmp=topline[-30:]
#print "parsehandStartTime, tmp:", tmp #print "parsehandStartTime, tmp:", tmp
pos = tmp.find("-")+2 pos = tmp.find("-")+2
tmp = tmp[pos:] tmp = tmp[pos:]
#Need to match either #Need to match either
# 2008/09/07 06:23:14 ET or # 2008/09/07 06:23:14 ET or
# 2008/08/17 - 01:14:43 (ET) or # 2008/08/17 - 01:14:43 (ET)
# 2008/11/12 9:33:31 CET [2008/11/12 3:33:31 ET] m = re.match('(?P<YEAR>[0-9]{4})\/(?P<MON>[0-9]{2})\/(?P<DAY>[0-9]{2})[\- ]+(?P<HR>[0-9]{2}):(?P<MIN>[0-9]{2}):(?P<SEC>[0-9]{2})',tmp)
rexx = '(?P<YEAR>[0-9]{4})\/(?P<MON>[0-9]{2})\/(?P<DAY>[0-9]{2})[\- ]+(?P<HR>[0-9]+):(?P<MIN>[0-9]+):(?P<SEC>[0-9]+)'
m = re.search(rexx,tmp)
#print "year:", int(m.group('YEAR')), "month", int(m.group('MON')), "day", int(m.group('DAY')), "hour", int(m.group('HR')), "minute", int(m.group('MIN')), "second", int(m.group('SEC')) #print "year:", int(m.group('YEAR')), "month", int(m.group('MON')), "day", int(m.group('DAY')), "hour", int(m.group('HR')), "minute", int(m.group('MIN')), "second", int(m.group('SEC'))
result = datetime.datetime(int(m.group('YEAR')), int(m.group('MON')), int(m.group('DAY')), int(m.group('HR')), int(m.group('MIN')), int(m.group('SEC'))) result = datetime.datetime(int(m.group('YEAR')), int(m.group('MON')), int(m.group('DAY')), int(m.group('HR')), int(m.group('MIN')), int(m.group('SEC')))
else: else:
@ -894,11 +928,6 @@ def parsePositions (hand, names):
if (bb!=-1): if (bb!=-1):
bb=recognisePlayerNo(bb, names, "bet") bb=recognisePlayerNo(bb, names, "bet")
# print "sb = ", sb, "bb = ", bb
if bb == sb:
sbExists = False
sb = -1
#write blinds into array #write blinds into array
if (sbExists): if (sbExists):
positions[sb]="S" positions[sb]="S"
@ -915,25 +944,16 @@ def parsePositions (hand, names):
positions[arraypos]=distFromBtn positions[arraypos]=distFromBtn
arraypos-=1 arraypos-=1
distFromBtn+=1 distFromBtn+=1
# eric - this takes into account dead seats between blinds
if sbExists:
i = bb - 1
while positions[i] < 0 and i != sb:
positions[i] = 9
i -= 1
### RHH - Changed to set the null seats before BB to "9"
if sbExists:
i = sb-1
else:
i = bb-1
### RHH - Changed to set the null seats before BB to "9"
i=bb-1
while positions[i] < 0: while positions[i] < 0:
positions[i]=9 positions[i]=9
i-=1 i-=1
arraypos=len(names)-1 arraypos=len(names)-1
if (bb!=0 or (bb==0 and sbExists==False) or (bb == 1 and sb != arraypos) ): if (bb!=0 or (bb==0 and sbExists==False)):
while (arraypos>bb and arraypos > sb): while (arraypos>bb):
positions[arraypos]=distFromBtn positions[arraypos]=distFromBtn
arraypos-=1 arraypos-=1
distFromBtn+=1 distFromBtn+=1
@ -943,7 +963,6 @@ def parsePositions (hand, names):
print "parsePositions names:",names print "parsePositions names:",names
print "result:",positions print "result:",positions
raise FpdbError ("failed to read positions") raise FpdbError ("failed to read positions")
#print str(positions), "\n"
return positions return positions
#end def parsePositions #end def parsePositions
@ -1039,7 +1058,7 @@ def recogniseCategory(line):
#end def recogniseCategory #end def recogniseCategory
#returns the int for the gametype_id for the given line #returns the int for the gametype_id for the given line
def recogniseGametypeID(cursor, topline, smallBlindLine, site_id, category, isTourney):#todo: this method is messy def recogniseGametypeID(backend, db, cursor, topline, smallBlindLine, site_id, category, isTourney):#todo: this method is messy
#if (topline.find("HORSE")!=-1): #if (topline.find("HORSE")!=-1):
# raise FpdbError("recogniseGametypeID: HORSE is not yet supported.") # raise FpdbError("recogniseGametypeID: HORSE is not yet supported.")
@ -1090,6 +1109,9 @@ def recogniseGametypeID(cursor, topline, smallBlindLine, site_id, category, isTo
else: else:
cursor.execute ("SELECT id FROM Gametypes WHERE siteId=%s AND type=%s AND category=%s AND limitType=%s AND smallBlind=%s AND bigBlind=%s", (site_id, type, category, limit_type, small_bet, big_bet)) cursor.execute ("SELECT id FROM Gametypes WHERE siteId=%s AND type=%s AND category=%s AND limitType=%s AND smallBlind=%s AND bigBlind=%s", (site_id, type, category, limit_type, small_bet, big_bet))
result=cursor.fetchone() result=cursor.fetchone()
#print "recgt1 result=",result
#ret=result[0]
#print "recgt1 ret=",ret
#print "tried SELECTing gametypes.id, result:",result #print "tried SELECTing gametypes.id, result:",result
try: try:
@ -1120,18 +1142,24 @@ def recogniseGametypeID(cursor, topline, smallBlindLine, site_id, category, isTo
small_blind=float2int(smallBlindLine[pos:]) small_blind=float2int(smallBlindLine[pos:])
else: else:
small_blind=0 small_blind=0
cursor.execute("""INSERT INTO Gametypes cursor.execute( """INSERT INTO Gametypes(siteId, type, base, category, limitType
(siteId, type, base, category, limitType, hiLo, smallBlind, bigBlind, smallBet, bigBet) ,hiLo, smallBlind, bigBlind, smallBet, bigBet)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""", (site_id, type, base, category, limit_type, hiLo, small_blind, big_blind, small_bet, big_bet)) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""
cursor.execute ("SELECT id FROM Gametypes WHERE siteId=%s AND type=%s AND category=%s AND limitType=%s AND smallBet=%s AND bigBet=%s", (site_id, type, category, limit_type, small_bet, big_bet)) , (site_id, type, base, category, limit_type, hiLo
,small_blind, big_blind, small_bet, big_bet) )
#cursor.execute ("SELECT id FROM Gametypes WHERE siteId=%s AND type=%s AND category=%s
#AND limitType=%s AND smallBet=%s AND bigBet=%s", (site_id, type, category, limit_type, small_bet, big_bet))
else: else:
cursor.execute("""INSERT INTO Gametypes cursor.execute( """INSERT INTO Gametypes(siteId, type, base, category, limitType
(siteId, type, base, category, limitType, hiLo, smallBlind, bigBlind, smallBet, bigBet) ,hiLo, smallBlind, bigBlind, smallBet, bigBet)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""", (site_id, type, base, category, limit_type, hiLo, small_bet, big_bet, 0, 0))#remember, for these bet means blind VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""
cursor.execute ("SELECT id FROM Gametypes WHERE siteId=%s AND type=%s AND category=%s AND limitType=%s AND smallBlind=%s AND bigBlind=%s", (site_id, type, category, limit_type, small_bet, big_bet)) , (site_id, type, base, category, limit_type
,hiLo, small_bet, big_bet, 0, 0))#remember, for these bet means blind
#cursor.execute ("SELECT id FROM Gametypes WHERE siteId=%s AND type=%s AND category=%s
#AND limitType=%s AND smallBlind=%s AND bigBlind=%s", (site_id, type, category, limit_type, small_bet, big_bet))
result=cursor.fetchone() #result=(db.insert_id(),)
#print "created new gametypes.id:",result result=(getLastInsertId(backend,db,cursor),)
return result[0] return result[0]
#end def recogniseGametypeID #end def recogniseGametypeID
@ -1253,7 +1281,8 @@ def storeActions(cursor, handsPlayersIds, actionTypes, allIns, actionAmounts, ac
for i in range (len(actionTypes)): #iterate through streets for i in range (len(actionTypes)): #iterate through streets
for j in range (len(actionTypes[i])): #iterate through names for j in range (len(actionTypes[i])): #iterate through names
for k in range (len(actionTypes[i][j])): #iterate through individual actions of that player on that street for k in range (len(actionTypes[i][j])): #iterate through individual actions of that player on that street
cursor.execute ("INSERT INTO HandsActions (handPlayerId, street, actionNo, action, allIn, amount) VALUES (%s, %s, %s, %s, %s, %s)", (handsPlayersIds[j], i, actionNos[i][j][k], actionTypes[i][j][k], allIns[i][j][k], actionAmounts[i][j][k])) cursor.execute ("INSERT INTO HandsActions (handPlayerId, street, actionNo, action, allIn, amount) VALUES (%s, %s, %s, %s, %s, %s)"
, (handsPlayersIds[j], i, actionNos[i][j][k], actionTypes[i][j][k], allIns[i][j][k], actionAmounts[i][j][k]))
#end def storeActions #end def storeActions
def store_board_cards(cursor, hands_id, board_values, board_suits): def store_board_cards(cursor, hands_id, board_values, board_suits):
@ -1266,15 +1295,19 @@ def store_board_cards(cursor, hands_id, board_values, board_suits):
board_values[4], board_suits[4])) board_values[4], board_suits[4]))
#end def store_board_cards #end def store_board_cards
def storeHands(cursor, site_hand_no, gametype_id, hand_start_time, names, tableName, maxSeats): def storeHands(backend, conn, cursor, site_hand_no, gametype_id
,hand_start_time, names, tableName, maxSeats):
#stores into table hands #stores into table hands
cursor.execute ("INSERT INTO Hands (siteHandNo, gametypeId, handStart, seats, tableName, importTime, maxSeats) VALUES (%s, %s, %s, %s, %s, %s, %s)", (site_hand_no, gametype_id, hand_start_time, len(names), tableName, datetime.datetime.today(), maxSeats)) cursor.execute ("INSERT INTO Hands (siteHandNo, gametypeId, handStart, seats, tableName, importTime, maxSeats) VALUES (%s, %s, %s, %s, %s, %s, %s)", (site_hand_no, gametype_id, hand_start_time, len(names), tableName, datetime.datetime.today(), maxSeats))
#todo: find a better way of doing this... #todo: find a better way of doing this...
cursor.execute("SELECT id FROM Hands WHERE siteHandNo=%s AND gametypeId=%s", (site_hand_no, gametype_id)) #cursor.execute("SELECT id FROM Hands WHERE siteHandNo=%s AND gametypeId=%s", (site_hand_no, gametype_id))
return cursor.fetchall()[0][0] #return cursor.fetchall()[0][0]
return getLastInsertId(backend, conn, cursor)
#return db.insert_id() # mysql only
#end def storeHands #end def storeHands
def store_hands_players_holdem_omaha(cursor, category, hands_id, player_ids, start_cashes, positions, card_values, card_suits, winnings, rakes, seatNos): def store_hands_players_holdem_omaha(backend, conn, cursor, category, hands_id, player_ids, start_cashes
,positions, card_values, card_suits, winnings, rakes, seatNos):
result=[] result=[]
if (category=="holdem"): if (category=="holdem"):
for i in range (len(player_ids)): for i in range (len(player_ids)):
@ -1286,8 +1319,9 @@ def store_hands_players_holdem_omaha(cursor, category, hands_id, player_ids, sta
(hands_id, player_ids[i], start_cashes[i], positions[i], (hands_id, player_ids[i], start_cashes[i], positions[i],
card_values[i][0], card_suits[i][0], card_values[i][1], card_suits[i][1], card_values[i][0], card_suits[i][0], card_values[i][1], card_suits[i][1],
winnings[i], rakes[i], seatNos[i])) winnings[i], rakes[i], seatNos[i]))
cursor.execute("SELECT id FROM HandsPlayers WHERE handId=%s AND playerId+0=%s", (hands_id, player_ids[i])) #cursor.execute("SELECT id FROM HandsPlayers WHERE handId=%s AND playerId=%s", (hands_id, player_ids[i]))
result.append(cursor.fetchall()[0][0]) #result.append(cursor.fetchall()[0][0])
result.append( getLastInsertId(backend, conn, cursor) ) # mysql only
elif (category=="omahahi" or category=="omahahilo"): elif (category=="omahahi" or category=="omahahilo"):
for i in range (len(player_ids)): for i in range (len(player_ids)):
cursor.execute ("""INSERT INTO HandsPlayers cursor.execute ("""INSERT INTO HandsPlayers
@ -1299,14 +1333,15 @@ def store_hands_players_holdem_omaha(cursor, category, hands_id, player_ids, sta
card_values[i][0], card_suits[i][0], card_values[i][1], card_suits[i][1], card_values[i][0], card_suits[i][0], card_values[i][1], card_suits[i][1],
card_values[i][2], card_suits[i][2], card_values[i][3], card_suits[i][3], card_values[i][2], card_suits[i][2], card_values[i][3], card_suits[i][3],
winnings[i], rakes[i], seatNos[i])) winnings[i], rakes[i], seatNos[i]))
cursor.execute("SELECT id FROM HandsPlayers WHERE handId=%s AND playerId+0=%s", (hands_id, player_ids[i])) #cursor.execute("SELECT id FROM HandsPlayers WHERE handId=%s AND playerId+0=%s", (hands_id, player_ids[i]))
result.append(cursor.fetchall()[0][0]) #result.append(cursor.fetchall()[0][0])
result.append( getLastInsertId(backend, conn, cursor) ) # mysql only
else: else:
raise FpdbError("invalid category") raise FpdbError("invalid category")
return result return result
#end def store_hands_players_holdem_omaha #end def store_hands_players_holdem_omaha
def store_hands_players_stud(cursor, hands_id, player_ids, start_cashes, antes, def store_hands_players_stud(backend, conn, cursor, hands_id, player_ids, start_cashes, antes,
card_values, card_suits, winnings, rakes, seatNos): card_values, card_suits, winnings, rakes, seatNos):
#stores hands_players rows for stud/razz games. returns an array of the resulting IDs #stores hands_players rows for stud/razz games. returns an array of the resulting IDs
result=[] result=[]
@ -1325,12 +1360,15 @@ def store_hands_players_stud(cursor, hands_id, player_ids, start_cashes, antes,
card_values[i][2], card_suits[i][2], card_values[i][3], card_suits[i][3], card_values[i][2], card_suits[i][2], card_values[i][3], card_suits[i][3],
card_values[i][4], card_suits[i][4], card_values[i][5], card_suits[i][5], card_values[i][4], card_suits[i][4], card_values[i][5], card_suits[i][5],
card_values[i][6], card_suits[i][6], winnings[i], rakes[i], seatNos[i])) card_values[i][6], card_suits[i][6], winnings[i], rakes[i], seatNos[i]))
cursor.execute("SELECT id FROM HandsPlayers WHERE handId=%s AND playerId+0=%s", (hands_id, player_ids[i])) #cursor.execute("SELECT id FROM HandsPlayers WHERE handId=%s AND playerId+0=%s", (hands_id, player_ids[i]))
result.append(cursor.fetchall()[0][0]) #result.append(cursor.fetchall()[0][0])
result.append( getLastInsertId(backend, conn, cursor) ) # mysql only
return result return result
#end def store_hands_players_stud #end def store_hands_players_stud
def store_hands_players_holdem_omaha_tourney(cursor, category, hands_id, player_ids, start_cashes, positions, card_values, card_suits, winnings, rakes, seatNos, tourneys_players_ids): def store_hands_players_holdem_omaha_tourney(backend, conn, cursor, category, hands_id, player_ids
,start_cashes, positions, card_values, card_suits
, winnings, rakes, seatNos, tourneys_players_ids):
#stores hands_players for tourney holdem/omaha hands #stores hands_players for tourney holdem/omaha hands
result=[] result=[]
for i in range (len(player_ids)): for i in range (len(player_ids)):
@ -1356,13 +1394,14 @@ def store_hands_players_holdem_omaha_tourney(cursor, category, hands_id, player_
winnings[i], rakes[i], tourneys_players_ids[i], seatNos[i])) winnings[i], rakes[i], tourneys_players_ids[i], seatNos[i]))
else: else:
raise FpdbError ("invalid card_values length:"+str(len(card_values[0]))) raise FpdbError ("invalid card_values length:"+str(len(card_values[0])))
cursor.execute("SELECT id FROM HandsPlayers WHERE handId=%s AND playerId+0=%s", (hands_id, player_ids[i])) #cursor.execute("SELECT id FROM HandsPlayers WHERE handId=%s AND playerId+0=%s", (hands_id, player_ids[i]))
result.append(cursor.fetchall()[0][0]) #result.append(cursor.fetchall()[0][0])
result.append( getLastInsertId(backend, conn, cursor) ) # mysql only
return result return result
#end def store_hands_players_holdem_omaha_tourney #end def store_hands_players_holdem_omaha_tourney
def store_hands_players_stud_tourney(cursor, hands_id, player_ids, start_cashes, def store_hands_players_stud_tourney(backend, conn, cursor, hands_id, player_ids, start_cashes,
antes, card_values, card_suits, winnings, rakes, seatNos, tourneys_players_ids): antes, card_values, card_suits, winnings, rakes, seatNos, tourneys_players_ids):
#stores hands_players for tourney stud/razz hands #stores hands_players for tourney stud/razz hands
result=[] result=[]
@ -1380,13 +1419,18 @@ def store_hands_players_stud_tourney(cursor, hands_id, player_ids, start_cashes,
card_values[i][2], card_suits[i][2], card_values[i][3], card_suits[i][3], card_values[i][2], card_suits[i][2], card_values[i][3], card_suits[i][3],
card_values[i][4], card_suits[i][4], card_values[i][5], card_suits[i][5], card_values[i][4], card_suits[i][4], card_values[i][5], card_suits[i][5],
card_values[i][6], card_suits[i][6], winnings[i], rakes[i], tourneys_players_ids[i], seatNos[i])) card_values[i][6], card_suits[i][6], winnings[i], rakes[i], tourneys_players_ids[i], seatNos[i]))
cursor.execute("SELECT id FROM HandsPlayers WHERE handId=%s AND playerId=%s", (hands_id, player_ids[i])) #cursor.execute("SELECT id FROM HandsPlayers WHERE handId=%s AND playerId+0=%s", (hands_id, player_ids[i]))
result.append(cursor.fetchall()[0][0]) #result.append(cursor.fetchall()[0][0])
result.append( getLastInsertId(backend, conn, cursor) ) # mysql only
return result return result
#end def store_hands_players_stud_tourney #end def store_hands_players_stud_tourney
def generateHudCacheData(player_ids, base, category, action_types, allIns, actionTypeByNo, winnings, totalWinnings, positions): def generateHudCacheData(player_ids, base, category, action_types, allIns, actionTypeByNo
"""calculates data for the HUD during import. IMPORTANT: if you change this method make sure to also change the following storage method and table_viewer.prepare_data if necessary""" ,winnings, totalWinnings, positions, actionTypes, actionAmounts):
"""calculates data for the HUD during import. IMPORTANT: if you change this method make
sure to also change the following storage method and table_viewer.prepare_data if necessary
"""
#print "generateHudCacheData, len(player_ids)=", len(player_ids)
#setup subarrays of the result dictionary. #setup subarrays of the result dictionary.
street0VPI=[] street0VPI=[]
street0Aggr=[] street0Aggr=[]
@ -1692,7 +1736,7 @@ def generateHudCacheData(player_ids, base, category, action_types, allIns, actio
hudDataPositions.append('C') hudDataPositions.append('C')
elif pos>=2 and pos<=4: elif pos>=2 and pos<=4:
hudDataPositions.append('M') hudDataPositions.append('M')
elif pos>=5 and pos<=8: elif pos>=5 and pos<=7:
hudDataPositions.append('E') hudDataPositions.append('E')
### RHH Added this elif to handle being a dead hand before the BB (pos==9) ### RHH Added this elif to handle being a dead hand before the BB (pos==9)
elif pos==9: elif pos==9:
@ -1906,8 +1950,14 @@ def generateHudCacheData(player_ids, base, category, action_types, allIns, actio
street3CheckCallRaiseDone=[] street3CheckCallRaiseDone=[]
street4CheckCallRaiseChance=[] street4CheckCallRaiseChance=[]
street4CheckCallRaiseDone=[] street4CheckCallRaiseDone=[]
for player in range (len(player_ids)): #print "b4 totprof calc, len(playerIds)=", len(player_ids)
myTotalProfit=0 for pl in range (len(player_ids)):
#print "pl=", pl
myTotalProfit=winnings[pl] # still need to deduct costs
for i in range (len(actionTypes)): #iterate through streets
#for j in range (len(actionTypes[i])): #iterate through names (using pl loop above)
for k in range (len(actionTypes[i][pl])): #iterate through individual actions of that player on that street
myTotalProfit -= actionAmounts[i][pl][k]
myStreet1CheckCallRaiseChance=False myStreet1CheckCallRaiseChance=False
myStreet1CheckCallRaiseDone=False myStreet1CheckCallRaiseDone=False
@ -1918,7 +1968,9 @@ def generateHudCacheData(player_ids, base, category, action_types, allIns, actio
myStreet4CheckCallRaiseChance=False myStreet4CheckCallRaiseChance=False
myStreet4CheckCallRaiseDone=False myStreet4CheckCallRaiseDone=False
#print "myTotalProfit=", myTotalProfit
totalProfit.append(myTotalProfit) totalProfit.append(myTotalProfit)
#print "totalProfit[]=", totalProfit
street1CheckCallRaiseChance.append(myStreet1CheckCallRaiseChance) street1CheckCallRaiseChance.append(myStreet1CheckCallRaiseChance)
street1CheckCallRaiseDone.append(myStreet1CheckCallRaiseDone) street1CheckCallRaiseDone.append(myStreet1CheckCallRaiseDone)
@ -1930,6 +1982,7 @@ def generateHudCacheData(player_ids, base, category, action_types, allIns, actio
street4CheckCallRaiseDone.append(myStreet4CheckCallRaiseDone) street4CheckCallRaiseDone.append(myStreet4CheckCallRaiseDone)
result['totalProfit']=totalProfit result['totalProfit']=totalProfit
#print "res[totalProfit]=", result['totalProfit']
result['street1CheckCallRaiseChance']=street1CheckCallRaiseChance result['street1CheckCallRaiseChance']=street1CheckCallRaiseChance
result['street1CheckCallRaiseDone']=street1CheckCallRaiseDone result['street1CheckCallRaiseDone']=street1CheckCallRaiseDone
@ -1965,6 +2018,8 @@ def generateFoldToCB(street, playerIDs, didStreetCB, streetCBDone, foldToStreetC
def storeHudCache(cursor, base, category, gametypeId, playerIds, hudImportData): def storeHudCache(cursor, base, category, gametypeId, playerIds, hudImportData):
# if (category=="holdem" or category=="omahahi" or category=="omahahilo"): # if (category=="holdem" or category=="omahahi" or category=="omahahilo"):
#print "storeHudCache, len(playerIds)=", len(playerIds), " len(vpip)=" \
#, len(hudImportData['street0VPI']), " len(totprof)=", len(hudImportData['totalProfit'])
for player in range (len(playerIds)): for player in range (len(playerIds)):
if base=="hold": if base=="hold":
cursor.execute("SELECT * FROM HudCache WHERE gametypeId+0=%s AND playerId=%s AND activeSeats=%s AND position=%s", (gametypeId, playerIds[player], len(playerIds), hudImportData['position'][player])) cursor.execute("SELECT * FROM HudCache WHERE gametypeId+0=%s AND playerId=%s AND activeSeats=%s AND position=%s", (gametypeId, playerIds[player], len(playerIds), hudImportData['position'][player]))
@ -2049,6 +2104,9 @@ def storeHudCache(cursor, base, category, gametypeId, playerIds, hudImportData):
if hudImportData['foldToStreet4CBChance'][player]: row[50]+=1 if hudImportData['foldToStreet4CBChance'][player]: row[50]+=1
if hudImportData['foldToStreet4CBDone'][player]: row[51]+=1 if hudImportData['foldToStreet4CBDone'][player]: row[51]+=1
#print "player=", player
#print "len(totalProfit)=", len(hudImportData['totalProfit'])
if hudImportData['totalProfit'][player]:
row[52]+=hudImportData['totalProfit'][player] row[52]+=hudImportData['totalProfit'][player]
if hudImportData['street1CheckCallRaiseChance'][player]: row[53]+=1 if hudImportData['street1CheckCallRaiseChance'][player]: row[53]+=1

27
pyfpdb/upd_indexes.sql Executable file
View File

@ -0,0 +1,27 @@
# script to update indexes on mysql (+other?) database
select '1. Dropping indexes' as ' ';
select 'Can''t drop messages indicate index already gone' as ' ';
ALTER TABLE `fpdb`.`Settings` DROP INDEX `id`;
ALTER TABLE `fpdb`.`Sites` DROP INDEX `id`;
ALTER TABLE `fpdb`.`Gametypes` DROP INDEX `id`;
ALTER TABLE `fpdb`.`Players` DROP INDEX `id`;
ALTER TABLE `fpdb`.`Autorates` DROP INDEX `id`;
ALTER TABLE `fpdb`.`Hands` DROP INDEX `id`;
ALTER TABLE `fpdb`.`BoardCards` DROP INDEX `id`;
ALTER TABLE `fpdb`.`TourneyTypes` DROP INDEX `id`;
ALTER TABLE `fpdb`.`Tourneys` DROP INDEX `id`;
ALTER TABLE `fpdb`.`TourneysPlayers` DROP INDEX `id`;
ALTER TABLE `fpdb`.`HandsPlayers` DROP INDEX `id`;
ALTER TABLE `fpdb`.`HandsActions` DROP INDEX `id`;
ALTER TABLE `fpdb`.`HudCache` DROP INDEX `id`;
select '2. Adding extra indexes on useful fields' as ' ';
select 'Duplicate key name messages indicate new indexes already there' as ' ';
ALTER TABLE `fpdb`.`tourneys` ADD INDEX `siteTourneyNo`(`siteTourneyNo`);
ALTER TABLE `fpdb`.`hands` ADD INDEX `siteHandNo`(`siteHandNo`);
ALTER TABLE `fpdb`.`players` ADD INDEX `name`(`name`);

0
readme.txt Normal file
View File