# Collection of code snippets by Arne Vajhøj 
# (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
from sys import argv

from rdb import dbapi2
#import pymysql
import sqlite3

def perform(con):
    c = con.cursor()
    c.execute('SELECT customer.id AS cid, name, phone, source ' + \
              'FROM customer JOIN customer_potential ON customer.id = customer_potential.id ' + \
              'ORDER BY cid')
    data = c.fetchall()
    c.close()
    for row in data:
        print('**future customer** %s, %s, %s' % (row[1], row[2], row[3]))
    c = con.cursor()
    c.execute('SELECT customer.id AS cid,name,address1,address2,phone,order_main.id AS oid,status,SUM(quantity*price) AS sumval ' + \
              'FROM customer JOIN customer_actual ON customer.id = customer_actual.id ' + \
              '              JOIN order_main ON customer.id = order_main.customer ' + \
              '              JOIN order_line ON order_main.id = order_line.order_main ' + \
              'GROUP BY customer.id,name,address1,address2,phone,order_main.id,status ' + \
              'ORDER BY cid, oid')
    data = c.fetchall()
    c.close()
    last_customer_id = 0
    for row in data:
        if row[0] != last_customer_id:
            print('%s, %s, %s, %s' % (row[1], row[2], row[3], row[4]))
            last_customer_id = row[0]
        print('  %s, %s, %s' % (row[5], row[6], row[7]))
    con.close()
    
if argv[1] == 'Rdb':
    perform(dbapi2.connect(database='disk4:[rdb]test'))
#if argv[1] == 'MySQL':
#    perform(pymysql.connect(host='localhost',user='root',password='',db='test'))
if argv[1] == 'SQLite':
    perform(sqlite3.connect('test.db'))
