# $Header: /home/cvsroot/tcldb/ucodb/Tlib/PGgetPkeys,v 1.2 1998/05/18 22:28:45 de Exp $
# tcl procs saved on Sun Sep 03 16:18:54 PDT 1995

proc PGgetPkeys table {

        global dbpipe1 server 
	global PGuids PGtypids PGusers PGtypes

#	Since PG95 has no concept of primarykeying, we will
#	just look for oid.  If we don't find an oid we are
#	unkeyed.

	set temp [split $table .]
        set pref ""
        if {[llength $temp] == 3} {
                lassign $temp dbs usr tbl
                set pref "$dbs.."
        } else {
                lassign $temp usr tbl
        }

#	This is all ripped off from PGgetEZcols

	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 $us
r??"
                return
        }
        set toid [keylget tables(0) toid]

        set sqlcmd "select attname from pg_attribute where attrelid = $toid and attnum < 0"

#        puts stderr "GETCOLS $sqlcmd"
        set sqt pg_attribute
        lassign [pgSQL 1] ct han res

	set keys ""
        loop i 0 $ct {

                set col [pgGetI $han $i]

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

                if {$col == ""} {break}

		if {$col == "oid"} {
			set keys "oid"
			break
		}
	}
	return $keys

}

