import MySQLdb
import MySQLdb.cursors

MAX_CONNECTIONS = 40
CONNECTION_POOL = []
CURRENT_POOL_INDEX = 0
def getDbCursor():
    # Does a round robin of connection pooling.
    # If you work this out with a single connection
    # it will segfault on high load
    #
    # Works fine with MAX_CONNECTIONS=5 but will double the pool just in case
    global CONNECTION_POOL
    global MAX_CONNECTIONS
    global CURRENT_POOL_INDEX

    con = None

    if len(CONNECTION_POOL) <= MAX_CONNECTIONS:
        con = MySQLdb.connect(host='localhost',
                              user='ip2location',
                              passwd='ip2location',
                              db='ip2location',
                              use_unicode=True,
                              cursorclass=MySQLdb.cursors.DictCursor,
                              )
        CONNECTION_POOL.append(con)
        CURRENT_POOL_INDEX = len(CONNECTION_POOL)-1
        #print "Adding New Connection. Total %d" % (len(CONNECTION_POOL))
    else:
        CURRENT_POOL_INDEX = (CURRENT_POOL_INDEX + 1) % len(CONNECTION_POOL)
        con = CONNECTION_POOL[CURRENT_POOL_INDEX]
        #print "Reusing connection (%d,%s)" % (CURRENT_POOL_INDEX,str(hex(id(con))))

    cursor = con.cursor(MySQLdb.cursors.DictCursor)
    cursor.execute("SET AUTOCOMMIT=1;")
        
    return cursor

def putUSRangesInTextFile():
  cursor = getDbCursor()
  cursor.execute("select ip_from,ip_to from ipcountry where country_short = 'US' order by ip_from asc;")

  f = open("us_based_ip_ranges.dat","wb")

  while 1:
      row = cursor.fetchone()

      if row is None:
          f.close()
          print "\n--"
          break

      f.write(str(row['ip_from'])+':'+str(row['ip_to'])+"\n")
      print ".",
  f.close()

if __name__ == '__main__':
    putUSRangesInTextFile()
