import sqlite3

__author__ = 'sammoth'


def build(log):
    """
    Build the necessary tables in the database
    use the 'IF NOT EXISTS' clause to allow for repeated running without barfing
    :return:
    """
    conn = sqlite3.connect('pool.db')
    c = conn.cursor()
    log.info('create the users table')
    c.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, user TEXT, "
              "address TEXT, exchange TEXT, unit TEXT)")
    log.info('create the orders table')
    c.execute("CREATE TABLE IF NOT EXISTS orders (id INTEGER PRIMARY KEY, user TEXT, "
              "rank TEXT, order_id TEXT, order_amount NUMBER, side TEXT, exchange "
              "TEXT, unit TEXT, credited INTEGER)")
    log.info('create the credits table')
    c.execute("CREATE TABLE IF NOT EXISTS credits (id INTEGER PRIMARY KEY, time NUMBER, "
              "user TEXT, exchange TEXT, unit TEXT, rank TEXT, side TEXT, "
              "order_id NUMBER, provided NUMBER, total NUMBER, percentage NUMBER, "
              "reward NUMBER, paid INTEGER)")
    log.info('create the stats table')
    c.execute("CREATE TABLE IF NOT EXISTS stats (id INTEGER PRIMARY KEY, time NUMBER, "
              "meta TEXT, totals TEXT, rewards TEXT)")
    log.info('create the info table')
    c.execute("CREATE TABLE IF NOT EXISTS info (key Text, value Text)")
    c.execute("INSERT INTO info VALUES (?, ?)", ('last_credit_time', 0))
    conn.commit()
    conn.close()
    return

@@ -7,16 +7,42 @@
  sqlite3
+%0Aimport psycopg2%0Aimport os
 %0A%0A__auth
@@ -70,16 +70,21 @@
 f build(
+app, 
 log):%0A  
@@ -253,33 +253,18 @@
 n = 
-sqlite3.connect('pool.db'
+get_db(app
 )%0A  
@@ -664,25 +664,16 @@
 de TEXT,
- exchange
  %22%0A     
@@ -682,31 +682,116 @@
        %22
-TEXT, unit TEXT
+order_price NUMBER, server_price NUMBER, exchange TEXT, unit TEXT, %22%0A              %22deviation NUMBER
 , credit
@@ -1515,45 +1515,587 @@
    c
-onn.commit()%0A    conn.close()%0A    return
+.execute(%22INSERT INTO info VALUES (?, ?)%22, ('next_payout_time', 0))%0A    conn.commit()%0A    conn.close()%0A    return%0A%0A%0Adef get_db(app):%0A    %22%22%22%0A    Determine which database to use based on Environment Variables and return a%0A    database cursor object%0A    :return:%0A    %22%22%22%0A    if os.getenv('DATABASE', '') == 'POSTGRES':%0A        conn = psycopg2.connect('dbname=%7B%7D user=%7B%7D password=%7B%7D host=%7B%7D'.format(%0A            app.config%5B'db.name'%5D, app.config%5B'db.user'%5D, app.config%5B'db.pass'%5D,%0A            app.config%5B'db.host'%5D))%0A    else:%0A        conn = sqlite3.connect('pool.db')%0A    return conn%0A
 %0A

add method to abstract different databases