#!/usr/bin/python
# Adds field and content from source table to target table.
import sys,dbcnf,os
db=dbcnf.db
dbc=db.cursor()
assert len(sys.argv)==4, 'Arguments: <source_table> <field> <target_table>'
stn=sys.argv[1]
fld=sys.argv[2]
ttn=sys.argv[3]

def table_exists(t):
 """Checks if a table exists in postgreSQL database."""
 dbc.execute('SELECT relname FROM pg_class WHERE relname ILIKE %s',(t,))
 return dbc.rowcount

def add_field(table,field,field_type):
 """Adds a field if it doesn not already exist in a certain table."""
 dbc.execute('SELECT * FROM %s LIMIT 1' % table)
 if field in map(lambda x:x[0],dbc.description):
  return 'Field "%s" is present in table %s' % (field,table)
 dbc.execute('ALTER TABLE %s ADD COLUMN %s %s' % (table,field,field_type) )
 return 'Field "%s" added to table %s' % (field,table)

def get_type(table,field):
 """Return the type of a field in a certain table."""
 dbc.execute('SELECT %s FROM %s LIMIT 1' % (field,table))
 return dbc.description[0][1]

def has_field(table,field):
 """Checks if a table has a certain field."""
 dbc.execute('SELECT * FROM %s LIMIT 1' % table)
 fields=map(lambda x:x[0],dbc.description)
 if field in fields: return True

assert table_exists(stn), 'Source table does not exist.'
assert table_exists(ttn), 'Target table does not exist.'
assert has_field(stn,fld), 'Source field does not exist.'

print add_field(ttn,fld,get_type(stn,fld))
db.commit()
cnt=0
dbc.execute('SELECT %s,gid FROM %s' % (fld,stn) )
print '%d rows fetched from %s.%s' % (dbc.rowcount,stn,fld) 
for ip in dbc.fetchall():
 if not ip[0]: continue
 dbc.execute('UPDATE %s SET %s = %%s WHERE gid = %%s' % (ttn,fld),ip)
 cnt+=1
db.commit()
print '%d values copied into %s.%s' % (cnt,ttn,fld)