# $Header: /home/cvsroot/tcldb/wisql/Tlib/PGgetEZcols,v 1.4 1998/05/18 22:29:09 de Exp ${DB}getEZcols,v 1.1.1.1 1996/10/12 02:26:27 de Exp $
# tcl procs saved on Tue Sep 05 09:32:55 PDT 1995

proc PGgetEZcols which {

global base table sybmsg syb server  DB
global PGusers PGuids PGtypes PGtypids

# puts stderr "Called PGgetEZcols $which"

upvar #0 EZ${which}cols cols
upvar #0 EZ${which}colatts colatts
upvar #0 EZ${which}shows shows
upvar #0 EZEkeys keys


	set cols ""

# puts stderr "nulled out cols, colnames, types, sizes, nulls"

        set temp [split $table .]
        set usr [lindex $temp 0]
        set tbl  [lindex $temp 1]


	set sqlcmd "select pg_class.oid,pg_class.relname from pg_class where relname = '$tbl' and relowner = $PGuids($usr)"

        set sqt "pg_class"
        lassign [pgSQL 1] ct han res
        if {[lindex $res 0] == "ERROR"} {
                echo "Something went wrong here:"
                echo "$res"
                exit 1
        }

	loop i 0 $ct {
                set line [pgGetI $han $i]
		lassign $line toid tnam
		keylset tables($i) toid $toid tnam $tnam
	}
	if {[llength [array names tables]] > 1} {
		puts stderr "Whoa Nellie!  Two tables called $tbl owned by $usr??"
		return
	}
	set toid [keylget tables(0) toid]

	set sqlcmd "select attname,atttypid,attlen,attnum from pg_attribute where attrelid = $toid and attnum >= 0 order by attnum"
#	puts stderr "GETCOLS $sqlcmd"
	set sqt pg_attribute
        lassign [pgSQL 1] ct han res

	loop i 0 $ct {

                set line [pgGetI $han $i]

                if {[lindex $line 0] == "ERROR"} {
                        puts stderr "$line"
                        break
                }

                if {$line == ""} {break}

		lassign $line c tc s num

		set t [keylget PGtypes($tc) typname]

#	hardwire this for the nonce
                set n 1

                lappend cols [string tolower $c]
                set cc [string tolower $c]
		keylset colatts($cc) name $c type $t size $s nulls $n

        }

	if {$which == "E"} {

            set keys [PGgetPkeys $table]
	    if {$keys == "oid"} {
		set cols "oid $cols"
		keylset colatts(oid) name oid type int size 4 nulls 0
	    }
        }

	foreach c $cols {
#		set shows to show this col, only if not already set
		set ierr [catch {set x $shows($c)}]
		if {($ierr) || ([lsearch $keys $c] >= 0)} {
		set shows($c) 1
		}
	}

}

