# encoding: UTF-8
import pg

#
# no connection
#

assert pg.escape_string('a') == 'a'
# real line breaks are okay
assert pg.escape_string('a\nb') == 'a\nb'
# but backslashes aren't (note that Python notation also needs to escape them)
assert pg.escape_string('a\\nb') == 'a\\\\nb'
# double quotes are not magic in SQL
assert pg.escape_string('a"b') == 'a"b'
# but single quotes are
assert pg.escape_string("a'b") == "a''b"

# this depends on the client encoding; connection-less method does not escape -> unsafe
assert pg.escape_string("\xbf'") == "\xbf''"

assert pg.escape_bytea('a"b') == 'a"b'
assert pg.escape_bytea("a'b") == "a''b"
assert pg.escape_bytea('a\x01\xFFb') == 'a\\\\001\\\\377b'

# XXX: currently fails
#for s in ('a', 'a\nb', 'a\\nb', 'a"b', "a'b", 'a\x01\xFFb'):
#    new = pg.unescape_bytea(pg.escape_bytea(s))
#    orig = s.replace('\n', '\\012') # bytea exclusively uses octal encoding
#    assert orig == new, 'original: »%s«, new: »%s«' % (orig, new)

#
# with connection
#

con = pg.connect('template1')
assert con.escape_string('a') == 'a'
# real line breaks are okay
assert con.escape_string('a\nb') == 'a\nb'
# but backslashes aren't (note that Python notation also needs to escape them)
assert con.escape_string('a\\nb') == 'a\\\\nb'
# double quotes are not magic in SQL
assert con.escape_string('a"b') == 'a"b'
# but single quotes are
assert con.escape_string("a'b") == "a''b"

assert con.escape_bytea('a"b') == 'a"b'
assert con.escape_bytea("a'b") == "a''b"
assert con.escape_bytea("a\x01\xFFb") == "a\\\\001\\\\377b"
    
con.query('set client_encoding="UTF-8"')
# 0xBF27 has to be escaped here, since ' is interpreted as a quote
assert con.escape_string("\xbf'") == "\xbf''"
con.query('set client_encoding="GBK"')
# 0xBF27 must not be escaped here, since it is a valid character in GBK
assert con.escape_string("\xbf'") == "\xbf'"

print 'OK'

