package require Pgtcl 1.5

proc assert { val1 val2 } {
    if { $val1 != $val2 } {
	puts "FAIL: $val1 != $val2"
	exit 1
    }
}

#
# no connection
#

assert [pg_quote "ab"] "'ab'"
# real line breaks are okay
assert [pg_quote "a\nb"] "'a\nb'"

# but backslashes aren't (note that Python notation also needs to escape them)
assert [pg_quote "a\\nb"] "'a\\\\nb'"
# double quotes are not magic in SQL
assert [pg_quote "a\"b"] "'a\"b'"
# but single quotes are
assert [pg_quote "a'b"] "'a''b'"

# this depends on the client encoding; connection-less method does not escape -> unsafe
assert [pg_quote "a\u00BF'b"] "'a\u00BF''b'"

assert [pg_escape_bytea "a\"b"] "a\"b"
assert [pg_escape_bytea "a'b"] "a''b"
assert [pg_escape_bytea "a\001\377b"] "a\\\\001\\\\377b"

#
# with connection
#


set conn [pg_connect template1]
puts "got connection"

pg_exec $conn "set client_encoding='UTF-8'"

# testing DB connectivity: print DB names
#set res [pg_exec $conn "SELECT datname FROM pg_database ORDER BY datname;"]
#puts [pg_result $res -list]

# 0xBF27 has to be escaped here, since ' is interpreted as a quote
assert [pg_quote $conn "a\u00BF'b"] "'a\u00BF''b'"
# 0xBF27 must not be escaped here, since it is a valid character in GBK
pg_exec $conn "set client_encoding='GBK'"
assert [pg_quote $conn "a\u00BF'b"] "'a\u00BF'b'"

# 0xBF27 has to be escaped here, since ' is interpreted as a quote
assert [pg_escape_bytea $conn "a\u00BF'b"] "a\u00BF''b"
# 0xBF27 must not be escaped here, since it is a valid character in GBK
pg_exec $conn "set client_encoding='GBK'"
assert [pg_escape_bytea $conn "a\u00BF'b"] "a\u00BF'b"

puts "OK"
