#@package: postgres-basic quote_sql gen_sql_insert_from_array perform_sql_insert_from_array clock_to_sql_time clock_to_precise_sql_time sql_time_to_clock

#
# Copyright (C) 1996-1997 NeoSoft.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted, provided
# that the above copyright notice appear in all copies.  NeoSoft makes no 
# representations about the suitability of this software for any purpose.
# It is provided "as is" without express or implied warranty.

#
# postgres95 interface stuff
#
# $Id: basic.tcl,v 1.1.1.1 1999/03/31 20:34:39 damon Exp $
#

#
# make string mostly legally quoted for postgres95 
#
proc quote_sql {string} {
    set string [join [split $string "\n"] "\\n"]
    regsub -all "(')" $string "\\'" string
    regsub -all {(\\)} $string "\\\\" string
    return '$string'
}

#
# generate a sql insert command based on contents of an array
#
proc gen_sql_insert_from_array {tableName arrayName} {
    upvar $arrayName array

    set nameList [array names array]

    set result "insert into $tableName ([join $nameList ","]) values ("

    foreach name $nameList {
	append result "[quote_sql $array($name)],"
    }
    return "[crange $result 0 end-1]);"
}

#
# generate a sql insert command based on contents of an array and
# send it to the database
#
proc perform_sql_insert_from_array {session tableName arrayName} {
    upvar $arrayName array
    set result [pg_exec $session [gen_sql_insert_from_array $tableName array]]
    set status [pg_result $result -status]
    pg_result $result -clear
    return $status
}

#
# convert a clock value (integer seconds since 1970) to a sql standard
# abstime value.
#
#        Month  Day [ Hour : Minute : Second ]  Year [ Timezone ]
#
proc clock_to_sql_time {clock} {
    return [fmtclock $clock "%b %d %Y"]
}

proc clock_to_precise_sql_time {clock} {
    return [fmtclock $clock "%b %d %H:%M:%S %Y GMT"]
}

#
# convert a sql standard abstime value to a clock value (integer
# seconds since 1970)
#
proc sql_time_to_clock {date} {
    if {$date == ""} {
	return 0
    }
    return [convertclock $date]
}
