nested hstore
authorTeodor Sigaev <teodor@sigaev.ru>
Fri, 7 Mar 2014 11:57:04 +0000 (15:57 +0400)
committerTeodor Sigaev <teodor@sigaev.ru>
Fri, 7 Mar 2014 11:57:04 +0000 (15:57 +0400)
23 files changed:
Makefile [new file with mode: 0644]
data/hstore.data [new file with mode: 0644]
expected/hstore.out [new file with mode: 0644]
expected/nested.out [new file with mode: 0644]
expected/types.out [new file with mode: 0644]
hstore--1.0--1.1.sql [new file with mode: 0644]
hstore--1.1--1.2.sql [new file with mode: 0644]
hstore--1.2--1.3.sql [new file with mode: 0644]
hstore--1.3.sql [new file with mode: 0644]
hstore--unpackaged--1.0.sql [new file with mode: 0644]
hstore.control [new file with mode: 0644]
hstore.h [new file with mode: 0644]
hstore_compat.c [new file with mode: 0644]
hstore_gin.c [new file with mode: 0644]
hstore_gist.c [new file with mode: 0644]
hstore_gram.y [new file with mode: 0644]
hstore_io.c [new file with mode: 0644]
hstore_op.c [new file with mode: 0644]
hstore_scan.l [new file with mode: 0644]
hstore_support.c [new file with mode: 0644]
sql/hstore.sql [new file with mode: 0644]
sql/nested.sql [new file with mode: 0644]
sql/types.sql [new file with mode: 0644]

diff --git a/Makefile b/Makefile
new file mode 100644 (file)
index 0000000..125a29b
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,35 @@
+# contrib/hstore/Makefile
+
+MODULE_big = hstore
+OBJS = hstore_io.o hstore_op.o hstore_gist.o hstore_gin.o hstore_compat.o \
+       hstore_gram.o hstore_support.o
+
+EXTENSION = hstore
+DATA = hstore--1.3.sql hstore--1.0--1.1.sql hstore--1.1--1.2.sql \
+          hstore--1.2--1.3.sql hstore--unpackaged--1.0.sql
+
+REGRESS = hstore nested types
+
+EXTRA_CLEAN = y.tab.c y.tab.h \
+                               hstore_gram.c hstore_scan.c hstore_gram.h
+
+ifdef USE_PGXS
+PG_CONFIG = pg_config
+PGXS := $(shell $(PG_CONFIG) --pgxs)
+include $(PGXS)
+else
+subdir = contrib/hstore
+top_builddir = ../..
+include $(top_builddir)/src/Makefile.global
+include $(top_srcdir)/contrib/contrib-global.mk
+endif
+
+hstore_gram.o: hstore_scan.c
+
+hstore_gram.c: BISONFLAGS += -d
+
+distprep: hstore_gram.c hstore_scan.c
+
+maintainer-clean:
+       rm -f hstore_gram.c hstore_scan.c hstore_gram.h
+
diff --git a/data/hstore.data b/data/hstore.data
new file mode 100644 (file)
index 0000000..f86f8a2
--- /dev/null
@@ -0,0 +1,1003 @@
+line=>1, date=>CB, node=>AA
+cleaned=>f, status=>59, line=>2, disabled=>f, node=>CBB
+indexed=>t, status=>35, line=>3, disabled=>f, wait=>CAA, subtitle=>BA, user=>CCA
+line=>4, disabled=>t, space=>BB
+cleaned=>f, line=>5, wait=>BB, query=>CAC, coauthors=>ACA, node=>CBA
+world=>CB, query=>CBC, indexed=>f, line=>6, pos=>92, date=>AAB, space=>CB, coauthors=>ACA, node=>CBC
+state=>98, org=>43, line=>7, pos=>97
+auth=>BB, title=>CAC, query=>BA, status=>94, line=>8, coauthors=>BBB
+auth=>BAC, title=>CAA, wait=>CA, bad=>t, query=>AA, indexed=>t, line=>9, pos=>56
+title=>AAC, bad=>t, user=>AAB, query=>AC, line=>10, node=>AB
+world=>CAC, user=>AB, query=>ACA, indexed=>t, line=>11, space=>CB
+line=>12, pos=>72, abstract=>BBA, space=>AAC
+
+world=>CC, query=>AA, line=>14, disabled=>f, date=>CAC, coauthors=>AB
+org=>68, title=>BBB, query=>BAC, line=>15, public=>f
+org=>73, user=>AA, indexed=>t, line=>16, date=>CCC, public=>t, coauthors=>AB
+indexed=>f, line=>17
+state=>23, auth=>BCC, org=>38, status=>28, line=>18, disabled=>f, abstract=>CB
+state=>99, auth=>CA, indexed=>t, line=>19, date=>BA
+wait=>CBA, user=>BBA, indexed=>t, line=>20, disabled=>f, abstract=>BA, date=>ABA
+org=>10, query=>AC, indexed=>f, line=>21, disabled=>t, abstract=>CA, pos=>44
+state=>65, title=>AC, user=>AAC, cleaned=>t, status=>93, line=>22, abstract=>ABC, node=>CCC
+subtitle=>AC, user=>CCC, line=>23
+state=>67, world=>ACB, bad=>t, user=>CB, line=>24, disabled=>t
+
+state=>65, title=>CBC, wait=>AAC, bad=>t, query=>ACA, line=>26, disabled=>f, space=>CA
+auth=>BAA, state=>68, indexed=>t, line=>27, space=>BA
+indexed=>f, line=>28, disabled=>t, space=>CC, node=>BB
+auth=>BAB, org=>80, title=>BBA, query=>BBC, status=>3, line=>29
+title=>AC, status=>16, cleaned=>t, line=>30
+state=>39, world=>AAB, user=>BB, line=>31, disabled=>t
+wait=>BC, bad=>f, query=>AA, line=>32, coauthors=>CAC
+line=>33, pos=>97
+title=>AA, world=>CCA, wait=>CC, bad=>t, status=>86, line=>34, disabled=>t, node=>ACA
+
+world=>BCC, title=>ACB, org=>61, status=>99, cleaned=>t, line=>36, pos=>76, space=>ACC, coauthors=>AA, node=>CB
+title=>CAA, cleaned=>f, line=>37, abstract=>ACA, node=>BC
+auth=>BC, title=>BA, world=>ACA, indexed=>t, line=>38, abstract=>AAA, public=>t
+org=>90, line=>39, public=>f
+state=>16, indexed=>t, line=>40, pos=>53
+auth=>AAB, wait=>CAC, status=>44, line=>41
+subtitle=>ACA, bad=>t, line=>42
+org=>19, world=>BC, user=>ABA, indexed=>f, line=>43, disabled=>t, pos=>48, abstract=>CAB, space=>CCB
+indexed=>f, line=>44
+indexed=>t, line=>45
+status=>84, line=>46, date=>CCC
+state=>94, title=>BAB, bad=>t, user=>BBB, indexed=>t, line=>47, public=>f
+org=>90, subtitle=>BAC, query=>CAC, cleaned=>f, line=>48, disabled=>t, abstract=>CC, pos=>17, space=>BCA
+world=>CBC, line=>49
+org=>24, line=>50, date=>CA, public=>f
+world=>BC, indexed=>t, status=>44, line=>51, pos=>59, date=>BA, public=>t
+org=>98, line=>52
+title=>CA, world=>ABC, subtitle=>CBB, line=>53, abstract=>BBA, date=>ACB, node=>CA
+user=>BAB, cleaned=>t, line=>54
+subtitle=>CAA, line=>55, disabled=>f, pos=>55, abstract=>AB, public=>f, coauthors=>AA
+wait=>CC, user=>CC, cleaned=>t, line=>56, pos=>73, node=>ABC
+title=>BCC, wait=>ABC, indexed=>t, line=>57, disabled=>f
+org=>42, title=>BB, line=>58, disabled=>t, public=>t, coauthors=>BCC
+wait=>CAB, title=>CCB, query=>BAC, status=>66, line=>59, disabled=>t
+user=>CAC, line=>60
+user=>BBB, line=>61, disabled=>f, pos=>31
+org=>18, line=>62, coauthors=>CCC, node=>CA
+line=>63, coauthors=>AB
+org=>25, wait=>CA, line=>64, abstract=>BA, date=>BBB
+title=>CB, wait=>CC, bad=>f, user=>BBB, line=>65, abstract=>ACA, public=>t
+line=>66, coauthors=>AC
+state=>20, wait=>CCB, bad=>t, line=>67, abstract=>CB
+state=>79, wait=>BAC, bad=>f, status=>11, line=>68, abstract=>BC, public=>t, coauthors=>CBA
+state=>39, title=>CCA, bad=>f, query=>BBA, line=>69, pos=>42, public=>f
+title=>BC, subtitle=>CA, query=>BC, line=>70
+
+bad=>t, query=>BBB, line=>72
+state=>35, world=>CC, bad=>f, line=>73, space=>BB, public=>f
+title=>ACC, wait=>CAB, subtitle=>CB, status=>19, line=>74, disabled=>f, space=>BAA, coauthors=>CBC, node=>AC
+subtitle=>BCB, indexed=>f, status=>83, line=>75, public=>t
+state=>32, line=>76, disabled=>f, pos=>66, space=>CC
+state=>43, cleaned=>t, line=>77
+
+state=>97, wait=>CBA, indexed=>f, cleaned=>f, line=>79, abstract=>CB, date=>ACC, public=>f
+user=>AAB, line=>80, pos=>85, date=>AC
+world=>AC, wait=>CC, subtitle=>AAB, bad=>f, cleaned=>f, line=>81, pos=>91, node=>CCC
+
+org=>87, bad=>f, user=>AAC, query=>CCC, line=>83, disabled=>f, abstract=>AC, date=>CCA, public=>f
+state=>50, line=>84
+wait=>AA, subtitle=>AA, query=>BB, status=>97, line=>85, disabled=>t, abstract=>CB
+
+subtitle=>CA, query=>BC, line=>87
+
+title=>CC, line=>89, disabled=>f, pos=>49, date=>CCB, space=>CB, node=>BB
+auth=>CC, wait=>AA, title=>BC, bad=>t, line=>90
+state=>37, org=>85, indexed=>f, line=>91, space=>CAA, public=>t, coauthors=>BA
+wait=>BBB, title=>BBC, org=>95, subtitle=>AC, line=>92, pos=>23, date=>AC, public=>t, space=>BBC
+org=>48, user=>AC, line=>93, space=>CCC
+
+state=>77, wait=>ABA, subtitle=>AC, user=>BA, status=>43, line=>95, public=>f
+title=>CA, indexed=>t, status=>26, line=>96
+auth=>BCA, subtitle=>ACC, user=>CA, line=>97, disabled=>f, node=>ACB
+query=>BB, line=>98, coauthors=>AB
+
+auth=>AA, title=>ACB, org=>58, subtitle=>AC, bad=>f, cleaned=>f, line=>100, space=>ACC, public=>t
+subtitle=>AAB, bad=>f, line=>101, public=>t
+subtitle=>AAA, indexed=>f, cleaned=>f, line=>102, disabled=>t, pos=>35
+
+world=>CAC, org=>10, query=>AAA, cleaned=>t, status=>79, indexed=>t, line=>104, pos=>65, public=>f, node=>BAB
+bad=>f, line=>105, abstract=>BA, node=>CBB
+world=>BB, wait=>BAA, title=>ACA, line=>106, date=>CBC, space=>BA
+state=>92, wait=>CAC, title=>AAA, bad=>f, line=>107, abstract=>CBC, date=>BCC, public=>f
+title=>CCC, indexed=>t, line=>108, abstract=>ACB, public=>f, coauthors=>ABB
+auth=>BB, query=>ACC, status=>68, line=>109
+user=>CC, cleaned=>f, indexed=>t, line=>110, date=>BAA, space=>BCB
+auth=>CC, org=>4, wait=>BAC, bad=>f, indexed=>f, line=>111, pos=>55, node=>BBC
+line=>112, disabled=>t
+org=>66, cleaned=>t, indexed=>f, line=>113, pos=>96
+world=>CA, title=>ACA, org=>83, query=>BAC, user=>BBC, indexed=>f, line=>114
+subtitle=>BCC, line=>115, space=>AA, public=>t, node=>CBA
+state=>77, status=>23, line=>116
+bad=>f, status=>4, line=>117, node=>CC
+state=>99, title=>BCC, query=>AC, status=>98, line=>118, date=>BA
+status=>55, line=>119, public=>f, coauthors=>BBA, node=>BCA
+query=>CAA, status=>40, indexed=>f, line=>120, disabled=>f, coauthors=>CA
+title=>BBC, org=>82, subtitle=>ACB, line=>121, abstract=>BB, node=>CC
+state=>66, world=>AB, subtitle=>BA, query=>CB, line=>122, abstract=>BBC, pos=>65, date=>BAB
+state=>96, title=>CBC, status=>44, line=>123, abstract=>BA, space=>ACA, node=>AAC
+auth=>CA, state=>59, bad=>f, cleaned=>f, line=>124, pos=>41, date=>BBA, coauthors=>ABB
+wait=>ACC, line=>125
+org=>30, wait=>CBB, subtitle=>CCA, cleaned=>t, line=>126, date=>AC, node=>ABC
+
+auth=>BBA, org=>66, subtitle=>CCB, bad=>t, cleaned=>f, line=>128, abstract=>BB, public=>t, coauthors=>BA
+subtitle=>AC, bad=>f, user=>BAA, line=>129, date=>BCB, node=>BAC
+wait=>CC, subtitle=>CA, line=>130, disabled=>f, pos=>49, node=>BA
+indexed=>f, line=>131, pos=>79, date=>AAA, node=>CAC
+wait=>AC, world=>CB, title=>AAA, user=>ABC, indexed=>f, status=>15, line=>132, coauthors=>BA
+state=>96, bad=>t, line=>133, disabled=>f, space=>BAC, coauthors=>ABA
+world=>BAC, line=>134
+title=>CCC, line=>135, coauthors=>CC
+cleaned=>t, line=>136
+bad=>t, query=>CCA, user=>CA, cleaned=>f, line=>137, disabled=>t
+
+world=>CC, subtitle=>BBB, line=>139
+wait=>CA, status=>2, line=>140
+world=>BC, bad=>f, user=>BBC, query=>ACB, line=>141, pos=>33, space=>ACA
+state=>92, title=>CA, bad=>t, query=>AB, line=>142, abstract=>BA, date=>ABB, space=>BC, coauthors=>CAA
+state=>79, query=>AB, user=>CCA, indexed=>t, cleaned=>t, line=>143, public=>t
+org=>37, query=>CA, cleaned=>t, line=>144, disabled=>t, date=>CC
+wait=>AC, title=>CBA, user=>AAA, status=>24, line=>145, date=>CBC, public=>f, coauthors=>BAC, node=>ACC
+user=>CA, indexed=>t, line=>146, disabled=>f, coauthors=>BA
+wait=>BC, org=>35, bad=>f, query=>CBB, line=>147, date=>AAA, public=>f, space=>BBB
+org=>56, user=>AB, indexed=>t, line=>148
+
+title=>CBB, org=>78, subtitle=>CBA, bad=>t, user=>AAB, line=>150, disabled=>t, abstract=>BAC
+world=>CCA, query=>BC, cleaned=>t, indexed=>f, line=>151, abstract=>BC, pos=>43, coauthors=>AB, node=>CBA
+auth=>ABA, status=>13, line=>152, date=>AA
+world=>CA, line=>153, space=>CBC
+world=>BA, user=>BBB, status=>72, line=>154
+auth=>ABB, line=>155, disabled=>t, node=>BBC
+world=>BBB, bad=>f, line=>156, abstract=>CBC
+line=>157, pos=>60, node=>ACC
+line=>158, node=>CC
+line=>159, public=>t
+
+query=>BA, status=>53, cleaned=>f, line=>161, public=>t
+line=>162, date=>CC
+
+title=>BC, bad=>f, query=>CC, line=>164, abstract=>CCB, date=>BA
+status=>36, line=>165
+title=>AB, bad=>f, status=>64, line=>166, abstract=>AB, coauthors=>AA, node=>AA
+wait=>AA, line=>167
+subtitle=>CBC, user=>AC, cleaned=>f, line=>168, disabled=>t, coauthors=>BAB, node=>CC
+state=>34, status=>73, cleaned=>t, line=>169, abstract=>BC, public=>f, space=>BBC, node=>BAA
+state=>10, auth=>BBB, bad=>t, indexed=>f, status=>34, line=>170, abstract=>BC
+subtitle=>AAA, bad=>f, user=>ACA, status=>53, line=>171, disabled=>f, date=>AAA
+subtitle=>CB, query=>CC, indexed=>t, line=>172, node=>BBC
+state=>5, world=>ABC, bad=>f, line=>173, public=>f
+subtitle=>AC, line=>174
+auth=>AC, org=>72, query=>CA, indexed=>f, cleaned=>t, line=>175, disabled=>t, pos=>54
+title=>BCB, bad=>f, line=>176, pos=>35, coauthors=>AAC, node=>ABB
+title=>BB, cleaned=>t, status=>26, line=>177
+state=>61, wait=>BB, world=>CB, query=>BAB, line=>178, abstract=>BB, date=>CBB, space=>CA, node=>AB
+wait=>CA, cleaned=>f, indexed=>t, line=>179, space=>CBC
+org=>68, line=>180
+wait=>ABB, subtitle=>CCC, cleaned=>t, line=>181, abstract=>BC, coauthors=>BA
+title=>ACA, subtitle=>AAB, line=>182, node=>BAC
+
+
+subtitle=>BA, query=>BBB, indexed=>t, cleaned=>t, line=>185, node=>BCC
+org=>6, title=>BCC, user=>BA, line=>186, pos=>67, abstract=>CBA, coauthors=>CBB, node=>CBC
+org=>50, title=>CAB, subtitle=>CB, query=>CBB, line=>187, coauthors=>CA, node=>CC
+bad=>f, line=>188, node=>CCB
+org=>4, world=>AAC, query=>CAC, line=>189, pos=>90, node=>AC
+state=>86, line=>190, pos=>79
+org=>98, title=>AAC, cleaned=>t, line=>191, space=>BC, coauthors=>AA
+wait=>CAA, bad=>f, user=>BC, status=>23, line=>192, disabled=>t, date=>CA, coauthors=>BBB
+status=>26, line=>193, disabled=>t
+world=>CA, subtitle=>CCC, query=>ABB, status=>86, line=>194, pos=>97, space=>CAC
+cleaned=>t, line=>195
+state=>53, org=>84, wait=>BC, query=>BCC, line=>196, disabled=>t, abstract=>AAC, node=>CAC
+state=>25, status=>70, cleaned=>f, line=>197, disabled=>t, space=>AA, public=>f
+org=>82, subtitle=>AAC, line=>198
+org=>87, bad=>t, status=>69, line=>199, public=>f
+wait=>CC, org=>60, subtitle=>BCA, bad=>t, cleaned=>f, indexed=>t, line=>200, date=>BA
+state=>9, world=>CAA, org=>78, user=>ACB, cleaned=>t, line=>201, disabled=>t, abstract=>ACC, public=>f
+state=>50, world=>AAA, title=>CAA, user=>AB, status=>37, line=>202, disabled=>f
+org=>36, subtitle=>CB, query=>BAA, status=>35, line=>203, abstract=>CC
+auth=>CCC, bad=>t, query=>CB, status=>84, line=>204, disabled=>f, date=>BB
+auth=>AC, query=>BA, indexed=>f, line=>205, date=>AAB, space=>ABB
+state=>30, world=>CCA, query=>CC, user=>BAA, line=>206
+title=>CAB, wait=>BAB, bad=>t, query=>BCB, indexed=>t, status=>48, cleaned=>t, line=>207, node=>ACB
+state=>97, subtitle=>BC, status=>99, line=>208, abstract=>CB
+title=>CA, world=>BBA, bad=>t, indexed=>f, cleaned=>f, status=>82, line=>209, disabled=>f, pos=>44, space=>ACA
+line=>210, public=>t
+line=>211, space=>BBC, node=>AAA
+wait=>BAA, org=>50, line=>212, abstract=>BB, public=>t, space=>AB
+line=>213, pos=>57, date=>CC, space=>AC
+state=>23, user=>BAB, query=>BCB, line=>214, abstract=>BAB
+world=>ACB, org=>21, line=>215, abstract=>AC, public=>f
+state=>14, wait=>ACB, org=>79, title=>BB, subtitle=>BA, line=>216
+wait=>BC, line=>217, date=>BB
+wait=>AC, user=>BB, indexed=>f, status=>83, line=>218
+auth=>BC, org=>9, user=>BA, status=>31, line=>219, disabled=>f
+state=>80, world=>BA, wait=>CA, line=>220, pos=>65, node=>CAC
+wait=>AC, subtitle=>ABB, status=>79, indexed=>t, line=>221, abstract=>AC, pos=>33, space=>BA
+state=>69, org=>83, world=>CBC, subtitle=>CAC, cleaned=>f, line=>222, space=>BC, node=>CCA
+line=>223, abstract=>BC
+
+world=>BB, title=>BC, bad=>f, query=>BBC, cleaned=>f, line=>225, disabled=>f, public=>t
+line=>226, date=>AC
+auth=>CB, subtitle=>AB, indexed=>f, status=>2, line=>227, pos=>53, space=>AB, coauthors=>BCA
+title=>ABA, org=>36, line=>228, space=>AA
+world=>AB, line=>229, pos=>78, date=>BC, space=>CC
+wait=>BBC, org=>47, cleaned=>t, status=>5, line=>230, pos=>2, date=>CCA
+line=>231, coauthors=>CB
+state=>1, user=>CAA, cleaned=>f, line=>232, date=>BA, public=>t, coauthors=>AAA, node=>BCC
+auth=>AB, world=>CAC, query=>BC, cleaned=>t, line=>233, pos=>47, space=>AB, node=>AB
+title=>CAA, line=>234, pos=>9, public=>t, node=>AB
+auth=>CCA, title=>AA, org=>6, subtitle=>CA, cleaned=>t, status=>12, indexed=>f, line=>235, space=>ABB
+auth=>CA, bad=>f, query=>BC, status=>61, cleaned=>f, line=>236, disabled=>t, public=>t
+user=>BCB, line=>237, pos=>70, node=>CBA
+query=>CCB, line=>238, disabled=>t, coauthors=>BAB, node=>BC
+auth=>AC, org=>73, title=>CA, bad=>f, status=>94, line=>239, abstract=>CC
+subtitle=>BC, indexed=>f, line=>240, disabled=>t
+auth=>AAC, org=>73, title=>CB, bad=>t, query=>CA, cleaned=>t, line=>241, disabled=>f, public=>f
+line=>242, public=>f
+auth=>AC, title=>BC, status=>61, line=>243, disabled=>f
+auth=>ABB, bad=>f, indexed=>f, line=>244, abstract=>BAB, date=>ABC, coauthors=>BC
+query=>BA, line=>245, disabled=>f, space=>BAB
+world=>BCC, bad=>f, indexed=>f, line=>246, disabled=>t, pos=>80, public=>f, coauthors=>BC
+indexed=>t, line=>247
+wait=>CCA, subtitle=>CBB, bad=>f, line=>248, pos=>83, public=>f, space=>BA
+
+auth=>ABA, org=>13, title=>BA, bad=>f, indexed=>t, line=>250, disabled=>f, abstract=>BBA, date=>AB
+state=>37, title=>AAA, bad=>f, line=>251, disabled=>f, coauthors=>CBC
+auth=>ACB, world=>AC, title=>CAA, subtitle=>BCA, bad=>f, status=>32, line=>252, pos=>84
+query=>BA, indexed=>f, status=>0, line=>253, abstract=>CCB, pos=>48, date=>AC, space=>AAC
+subtitle=>BBA, line=>254, node=>AAA
+query=>AC, user=>CAA, status=>13, line=>255, public=>t, coauthors=>BCC
+auth=>AAA, state=>31, line=>256
+
+
+wait=>AC, query=>AAA, cleaned=>t, indexed=>f, line=>259, pos=>89, coauthors=>BCA, node=>BC
+world=>CC, query=>BB, line=>260
+
+org=>99, bad=>f, user=>ABA, line=>262, abstract=>BA, coauthors=>BCC
+auth=>CAC, world=>CBC, subtitle=>CA, bad=>f, status=>22, line=>263, pos=>4, public=>t, node=>BB
+wait=>BB, subtitle=>BCC, indexed=>t, line=>264, node=>CAC
+subtitle=>BB, query=>CBB, line=>265
+state=>35, query=>AA, line=>266, coauthors=>AAA
+status=>6, line=>267, pos=>66
+auth=>BAA, subtitle=>CCA, bad=>f, query=>CCB, line=>268, public=>t, space=>CAB, node=>CAC
+world=>AC, org=>58, user=>AC, line=>269, node=>AB
+auth=>BCB, org=>36, title=>AB, line=>270, abstract=>CAB, date=>CAB, public=>t, coauthors=>CB, node=>AB
+cleaned=>t, line=>271
+world=>ACC, cleaned=>t, status=>11, line=>272, disabled=>f, abstract=>AA, space=>BCA, node=>BA
+cleaned=>t, line=>273, pos=>50, public=>t
+status=>95, line=>274, abstract=>BB, coauthors=>AC
+auth=>BCC, state=>80, cleaned=>t, line=>275, abstract=>AC
+wait=>BA, line=>276
+org=>62, subtitle=>CAA, query=>BA, user=>BCC, indexed=>f, line=>277, disabled=>f, abstract=>ACA, date=>AB
+org=>63, bad=>t, line=>278, pos=>26, coauthors=>BA
+auth=>CBB, indexed=>f, line=>279, pos=>40, space=>CA, coauthors=>CC
+auth=>BA, line=>280, abstract=>AAA, public=>t, coauthors=>CAC
+org=>10, status=>16, line=>281, date=>CCC, space=>AC
+org=>76, user=>BBC, indexed=>f, line=>282, pos=>56, node=>CBA
+auth=>CA, subtitle=>AB, query=>AA, indexed=>t, line=>283, disabled=>f, coauthors=>ABC, node=>CAA
+title=>BA, status=>91, line=>284, pos=>7, coauthors=>BB
+wait=>CCA, line=>285, public=>t
+world=>AC, line=>286, disabled=>t
+line=>287, abstract=>AAA
+user=>CCB, status=>50, line=>288, public=>f
+state=>41, world=>CCC, query=>AA, line=>289, disabled=>t, pos=>49, public=>f
+wait=>CBC, line=>290, abstract=>CCA, space=>BBC
+auth=>CCB, world=>BAB, user=>CCC, status=>93, line=>291, pos=>77, node=>BAC
+wait=>BCC, org=>8, user=>AC, cleaned=>t, line=>292, disabled=>t, pos=>67, date=>AA
+org=>56, query=>BCA, line=>293, pos=>81, coauthors=>AAA, node=>CAB
+world=>CB, subtitle=>CBC, bad=>t, query=>ACB, indexed=>f, line=>294, pos=>58, date=>BC, node=>CB
+wait=>BC, user=>CA, line=>295
+world=>ABA, wait=>BA, user=>BB, status=>65, line=>296, pos=>45, date=>BB
+
+
+auth=>BA, user=>AA, indexed=>f, line=>299, space=>ABA, public=>f, coauthors=>BC
+line=>300, space=>ABA
+state=>36, org=>16, world=>BBC, status=>13, line=>301, public=>f
+subtitle=>CB, user=>BC, line=>302, date=>AA, coauthors=>CAC
+wait=>CBC, indexed=>t, cleaned=>t, line=>303, date=>ACC, public=>t
+user=>CAC, status=>81, line=>304, node=>CAB
+title=>CBB, org=>89, subtitle=>CAA, user=>CCA, indexed=>t, line=>305
+state=>10, title=>CBA, org=>66, cleaned=>t, line=>306, pos=>59, coauthors=>CAC
+
+auth=>AAA, world=>AC, wait=>ACA, subtitle=>BAA, status=>64, line=>308, node=>CCA
+state=>31, world=>CCC, title=>BCB, cleaned=>f, status=>11, line=>309, disabled=>t, date=>AA
+title=>BC, subtitle=>CB, indexed=>f, line=>310, disabled=>t, abstract=>BA, space=>ACA
+wait=>ABB, cleaned=>t, indexed=>f, line=>311, space=>CAB
+
+subtitle=>CA, line=>313
+org=>91, title=>CAB, line=>314, date=>CA
+
+state=>65, line=>316, node=>CC
+line=>317, space=>AA
+
+wait=>AA, indexed=>t, line=>319
+wait=>BB, org=>42, world=>AC, subtitle=>ACC, indexed=>t, line=>320, disabled=>t
+
+auth=>CAC, line=>322
+
+line=>324, pos=>38, space=>CC, node=>BBC
+title=>CC, line=>325, public=>t, coauthors=>BAC, node=>ACC
+world=>CC, subtitle=>BBC, bad=>f, user=>BA, line=>326, date=>AAA, space=>AA
+state=>81, title=>BC, wait=>BA, indexed=>f, status=>48, line=>327, coauthors=>AB
+line=>328, space=>ABB
+line=>329, date=>CCA
+
+auth=>BB, world=>BAB, subtitle=>BA, query=>ABB, line=>331, disabled=>t, date=>AAA, node=>BC
+auth=>ABA, title=>CC, user=>CBA, line=>332, disabled=>t, space=>ACC
+org=>98, subtitle=>ACB, line=>333, abstract=>BC, public=>f, coauthors=>BC, node=>ABA
+
+world=>BC, subtitle=>BAC, user=>AB, query=>BAA, cleaned=>t, line=>335, space=>AC, node=>BAA
+state=>76, indexed=>t, cleaned=>f, line=>336, node=>CAC
+org=>95, status=>84, line=>337
+
+world=>BBA, title=>BCC, subtitle=>ACB, query=>BA, line=>339, space=>ABC, node=>AC
+title=>CBB, user=>CBA, cleaned=>t, line=>340, public=>t, space=>CB, coauthors=>CAB
+wait=>AA, status=>82, line=>341
+world=>CC, line=>342
+auth=>BAB, title=>CAC, query=>BCC, indexed=>t, line=>343
+org=>77, world=>BAC, subtitle=>AA, user=>ABA, line=>344
+state=>99, org=>56, world=>CC, title=>CAB, wait=>CB, subtitle=>BCC, line=>345, pos=>65
+state=>68, org=>97, title=>AA, indexed=>t, line=>346, node=>CC
+state=>3, title=>CBC, user=>BAA, status=>98, line=>347, disabled=>t, pos=>96, date=>BBA
+auth=>BAA, world=>ABB, line=>348, disabled=>f, abstract=>ACA, pos=>66, space=>CCC, coauthors=>CBB, node=>BC
+
+status=>54, line=>350
+wait=>CC, query=>ABA, user=>AB, status=>76, cleaned=>f, line=>351, abstract=>CBA
+line=>352, disabled=>t, public=>f
+state=>93, org=>92, status=>88, line=>353, space=>AB, coauthors=>CB
+org=>34, wait=>ABC, world=>CBA, bad=>f, query=>BB, indexed=>f, line=>354, date=>CB, public=>t
+wait=>CBA, title=>CAC, cleaned=>t, indexed=>t, line=>355, pos=>9, date=>CAA
+user=>BC, indexed=>f, cleaned=>t, status=>73, line=>356, disabled=>t, space=>CB
+state=>20, cleaned=>f, line=>357, pos=>28, abstract=>CCB, space=>BC
+state=>17, wait=>ABC, query=>CB, cleaned=>f, status=>4, line=>358, disabled=>f
+
+state=>83, world=>CC, org=>53, cleaned=>f, status=>64, line=>360, abstract=>CBC, coauthors=>BC
+title=>BB, indexed=>f, line=>361
+state=>49, wait=>BCA, line=>362
+world=>CCC, title=>CA, query=>CCC, cleaned=>t, line=>363, space=>AA, coauthors=>AAC
+state=>8, wait=>BBB, line=>364, pos=>70, public=>f, space=>BAA, coauthors=>AB
+state=>20, indexed=>f, status=>87, cleaned=>t, line=>365, public=>t
+
+state=>92, title=>CCC, subtitle=>CAB, status=>39, line=>367
+state=>54, org=>38, line=>368
+
+auth=>ACA, subtitle=>CBC, status=>52, line=>370, date=>ACC, public=>t
+indexed=>t, line=>371, pos=>98, node=>CBA
+world=>BA, status=>40, line=>372, coauthors=>AA
+
+query=>BA, indexed=>f, cleaned=>t, line=>374, date=>BCC
+query=>CA, indexed=>t, line=>375, public=>f
+auth=>CCA, wait=>BBC, bad=>f, status=>91, line=>376, abstract=>BBC, date=>ABA
+user=>BA, query=>CB, status=>86, indexed=>f, line=>377, pos=>83, abstract=>BCC, space=>CBC, public=>t
+title=>ACA, org=>15, wait=>CBC, status=>85, line=>378
+state=>57, bad=>t, line=>379, abstract=>BC, date=>CAC
+world=>CC, cleaned=>t, line=>380
+title=>CB, subtitle=>AC, line=>381, public=>f
+
+
+status=>12, line=>384, coauthors=>CC
+auth=>BAC, bad=>f, line=>385, abstract=>CBB, public=>f, space=>BBC
+
+
+world=>BBC, bad=>t, status=>71, cleaned=>f, line=>388, node=>BB
+cleaned=>f, line=>389
+state=>73, line=>390
+wait=>BB, org=>5, subtitle=>BAA, bad=>f, indexed=>f, line=>391, public=>f, node=>BAA
+auth=>CCC, org=>51, bad=>f, cleaned=>t, line=>392, space=>AC, node=>CC
+
+line=>394, abstract=>ACC, public=>t
+org=>44, subtitle=>BAC, query=>BAC, line=>395
+wait=>BC, line=>396
+state=>68, world=>AB, title=>ABB, user=>CBC, cleaned=>f, indexed=>t, line=>397, abstract=>BA, pos=>11
+world=>CA, title=>AB, subtitle=>BC, user=>BCB, line=>398
+bad=>t, query=>BCC, line=>399
+wait=>BB, user=>BB, cleaned=>t, indexed=>f, line=>400, date=>BC, public=>f
+
+wait=>BA, line=>402
+title=>AC, subtitle=>BCB, query=>BA, line=>403
+
+auth=>BA, org=>19, query=>CCB, line=>405, pos=>82, date=>CAA
+state=>26, world=>CB, subtitle=>AB, cleaned=>f, line=>406, disabled=>t, date=>AC
+
+state=>11, bad=>t, indexed=>t, line=>408, pos=>79, abstract=>BA, date=>CB, space=>BBA
+auth=>AC, status=>59, line=>409
+org=>15, line=>410, disabled=>t, date=>BAC, space=>CCA
+
+
+state=>65, world=>AB, status=>69, line=>413, space=>BA
+
+title=>CCB, line=>415
+title=>BAB, subtitle=>CA, indexed=>f, line=>416, public=>t
+wait=>CAB, user=>CAB, cleaned=>t, line=>417, date=>BC, coauthors=>BBA
+subtitle=>ABA, user=>BB, query=>AA, indexed=>t, line=>418, pos=>8, space=>BB, coauthors=>CBA
+state=>11, indexed=>t, line=>419, node=>AA
+state=>86, cleaned=>f, line=>420, pos=>2, node=>CBC
+org=>73, line=>421, disabled=>f
+query=>BAC, user=>CB, status=>69, line=>422
+status=>22, line=>423
+auth=>CB, wait=>CCA, world=>AAB, line=>424, disabled=>f, space=>BA, public=>f
+state=>81, world=>AC, subtitle=>CBA, bad=>t, cleaned=>f, indexed=>t, line=>425, date=>AAB, coauthors=>BC, node=>BAC
+wait=>CB, query=>BCC, status=>97, line=>426
+org=>47, query=>CB, cleaned=>t, line=>427, date=>CC
+org=>33, query=>AC, status=>48, indexed=>f, line=>428, disabled=>t, abstract=>BC, space=>ACC
+org=>10, query=>AB, line=>429, pos=>77, date=>BC
+line=>430, pos=>7, abstract=>CCA, space=>AA
+bad=>f, user=>CA, query=>CAB, line=>431, node=>AC
+auth=>CA, bad=>f, line=>432
+
+auth=>BAA, org=>98, title=>CCC, world=>BAC, line=>434, public=>t
+state=>54, wait=>AA, user=>BBA, indexed=>f, line=>435, disabled=>t, pos=>12, space=>AB
+world=>AC, title=>CA, query=>AAA, line=>436, space=>AB, coauthors=>AA
+auth=>CB, wait=>CCC, bad=>f, line=>437, pos=>42, date=>ABC, space=>AB, coauthors=>ABC
+auth=>CBB, title=>BB, query=>CB, line=>438, pos=>15, abstract=>BC, node=>BBB
+title=>CC, line=>439, disabled=>f
+title=>AB, line=>440, disabled=>f
+org=>3, bad=>t, user=>BCB, query=>AB, indexed=>f, cleaned=>t, line=>441, disabled=>f, space=>BA, node=>BB
+state=>62, user=>BCC, status=>12, line=>442, pos=>58, date=>CC, node=>CB
+world=>BCB, bad=>t, line=>443, space=>AAB
+state=>56, bad=>f, cleaned=>f, line=>444, disabled=>f, date=>CA, space=>BBB, public=>t
+
+org=>31, world=>ABC, cleaned=>t, line=>446, disabled=>t, public=>t, coauthors=>CB
+state=>54, indexed=>t, line=>447
+state=>98, title=>AC, wait=>AAC, world=>BC, bad=>f, line=>448, disabled=>t, public=>t, node=>ABB
+world=>AAC, indexed=>t, line=>449, disabled=>t, pos=>61
+org=>56, title=>CA, line=>450
+auth=>BBB, line=>451, pos=>58, date=>BB, space=>ABA
+auth=>AB, world=>CA, cleaned=>t, line=>452
+bad=>t, line=>453, disabled=>t, abstract=>AC, pos=>20, date=>ABB, node=>CAB
+
+state=>91, wait=>AC, org=>96, world=>AA, subtitle=>BBC, query=>AA, cleaned=>t, line=>455, public=>f
+status=>99, line=>456, disabled=>t
+org=>86, line=>457, public=>t, coauthors=>AC
+status=>14, cleaned=>t, line=>458, disabled=>t
+world=>AB, user=>CB, query=>AAB, line=>459, pos=>66, public=>f, node=>BBA
+state=>58, world=>BB, wait=>CBA, title=>BCA, line=>460, pos=>95, abstract=>CCA, space=>BC, coauthors=>CB
+
+auth=>CAC, title=>AB, query=>BBA, user=>CB, line=>462, abstract=>BCC, pos=>89, coauthors=>ABB
+org=>13, bad=>f, query=>AA, status=>49, line=>463, disabled=>f
+bad=>t, cleaned=>f, line=>464, coauthors=>BB
+org=>14, query=>BA, line=>465, pos=>25, abstract=>BBA, space=>AAA, node=>CAC
+org=>63, title=>CA, subtitle=>ACC, query=>BAC, status=>76, line=>466, abstract=>ACA
+wait=>BA, subtitle=>BC, line=>467, disabled=>f, abstract=>AC
+org=>76, title=>CA, query=>AB, line=>468, public=>f
+state=>95, world=>AC, bad=>f, status=>65, cleaned=>f, line=>469, disabled=>f
+wait=>AB, subtitle=>AA, bad=>f, user=>CC, query=>BBC, status=>6, line=>470, date=>CCC
+state=>82, bad=>t, indexed=>t, line=>471, date=>BB, coauthors=>AAA
+
+state=>12, auth=>ACB, world=>CBC, bad=>f, indexed=>t, line=>473, date=>CA, space=>ABB, coauthors=>CC
+subtitle=>AA, bad=>f, user=>ACC, line=>474, pos=>86, abstract=>CAC, space=>BBA
+cleaned=>t, line=>475
+title=>CC, wait=>BB, status=>6, line=>476, abstract=>ACC, date=>CB, space=>BA, public=>t
+state=>96, wait=>BA, org=>30, subtitle=>BB, user=>CBB, status=>19, line=>477
+state=>78, org=>99, title=>CC, line=>478, node=>BAB
+world=>CBC, bad=>f, line=>479, date=>ACB, public=>t, node=>CB
+state=>0, query=>ABC, status=>65, line=>480, disabled=>t, space=>CBA, node=>BA
+auth=>BAC, org=>24, subtitle=>BBC, bad=>f, user=>CAC, line=>481, date=>BBB, public=>t, coauthors=>CBA
+org=>18, bad=>t, cleaned=>f, status=>3, indexed=>t, line=>482, date=>BB, coauthors=>ACC
+wait=>CB, user=>AC, line=>483, disabled=>f
+world=>AC, subtitle=>AA, query=>AAB, line=>484, disabled=>t, space=>CAA
+line=>485, pos=>2, space=>CA
+org=>42, indexed=>f, line=>486, date=>CB
+org=>3, wait=>CAA, subtitle=>CA, cleaned=>t, line=>487, disabled=>t
+org=>68, subtitle=>CCB, query=>CAA, cleaned=>f, status=>46, line=>488, pos=>87, public=>f, node=>BC
+
+status=>60, cleaned=>f, line=>490, space=>CC, node=>BCB
+state=>42, org=>9, subtitle=>CBA, user=>BA, status=>96, line=>491, pos=>36
+state=>16, title=>BCC, user=>ABC, indexed=>f, status=>24, line=>492, disabled=>t, node=>CBC
+auth=>CC, wait=>BBB, line=>493, disabled=>f, public=>f, coauthors=>AB
+
+wait=>BB, title=>BBC, subtitle=>BA, status=>3, cleaned=>f, line=>495, disabled=>f, coauthors=>AB, node=>BAC
+
+query=>CC, indexed=>f, line=>497, coauthors=>CAC, node=>BC
+auth=>BBA, state=>68, line=>498
+state=>21, title=>CCB, wait=>AAA, subtitle=>CCC, user=>BAA, indexed=>t, line=>499, coauthors=>BB
+auth=>AAA, subtitle=>CC, bad=>t, user=>CC, indexed=>t, line=>500, disabled=>t, date=>AB, node=>AC
+auth=>BB, title=>CCA, user=>BA, cleaned=>t, line=>501, pos=>37, space=>BA, public=>f
+auth=>BCA, line=>502, date=>BA
+world=>ABA, bad=>t, indexed=>f, line=>503, disabled=>t, abstract=>AC, pos=>1, public=>f
+auth=>BBB, subtitle=>ACB, line=>504, space=>AC, node=>BB
+auth=>CAC, state=>19, title=>ACA, wait=>BA, query=>CC, line=>505
+subtitle=>BC, cleaned=>f, indexed=>f, line=>506, date=>CAB, public=>f, node=>ABC
+state=>87, wait=>CCC, query=>CAC, user=>CBB, line=>507, abstract=>BBC, date=>AA, coauthors=>CA
+auth=>AC, subtitle=>BC, bad=>f, query=>ABA, user=>CBB, indexed=>t, cleaned=>f, line=>508, coauthors=>BA
+auth=>AA, title=>ABA, subtitle=>CCA, query=>CC, line=>509, pos=>27, node=>CBB
+org=>5, title=>CAC, subtitle=>BBB, line=>510, pos=>76, abstract=>AAB, space=>AA
+bad=>t, line=>511
+wait=>ACB, indexed=>f, line=>512
+auth=>CBA, world=>BA, bad=>t, user=>CBA, query=>CC, line=>513, public=>f, coauthors=>CC
+
+state=>97, wait=>BB, line=>515, date=>CBC, space=>CA
+auth=>CBC, line=>516, disabled=>t
+state=>91, user=>CCA, line=>517, coauthors=>BA, node=>CBA
+bad=>f, cleaned=>t, line=>518, space=>AAB
+
+title=>CA, cleaned=>f, status=>38, line=>520
+auth=>BCA, world=>AC, org=>71, user=>CA, line=>521, abstract=>AAB
+bad=>t, line=>522, pos=>28, abstract=>BAA
+line=>523, coauthors=>CBC, node=>AAB
+status=>51, cleaned=>f, line=>524
+query=>AAB, line=>525, disabled=>t, date=>AA, public=>t, coauthors=>CA
+org=>15, user=>AC, cleaned=>f, line=>526, coauthors=>CAC, node=>BAB
+world=>ABA, line=>527, disabled=>t, public=>t
+auth=>BBC, state=>48, bad=>f, line=>528, abstract=>BB, date=>BAC, space=>BA, public=>t
+auth=>BA, wait=>CAC, subtitle=>ABC, query=>CB, indexed=>f, cleaned=>f, line=>529, disabled=>t, date=>CA
+wait=>AC, world=>ABA, org=>55, bad=>t, indexed=>t, line=>530, pos=>32, space=>BCA, public=>t
+title=>CBC, wait=>BAA, line=>531
+world=>AA, line=>532, pos=>35, space=>AAB, public=>t
+line=>533, space=>AB, coauthors=>BA
+auth=>CBC, world=>BB, line=>534, space=>ACA, coauthors=>CBB
+wait=>ACA, status=>47, line=>535, public=>t, node=>BAA
+org=>16, subtitle=>BBB, line=>536, abstract=>AC, space=>CB, coauthors=>CC, node=>CBC
+wait=>AAB, line=>537, abstract=>AB, space=>CAC
+query=>CAC, line=>538
+world=>AC, query=>AAA, indexed=>f, status=>18, line=>539, pos=>62, space=>BC, coauthors=>BAC
+org=>30, world=>AA, query=>BC, user=>BAC, status=>12, cleaned=>t, line=>540, space=>AB
+org=>30, user=>CCB, query=>BB, cleaned=>f, line=>541, disabled=>t, public=>t, node=>CBA
+
+subtitle=>ABB, bad=>t, line=>543
+subtitle=>BBB, bad=>t, line=>544, pos=>43, coauthors=>ABB
+
+subtitle=>AB, user=>BA, line=>546, node=>CB
+title=>BBB, user=>AA, line=>547, abstract=>CBB, pos=>45
+wait=>CCB, title=>AC, world=>AAA, line=>548, abstract=>BBC, pos=>23, coauthors=>ACC
+org=>55, subtitle=>BA, line=>549, disabled=>t, date=>CB, space=>AA
+org=>39, cleaned=>t, line=>550, public=>f
+state=>41, auth=>CC, world=>CB, line=>551, space=>AAB
+
+state=>26, bad=>f, query=>BAA, status=>84, indexed=>t, line=>553, disabled=>f, coauthors=>CC, node=>CBB
+world=>ABA, user=>CCC, query=>ABB, line=>554, space=>ABC, node=>AAA
+state=>18, wait=>CCB, bad=>t, user=>BA, line=>555, space=>CC, coauthors=>BB, node=>BBB
+auth=>AA, state=>71, subtitle=>AA, query=>ACC, indexed=>t, line=>556, space=>BAB, public=>f
+indexed=>t, cleaned=>t, line=>557, disabled=>f, abstract=>AB
+auth=>BCC, title=>ACB, world=>BCA, user=>BAB, cleaned=>f, line=>558, space=>BB, coauthors=>CBC
+
+auth=>ACC, org=>18, wait=>AB, status=>1, indexed=>t, line=>560
+status=>8, line=>561, abstract=>BA, public=>f
+state=>27, title=>ABA, bad=>t, query=>AAB, indexed=>f, line=>562, pos=>86, public=>t, coauthors=>BA
+
+title=>BAC, wait=>CCC, user=>BA, line=>564, disabled=>f, date=>BB, public=>t, space=>CB, coauthors=>CCB
+wait=>CAA, line=>565, pos=>80, space=>AB
+auth=>CBB, subtitle=>BCA, user=>CB, line=>566, abstract=>BC, date=>AB
+title=>CCB, status=>78, line=>567, pos=>68, node=>BA
+auth=>BC, query=>AB, line=>568, space=>AB, node=>BB
+
+line=>570, pos=>54
+world=>BBB, user=>CC, indexed=>t, line=>571, abstract=>CC, coauthors=>BA, node=>ABB
+state=>41, line=>572
+subtitle=>CBC, cleaned=>t, line=>573, node=>BCB
+title=>ABA, line=>574, pos=>27, space=>CC
+status=>29, indexed=>f, cleaned=>f, line=>575, pos=>52, public=>f, coauthors=>ACC
+title=>BBB, org=>86, wait=>AAA, user=>CC, query=>CA, line=>576, disabled=>f, date=>AB, node=>BC
+line=>577, abstract=>CAA, date=>BB
+auth=>CCC, subtitle=>BBB, query=>ABA, line=>578, pos=>99, space=>CCB, public=>t, coauthors=>ACA, node=>ACB
+wait=>BCC, line=>579
+state=>99, world=>BAC, user=>CA, line=>580
+state=>55, world=>AAA, title=>AAA, cleaned=>f, line=>581, date=>AC, public=>t, node=>AA
+query=>ACC, cleaned=>t, line=>582, disabled=>f
+auth=>AAB, query=>BAC, line=>583
+auth=>AA, user=>BAC, line=>584
+
+org=>96, wait=>BC, bad=>f, cleaned=>f, status=>96, line=>586, pos=>95
+auth=>BC, subtitle=>BCB, bad=>t, user=>BBC, line=>587, pos=>79, node=>BA
+state=>55, line=>588
+title=>ABC, world=>AB, subtitle=>CBC, user=>BA, query=>BAB, line=>589, date=>AC, node=>CB
+world=>BAA, bad=>f, user=>AAB, cleaned=>f, indexed=>f, line=>590
+title=>CB, wait=>BC, subtitle=>BAC, cleaned=>t, line=>591, disabled=>f, abstract=>CBB, public=>f, node=>ACC
+user=>BC, line=>592, public=>f
+
+wait=>CC, org=>57, title=>BAC, line=>594, abstract=>AA
+auth=>BBC, state=>3, world=>AAC, query=>BA, line=>595, coauthors=>BB
+
+subtitle=>CC, user=>CC, line=>597
+wait=>BBA, user=>AAA, line=>598, space=>ACB, node=>AA
+auth=>BB, user=>ABA, line=>599, abstract=>AB, node=>BA
+
+world=>AAA, user=>BB, cleaned=>f, line=>601, space=>AC, coauthors=>ABB
+title=>CAB, bad=>f, line=>602, coauthors=>ABB
+
+world=>CCC, org=>79, line=>604
+org=>56, query=>AB, cleaned=>t, indexed=>t, status=>20, line=>605, public=>t, coauthors=>ACA
+auth=>BBC, org=>13, subtitle=>CC, bad=>t, user=>ABC, line=>606, date=>CA, public=>f
+query=>BA, line=>607
+bad=>t, line=>608, pos=>12, coauthors=>CB
+bad=>f, status=>42, line=>609
+
+bad=>t, line=>611
+auth=>CCA, subtitle=>BC, bad=>t, query=>CAA, cleaned=>f, line=>612, public=>f, node=>CBA
+org=>65, query=>BC, line=>613
+
+wait=>BAC, title=>AAB, user=>CAC, line=>615, pos=>69, space=>CC, node=>AAC
+bad=>f, line=>616, abstract=>AB, pos=>65, coauthors=>BBB
+
+org=>38, world=>BA, line=>618, coauthors=>AA, node=>BC
+cleaned=>f, line=>619, disabled=>f
+auth=>BC, line=>620, pos=>79, date=>AB, coauthors=>BAA, node=>CB
+auth=>CAA, title=>CB, user=>BAC, cleaned=>f, line=>621, public=>f, space=>CBA
+
+bad=>f, status=>12, line=>623
+auth=>BBB, wait=>BAC, org=>36, title=>AB, indexed=>f, cleaned=>f, line=>624, date=>AB, coauthors=>CB
+wait=>AA, subtitle=>AB, query=>CCB, line=>625, node=>CBB
+wait=>BC, subtitle=>BA, bad=>t, user=>AA, line=>626, pos=>3, date=>BB
+org=>28, user=>BC, query=>AC, status=>63, line=>627, pos=>45, public=>t, node=>BC
+query=>BC, status=>47, line=>628, disabled=>f, date=>CA, public=>f
+
+wait=>CB, line=>630, pos=>67, coauthors=>AC
+org=>33, world=>BBB, query=>BB, status=>92, line=>631
+state=>65, title=>AC, world=>CBC, query=>CBC, line=>632, date=>CAC, space=>CC, coauthors=>CC
+
+auth=>CC, query=>BCA, status=>46, line=>634, disabled=>f, pos=>69
+wait=>CB, line=>635, pos=>34
+state=>9, wait=>CC, status=>23, line=>636, disabled=>t, date=>BB, space=>AC
+user=>CCB, indexed=>f, cleaned=>t, line=>637, pos=>65, date=>AA, public=>t
+auth=>BC, wait=>AB, title=>BB, bad=>t, line=>638, abstract=>ACC, date=>BC, public=>f
+state=>44, auth=>BC, world=>CBC, line=>639, disabled=>f, date=>CAA
+world=>CB, title=>ACB, user=>BA, query=>AA, line=>640, disabled=>t, space=>AC
+state=>37, line=>641, disabled=>t, pos=>66
+world=>AAA, bad=>t, user=>AAA, query=>BA, line=>642, disabled=>t, coauthors=>CBC
+world=>BA, title=>ABB, org=>96, bad=>f, query=>AAA, status=>75, cleaned=>f, line=>643, space=>BA
+state=>36, org=>66, subtitle=>AA, query=>CA, cleaned=>t, status=>79, line=>644, date=>CB
+wait=>BC, line=>645, date=>CBA, space=>BCB, public=>t, node=>ABA
+auth=>BB, org=>37, query=>CAA, indexed=>t, line=>646, abstract=>CBA, coauthors=>CBA
+
+
+state=>58, world=>BAB, org=>11, user=>CC, line=>649
+title=>CB, status=>19, line=>650, disabled=>f, public=>f, coauthors=>AA
+user=>BBC, indexed=>t, line=>651, disabled=>t, pos=>8
+query=>CC, cleaned=>t, indexed=>f, line=>652, pos=>67, date=>AA
+auth=>AAC, line=>653, disabled=>t, public=>f, coauthors=>AAA, node=>CBB
+bad=>t, query=>AC, line=>654, disabled=>f
+world=>CCA, org=>15, bad=>f, user=>CCC, line=>655, public=>t, space=>CC
+line=>656, coauthors=>BBB
+title=>BA, line=>657, date=>ACB
+user=>BC, query=>CC, cleaned=>t, line=>658, pos=>51, abstract=>BA
+subtitle=>CCA, user=>CCA, cleaned=>f, line=>659, abstract=>BA, pos=>95, date=>CA
+auth=>CA, state=>23, org=>19, bad=>f, user=>BCB, indexed=>f, line=>660, date=>ABA
+state=>64, org=>97, bad=>f, indexed=>f, line=>661, space=>BAB, coauthors=>BB, node=>BA
+status=>11, line=>662
+title=>BCC, org=>44, subtitle=>ACB, cleaned=>f, line=>663, pos=>58
+auth=>ABB, bad=>t, line=>664, pos=>82, coauthors=>CC, node=>AB
+bad=>f, cleaned=>t, status=>25, line=>665, disabled=>f, abstract=>BB, public=>t
+wait=>AC, user=>CB, line=>666, pos=>71, abstract=>ACA, coauthors=>CBB
+title=>AA, bad=>t, user=>BB, line=>667, date=>CA, space=>BC, node=>CC
+
+auth=>AAB, line=>669
+wait=>AAC, query=>ABA, status=>35, line=>670, disabled=>f, pos=>56
+org=>3, line=>671
+state=>46, bad=>f, cleaned=>t, line=>672
+state=>30, org=>9, status=>72, line=>673, abstract=>ACA, coauthors=>CB
+auth=>BB, wait=>CA, title=>BBB, bad=>t, user=>AAA, status=>86, indexed=>f, line=>674, node=>BCC
+indexed=>t, line=>675, pos=>63
+bad=>t, query=>CBB, status=>5, line=>676, abstract=>CCC, public=>f, space=>BB
+title=>BBB, org=>60, bad=>t, cleaned=>f, line=>677, pos=>82, date=>BAA, space=>BB, coauthors=>CAA
+
+
+state=>73, bad=>f, cleaned=>f, line=>680, abstract=>CA, date=>CCA, space=>CB
+state=>92, query=>CC, line=>681, abstract=>AB, date=>BBB, public=>t, coauthors=>CBA
+subtitle=>CCA, line=>682
+world=>BAC, subtitle=>AC, line=>683, disabled=>t, abstract=>AA, pos=>55, space=>AC, node=>CA
+state=>75, world=>ACA, query=>BC, line=>684, coauthors=>AAC
+status=>21, line=>685
+state=>39, wait=>CB, title=>CBC, query=>BB, cleaned=>t, line=>686, disabled=>f
+world=>CCA, wait=>AB, user=>CC, query=>BB, cleaned=>t, line=>687
+auth=>CAC, state=>94, wait=>ACC, title=>BBC, user=>BB, line=>688, disabled=>f, pos=>16, coauthors=>AAC
+
+org=>43, line=>690
+
+state=>4, title=>CA, subtitle=>AA, query=>BC, line=>692, pos=>57, date=>BCA, public=>f, coauthors=>ABB
+wait=>BBA, line=>693
+auth=>BCA, bad=>f, user=>BBA, line=>694, disabled=>f, date=>CC, public=>t, coauthors=>CB
+state=>66, wait=>BB, user=>CC, indexed=>t, line=>695, pos=>99, space=>BCA
+org=>1, line=>696, disabled=>f, space=>BCC, coauthors=>BC
+auth=>BC, cleaned=>t, indexed=>f, line=>697, space=>CBB
+wait=>AC, indexed=>f, line=>698, pos=>44
+wait=>AA, title=>BBB, org=>31, indexed=>t, line=>699, disabled=>f
+auth=>BB, world=>ACC, bad=>t, indexed=>f, line=>700, abstract=>CB, pos=>5, space=>ACB, node=>CC
+cleaned=>f, line=>701, space=>CB
+line=>702, space=>CCC
+world=>CA, subtitle=>ABA, line=>703, pos=>5, date=>BA, coauthors=>AB
+
+line=>705, date=>BBB
+state=>10, query=>CB, status=>70, line=>706, abstract=>ABA, date=>BC
+auth=>CB, line=>707
+wait=>BBA, cleaned=>t, line=>708, pos=>94, date=>CBC
+state=>86, org=>5, world=>BB, indexed=>f, line=>709, date=>BBB, space=>CA, public=>t
+world=>ACA, query=>ABC, status=>40, line=>710, disabled=>t, public=>t, node=>CA
+bad=>t, line=>711
+query=>AB, line=>712, coauthors=>BBC, node=>AA
+user=>ABB, line=>713, public=>f, space=>AAA, node=>BBA
+auth=>AC, wait=>BAC, bad=>t, line=>714, public=>f
+line=>715, abstract=>CA, public=>f
+user=>AC, indexed=>t, line=>716, coauthors=>CB
+state=>4, title=>ABB, org=>26, indexed=>t, line=>717, public=>t, coauthors=>CCA, node=>AC
+wait=>CA, title=>CCA, world=>CCC, line=>718, abstract=>ACA
+auth=>ACA, org=>29, subtitle=>AA, user=>CA, status=>24, indexed=>t, line=>719, public=>f, node=>CA
+
+line=>721, disabled=>t, abstract=>BAC
+world=>BC, line=>722
+state=>27, auth=>AA, title=>BC, world=>CC, query=>BCC, line=>723, disabled=>t, pos=>9, public=>f, node=>BCC
+org=>78, wait=>ABA, cleaned=>t, indexed=>t, line=>724, date=>ACB, space=>AA
+state=>60, line=>725
+
+
+wait=>ABA, title=>CAC, user=>CCC, line=>728
+wait=>CC, indexed=>t, status=>39, line=>729, disabled=>t, public=>f
+auth=>CB, subtitle=>BBA, line=>730, coauthors=>CAC
+world=>CBB, line=>731, space=>BCB
+cleaned=>t, line=>732
+org=>67, bad=>t, line=>733, pos=>9, node=>ACC
+world=>BC, wait=>CAC, org=>58, subtitle=>ACC, bad=>t, query=>CAA, line=>734, abstract=>BCA, pos=>1, public=>t
+state=>45, query=>AB, indexed=>f, line=>735, pos=>82, date=>BC, public=>f, coauthors=>BA
+state=>68, title=>BC, cleaned=>t, status=>34, line=>736, disabled=>t, node=>BBB
+auth=>AC, line=>737
+line=>738, date=>BA, space=>CCC, public=>f
+line=>739, node=>BAA
+org=>72, title=>BC, line=>740, pos=>51, coauthors=>CA
+state=>72, user=>CCB, query=>ACA, line=>741
+org=>80, subtitle=>BBA, bad=>t, user=>BC, line=>742, pos=>52, coauthors=>BCA
+
+query=>BC, line=>744, abstract=>AB, public=>f, node=>BAC
+world=>CAC, line=>745
+auth=>CBB, title=>AA, user=>AB, line=>746, pos=>35, public=>f, space=>AAB
+state=>69, world=>AB, org=>78, subtitle=>BA, bad=>f, line=>747, node=>AAA
+bad=>t, line=>748, public=>t
+wait=>BC, org=>47, query=>BBB, line=>749
+title=>BBB, line=>750
+org=>33, query=>CB, line=>751, disabled=>t
+subtitle=>BB, line=>752, space=>CC
+org=>89, line=>753
+auth=>ABA, line=>754, coauthors=>ACC
+subtitle=>BA, line=>755, pos=>47
+state=>81, subtitle=>CB, query=>AB, status=>25, cleaned=>f, line=>756, pos=>72, date=>BA, coauthors=>BCA
+state=>46, status=>88, line=>757, disabled=>f, public=>t
+world=>AB, line=>758, disabled=>t, abstract=>BB, coauthors=>AAA
+query=>AC, line=>759, abstract=>AAB
+auth=>BC, indexed=>f, line=>760, abstract=>BA, node=>CAA
+state=>10, auth=>BAC, title=>BC, query=>BCA, cleaned=>t, line=>761, disabled=>t, space=>ACC, coauthors=>ABA
+line=>762, disabled=>t, pos=>43
+world=>CBA, user=>BBC, indexed=>t, line=>763
+wait=>ACB, query=>BA, status=>22, line=>764, pos=>70, abstract=>BAC, public=>f, space=>BC
+
+line=>766, disabled=>f, abstract=>CBC, date=>CA
+title=>CC, bad=>t, user=>BCC, indexed=>f, line=>767, date=>BCB, node=>AAA
+title=>CB, line=>768, abstract=>AA, node=>ABB
+org=>21, user=>ABC, line=>769, abstract=>BB, date=>CBB, space=>CC
+auth=>AC, org=>66, user=>CC, line=>770, public=>f, space=>CA, coauthors=>AA
+org=>58, line=>771, coauthors=>BCC, node=>AC
+
+auth=>BC, wait=>CC, line=>773, abstract=>ACC, pos=>98, date=>CCC, space=>ABB, node=>CB
+
+query=>BC, user=>AC, indexed=>t, line=>775, abstract=>AAA
+subtitle=>BAA, indexed=>f, line=>776
+line=>777, pos=>33, date=>CCB, public=>t
+world=>BCA, bad=>t, line=>778
+auth=>CA, line=>779, date=>AC, space=>CAC
+title=>BB, bad=>f, cleaned=>t, line=>780, disabled=>f, date=>BAB, space=>ACB
+auth=>CAC, title=>AAB, subtitle=>CA, bad=>f, line=>781, disabled=>f, space=>CB
+state=>78, auth=>AC, bad=>t, status=>46, line=>782, abstract=>CCA, pos=>97, public=>t
+user=>BBA, line=>783
+
+state=>63, title=>CA, cleaned=>t, line=>785, abstract=>BA, space=>BCC
+line=>786, node=>CAC
+line=>787, pos=>65
+line=>788, space=>ABB
+
+org=>14, line=>790, abstract=>CAB, coauthors=>BBC
+subtitle=>CBA, cleaned=>f, line=>791, disabled=>f, pos=>57, node=>CB
+auth=>CAA, org=>84, wait=>AB, indexed=>t, status=>51, line=>792, abstract=>CC
+org=>72, bad=>t, line=>793, space=>ACA
+
+auth=>BC, state=>76, wait=>CC, user=>ABB, cleaned=>f, line=>795, pos=>99, abstract=>CA
+wait=>CCA, world=>CBC, line=>796, date=>CB, public=>f
+state=>49, line=>797, coauthors=>CC
+wait=>BBB, title=>ABB, org=>74, line=>798, disabled=>f, pos=>34, space=>BB
+line=>799, abstract=>CB
+state=>84, user=>ABB, cleaned=>f, status=>18, line=>800, disabled=>t, date=>CCA, node=>BA
+state=>81, auth=>CB, world=>CA, user=>CAA, line=>801, date=>AC, space=>CBC, coauthors=>BCB
+org=>4, line=>802, disabled=>f, abstract=>ABA, public=>f
+auth=>CBC, state=>99, cleaned=>t, line=>803, disabled=>t, space=>BC, node=>BBC
+auth=>AC, wait=>CA, cleaned=>f, line=>804, pos=>54, date=>BAA, public=>t, space=>AB
+
+auth=>BCB, wait=>BCC, subtitle=>AAA, line=>806
+line=>807, disabled=>f, space=>ACA
+org=>96, query=>CBA, line=>808, disabled=>f, pos=>74, space=>CA, public=>f
+
+state=>12, title=>AA, bad=>f, status=>20, line=>810, disabled=>t, coauthors=>CAC, node=>AB
+auth=>ABC, line=>811, date=>CA
+title=>AB, indexed=>f, line=>812, disabled=>f, node=>AAC
+
+world=>CBA, status=>15, line=>814, abstract=>CBA
+status=>49, line=>815, pos=>49
+subtitle=>CAB, line=>816
+
+
+world=>CAC, title=>CB, wait=>AA, query=>CA, indexed=>t, line=>819, disabled=>t
+auth=>ABB, wait=>AC, query=>CC, cleaned=>t, indexed=>f, line=>820, abstract=>AA, public=>f, node=>AB
+org=>5, wait=>BA, indexed=>t, line=>821, node=>AB
+title=>CC, wait=>CC, bad=>f, query=>BCC, indexed=>f, line=>822, pos=>27, date=>CB, node=>CBA
+query=>BC, status=>28, line=>823, public=>f
+status=>1, line=>824, abstract=>BB
+
+auth=>AA, title=>BC, query=>CA, status=>33, line=>826
+state=>9, title=>BB, subtitle=>ACC, bad=>t, query=>BA, status=>41, line=>827, abstract=>ACB, public=>f
+auth=>AB, subtitle=>CAB, line=>828, public=>f, coauthors=>AB, node=>BAC
+line=>829, disabled=>f, public=>t, node=>CBC
+auth=>BAB, line=>830
+wait=>BBA, bad=>t, indexed=>f, line=>831, space=>BB
+org=>70, wait=>BC, world=>AC, indexed=>t, status=>96, line=>832, disabled=>t, space=>AB
+state=>8, world=>BAB, bad=>t, indexed=>t, status=>18, line=>833, date=>BA, space=>BA
+query=>AB, line=>834
+bad=>t, status=>5, line=>835
+world=>BAC, subtitle=>BB, bad=>f, user=>AB, indexed=>f, cleaned=>t, line=>836
+line=>837, public=>f
+line=>838, pos=>7
+auth=>CA, query=>ABB, indexed=>t, line=>839, public=>t
+wait=>CC, bad=>f, line=>840, date=>AAB, public=>f, coauthors=>BCB
+auth=>AB, state=>97, org=>24, line=>841, pos=>41, node=>BC
+wait=>BB, world=>CBA, user=>BAA, status=>18, line=>842, date=>BAB, public=>t
+title=>BA, subtitle=>CA, query=>CCB, line=>843, space=>BB
+auth=>BB, world=>ACA, line=>844, pos=>29
+state=>65, org=>40, query=>CAA, user=>AB, indexed=>f, cleaned=>f, line=>845
+title=>CB, cleaned=>f, indexed=>f, line=>846
+wait=>CAA, indexed=>f, line=>847, disabled=>f
+
+title=>CB, query=>CC, line=>849, abstract=>CB, pos=>10, public=>t
+auth=>CB, subtitle=>BA, cleaned=>t, line=>850, disabled=>t, pos=>84
+org=>45, wait=>BA, query=>CCC, line=>851, date=>BCA, coauthors=>CAB
+state=>84, title=>CB, line=>852, pos=>71, space=>CA
+line=>853, public=>t, node=>AA
+subtitle=>BC, user=>AB, cleaned=>t, line=>854, public=>t
+state=>26, wait=>BA, world=>BBB, user=>BB, status=>53, line=>855, abstract=>ABA, pos=>72, space=>AC
+line=>856, public=>f, coauthors=>CA
+wait=>ABB, subtitle=>CBA, line=>857, pos=>44
+auth=>ABA, wait=>CC, org=>0, bad=>t, query=>BB, line=>858, disabled=>f, public=>t
+bad=>f, user=>AA, line=>859, pos=>90
+world=>BCC, title=>BAA, bad=>f, user=>CAA, query=>BBC, line=>860, date=>CAA, space=>BCB, public=>t, coauthors=>CB
+title=>BAB, world=>BC, subtitle=>AA, cleaned=>f, status=>9, line=>861, pos=>95
+title=>AC, line=>862
+wait=>CB, bad=>f, status=>89, line=>863, coauthors=>AB
+subtitle=>ACC, indexed=>t, cleaned=>t, line=>864
+title=>AB, subtitle=>CBB, query=>ACA, indexed=>t, line=>865, disabled=>t
+title=>BC, world=>BB, query=>AA, user=>ACB, status=>43, cleaned=>f, line=>866, coauthors=>CBC, node=>ACB
+
+org=>25, wait=>AC, indexed=>f, line=>868, disabled=>f, abstract=>CA, pos=>48
+bad=>t, status=>34, line=>869, pos=>32, date=>AC, public=>t, node=>AA
+state=>33, wait=>AAC, indexed=>t, status=>20, line=>870, abstract=>BA
+wait=>CCC, subtitle=>AC, line=>871, disabled=>f, space=>BA, public=>t, coauthors=>BCC
+status=>49, line=>872
+state=>90, title=>ACC, world=>CBB, subtitle=>BAB, bad=>f, status=>94, line=>873, abstract=>CB
+title=>BCB, line=>874
+cleaned=>f, line=>875
+wait=>BAA, subtitle=>BBC, line=>876
+auth=>AB, org=>35, bad=>f, indexed=>f, line=>877, coauthors=>BBA
+line=>878, public=>f
+
+auth=>CB, wait=>CBC, indexed=>f, line=>880, public=>t
+query=>CC, status=>4, line=>881, disabled=>t, node=>CA
+title=>BB, line=>882
+state=>53, bad=>f, cleaned=>f, status=>63, line=>883, coauthors=>BAA
+auth=>ACA, world=>AC, user=>CBC, line=>884, date=>BCA, node=>BBC
+auth=>BAB, state=>11, world=>CB, org=>77, query=>BA, cleaned=>f, line=>885, space=>AC
+world=>CA, user=>CA, line=>886, node=>CB
+state=>32, org=>50, wait=>AA, line=>887, disabled=>f, space=>BBA, public=>f
+cleaned=>t, line=>888, pos=>70, node=>ABC
+org=>63, user=>AAB, query=>BB, line=>889, date=>BC, space=>CBB, node=>ABC
+wait=>BB, user=>BB, query=>CB, line=>890, space=>BB, coauthors=>BA, node=>ABC
+auth=>BC, world=>CC, subtitle=>CB, line=>891, public=>f, coauthors=>BC
+state=>13, org=>38, line=>892, coauthors=>BC, node=>ABC
+auth=>CC, world=>CAC, line=>893, date=>BBA, node=>CBC
+
+auth=>AA, line=>895, coauthors=>BB
+auth=>AA, state=>76, status=>85, line=>896, date=>CCC, public=>t, coauthors=>AB
+auth=>AB, indexed=>t, cleaned=>f, line=>897
+line=>898, coauthors=>CBB
+
+wait=>ACC, line=>900, abstract=>BBA
+auth=>AA, wait=>BCB, cleaned=>f, line=>901, abstract=>AAC
+state=>68, title=>AC, subtitle=>BB, line=>902
+state=>41, wait=>ABA, bad=>f, user=>BBA, status=>46, line=>903, node=>AAB
+
+cleaned=>f, line=>905, pos=>33
+bad=>f, query=>BA, line=>906, pos=>48, space=>CB, public=>t
+query=>CB, indexed=>t, line=>907, pos=>41, abstract=>CBB, space=>BA, public=>f, node=>BC
+title=>AB, line=>908
+auth=>BC, title=>CB, line=>909, disabled=>f, space=>CA, public=>t, coauthors=>BC
+world=>AA, user=>ABA, indexed=>f, line=>910, abstract=>CC
+auth=>CCA, indexed=>f, line=>911, date=>AC, public=>f
+world=>AAB, bad=>t, line=>912
+subtitle=>CBB, line=>913, public=>t
+wait=>CB, line=>914, disabled=>f, pos=>71, date=>BA, space=>CBA, public=>f, coauthors=>BB
+org=>67, wait=>CA, bad=>f, line=>915, disabled=>f, public=>t
+
+line=>917, date=>CB
+auth=>CBB, world=>AAA, status=>83, indexed=>f, line=>918, disabled=>t, date=>CBA, coauthors=>ACC
+wait=>AB, title=>BA, status=>33, line=>919, disabled=>f
+wait=>ACB, cleaned=>f, line=>920, abstract=>AA, coauthors=>BCB
+wait=>ABB, org=>40, world=>BC, subtitle=>CA, user=>AAC, status=>14, indexed=>t, line=>921, pos=>66
+auth=>BA, org=>22, wait=>BAB, bad=>t, user=>ACC, status=>32, line=>922
+world=>BA, query=>CAB, status=>0, line=>923
+org=>84, bad=>t, line=>924, coauthors=>BAB
+auth=>ACC, subtitle=>AAA, query=>CCA, cleaned=>f, line=>925, pos=>60, space=>BC
+wait=>BC, subtitle=>CCC, bad=>f, cleaned=>f, indexed=>f, line=>926, public=>f, coauthors=>AC
+auth=>CA, state=>91, org=>6, world=>AA, wait=>ABB, query=>AAC, line=>927, date=>CA, node=>BAC
+world=>BCA, query=>AA, user=>BBC, line=>928, disabled=>f
+world=>CBC, user=>CBC, line=>929, date=>CAC
+world=>BCB, bad=>f, user=>BB, line=>930
+auth=>CA, world=>AA, query=>ABA, user=>AA, indexed=>t, line=>931, coauthors=>BBC
+auth=>BAA, bad=>t, line=>932, disabled=>f, pos=>93, abstract=>CCA, date=>BBA, coauthors=>AA
+line=>933, space=>CAB, node=>AB
+
+status=>60, cleaned=>t, indexed=>t, line=>935, pos=>35, space=>CAB, node=>BBB
+wait=>AAA, bad=>t, status=>26, line=>936, abstract=>ACB, space=>BBA, coauthors=>CCC
+title=>BA, bad=>t, line=>937, date=>BBA, public=>t
+
+query=>BA, user=>BA, line=>939, disabled=>t
+line=>940, date=>CC
+wait=>CAB, query=>BCA, user=>BC, line=>941, pos=>8, coauthors=>ACC
+line=>942, space=>BA
+auth=>CA, org=>11, line=>943, pos=>99
+org=>83, line=>944, disabled=>f, date=>BBA, space=>AC, node=>AC
+world=>CCA, line=>945, node=>BC
+org=>95, title=>CA, world=>BA, line=>946, pos=>36, coauthors=>CA
+state=>93, line=>947
+cleaned=>f, status=>5, line=>948, abstract=>BB, public=>f, coauthors=>ABC
+world=>CA, org=>61, bad=>f, query=>CC, cleaned=>t, line=>949, pos=>14, space=>CC
+state=>91, line=>950, abstract=>BA, date=>AB
+auth=>BBC, line=>951, date=>BB
+auth=>BAB, line=>952, disabled=>t, node=>AAA
+auth=>CAA, subtitle=>ABA, bad=>t, line=>953
+auth=>CA, wait=>BB, org=>12, user=>BCC, cleaned=>f, line=>954, public=>f, coauthors=>AA
+org=>93, cleaned=>t, line=>955, disabled=>t, public=>t, node=>ACA
+line=>956, pos=>10
+org=>74, world=>CCC, subtitle=>AB, user=>AAA, cleaned=>t, line=>957, pos=>70, public=>t, node=>CC
+state=>51, line=>958
+world=>CCA, title=>BCB, user=>AB, indexed=>t, line=>959, disabled=>t, pos=>21, date=>CBC
+org=>86, wait=>BC, query=>BB, user=>AA, indexed=>t, line=>960, pos=>58, date=>AB
+line=>961, node=>CC
+auth=>BCB, world=>ACC, subtitle=>CA, bad=>t, user=>BA, indexed=>f, line=>962, public=>f
+
+status=>37, line=>964
+state=>70, status=>76, indexed=>f, line=>965, disabled=>t, space=>BB
+
+state=>67, world=>CA, title=>AA, line=>967, abstract=>BA, space=>BAA
+auth=>CA, world=>AA, bad=>t, query=>BC, status=>53, indexed=>f, line=>968, date=>AB, node=>BAA
+query=>AC, cleaned=>t, line=>969, abstract=>BC, space=>CAB, coauthors=>BAA
+wait=>BCA, world=>CB, title=>BC, indexed=>f, line=>970, disabled=>t, pos=>70, date=>AB
+
+subtitle=>BC, query=>AA, line=>972
+line=>973, public=>t
+org=>75, world=>AAB, subtitle=>BB, user=>CC, line=>974, space=>CA
+auth=>BCB, cleaned=>t, line=>975
+title=>BAC, user=>CB, line=>976, public=>f
+subtitle=>BAC, indexed=>f, cleaned=>f, line=>977, disabled=>f, abstract=>ABC, space=>ABA
+state=>63, bad=>f, line=>978, pos=>93, node=>AAC
+
+cleaned=>f, line=>980, abstract=>CCB
+state=>40, title=>ABA, subtitle=>CAB, query=>BC, line=>981, date=>CA, coauthors=>AB
+
+auth=>ABA, subtitle=>ACC, user=>AA, query=>AC, cleaned=>t, line=>983, date=>ACB, node=>CB
+state=>32, title=>ABC, org=>58, status=>95, line=>984, disabled=>t, pos=>6, space=>CBB
+title=>BCC, subtitle=>CCC, user=>BBC, line=>985, public=>f, coauthors=>CCB, node=>AA
+subtitle=>ACA, query=>BCC, status=>43, cleaned=>t, indexed=>t, line=>986, abstract=>CAC
+
+world=>CAB, org=>21, indexed=>t, line=>988, abstract=>ABC
+title=>CBC, status=>66, line=>989
+
+line=>991, abstract=>BA, node=>BBB
+line=>992, disabled=>t, pos=>29, public=>f
+state=>53, wait=>CB, subtitle=>CCC, line=>993, date=>CAC, public=>f, coauthors=>BB
+wait=>CBA, title=>CA, subtitle=>BB, user=>BAA, line=>994, disabled=>t, date=>BB, coauthors=>CCC, node=>CC
+title=>BB, user=>AA, query=>CAA, status=>43, line=>995, pos=>6, abstract=>CC, public=>t
+wait=>AC, query=>BA, line=>996, coauthors=>BB, node=>CCC
+auth=>BC, title=>CAC, subtitle=>BA, line=>997, date=>BAA
+wait=>AB, user=>ABC, line=>998, pos=>41, node=>CAC
+state=>4, title=>AC, bad=>t, status=>59, line=>999, disabled=>t
+user=>BC, line=>1000
+wait=>NULL, line=>1000
+age=>25
+age=>25.0
diff --git a/expected/hstore.out b/expected/hstore.out
new file mode 100644 (file)
index 0000000..82d0d8f
--- /dev/null
@@ -0,0 +1,1610 @@
+CREATE EXTENSION hstore;
+set escape_string_warning=off;
+--hstore;
+select ''::hstore;
+ hstore 
+--------
+(1 row)
+
+select 'a=>b'::hstore;
+  hstore  
+----------
+ "a"=>"b"
+(1 row)
+
+select ' a=>b'::hstore;
+  hstore  
+----------
+ "a"=>"b"
+(1 row)
+
+select 'a =>b'::hstore;
+  hstore  
+----------
+ "a"=>"b"
+(1 row)
+
+select 'a=>b '::hstore;
+  hstore  
+----------
+ "a"=>"b"
+(1 row)
+
+select 'a=> b'::hstore;
+  hstore  
+----------
+ "a"=>"b"
+(1 row)
+
+select '"a"=>"b"'::hstore;
+  hstore  
+----------
+ "a"=>"b"
+(1 row)
+
+select ' "a"=>"b"'::hstore;
+  hstore  
+----------
+ "a"=>"b"
+(1 row)
+
+select '"a" =>"b"'::hstore;
+  hstore  
+----------
+ "a"=>"b"
+(1 row)
+
+select '"a"=>"b" '::hstore;
+  hstore  
+----------
+ "a"=>"b"
+(1 row)
+
+select '"a"=> "b"'::hstore;
+  hstore  
+----------
+ "a"=>"b"
+(1 row)
+
+select 'aa=>bb'::hstore;
+   hstore   
+------------
+ "aa"=>"bb"
+(1 row)
+
+select ' aa=>bb'::hstore;
+   hstore   
+------------
+ "aa"=>"bb"
+(1 row)
+
+select 'aa =>bb'::hstore;
+   hstore   
+------------
+ "aa"=>"bb"
+(1 row)
+
+select 'aa=>bb '::hstore;
+   hstore   
+------------
+ "aa"=>"bb"
+(1 row)
+
+select 'aa=> bb'::hstore;
+   hstore   
+------------
+ "aa"=>"bb"
+(1 row)
+
+select '"aa"=>"bb"'::hstore;
+   hstore   
+------------
+ "aa"=>"bb"
+(1 row)
+
+select ' "aa"=>"bb"'::hstore;
+   hstore   
+------------
+ "aa"=>"bb"
+(1 row)
+
+select '"aa" =>"bb"'::hstore;
+   hstore   
+------------
+ "aa"=>"bb"
+(1 row)
+
+select '"aa"=>"bb" '::hstore;
+   hstore   
+------------
+ "aa"=>"bb"
+(1 row)
+
+select '"aa"=> "bb"'::hstore;
+   hstore   
+------------
+ "aa"=>"bb"
+(1 row)
+
+select 'aa=>bb, cc=>dd'::hstore;
+         hstore         
+------------------------
+ "aa"=>"bb", "cc"=>"dd"
+(1 row)
+
+select 'aa=>bb , cc=>dd'::hstore;
+         hstore         
+------------------------
+ "aa"=>"bb", "cc"=>"dd"
+(1 row)
+
+select 'aa=>bb ,cc=>dd'::hstore;
+         hstore         
+------------------------
+ "aa"=>"bb", "cc"=>"dd"
+(1 row)
+
+select 'aa=>bb, "cc"=>dd'::hstore;
+         hstore         
+------------------------
+ "aa"=>"bb", "cc"=>"dd"
+(1 row)
+
+select 'aa=>bb , "cc"=>dd'::hstore;
+         hstore         
+------------------------
+ "aa"=>"bb", "cc"=>"dd"
+(1 row)
+
+select 'aa=>bb ,"cc"=>dd'::hstore;
+         hstore         
+------------------------
+ "aa"=>"bb", "cc"=>"dd"
+(1 row)
+
+select 'aa=>"bb", cc=>dd'::hstore;
+         hstore         
+------------------------
+ "aa"=>"bb", "cc"=>"dd"
+(1 row)
+
+select 'aa=>"bb" , cc=>dd'::hstore;
+         hstore         
+------------------------
+ "aa"=>"bb", "cc"=>"dd"
+(1 row)
+
+select 'aa=>"bb" ,cc=>dd'::hstore;
+         hstore         
+------------------------
+ "aa"=>"bb", "cc"=>"dd"
+(1 row)
+
+select 'aa=>null'::hstore;
+   hstore   
+------------
+ "aa"=>NULL
+(1 row)
+
+select 'aa=>NuLl'::hstore;
+   hstore   
+------------
+ "aa"=>NULL
+(1 row)
+
+select 'aa=>"NuLl"'::hstore;
+    hstore    
+--------------
+ "aa"=>"NuLl"
+(1 row)
+
+select 'aa=>nul'::hstore;
+   hstore    
+-------------
+ "aa"=>"nul"
+(1 row)
+
+select 'aa=>NuL'::hstore;
+   hstore    
+-------------
+ "aa"=>"NuL"
+(1 row)
+
+select 'aa=>"NuL"'::hstore;
+   hstore    
+-------------
+ "aa"=>"NuL"
+(1 row)
+
+select e'\\=a=>q=w'::hstore;
+   hstore    
+-------------
+ "=a"=>"q=w"
+(1 row)
+
+select e'"=a"=>q\\=w'::hstore;
+   hstore    
+-------------
+ "=a"=>"q=w"
+(1 row)
+
+select e'"\\"a"=>q>w'::hstore;
+    hstore    
+--------------
+ "\"a"=>"q>w"
+(1 row)
+
+select e'\\"a=>q"w'::hstore;
+    hstore     
+---------------
+ "\"a"=>"q\"w"
+(1 row)
+
+select ''::hstore;
+ hstore 
+--------
+(1 row)
+
+select '       '::hstore;
+ hstore 
+--------
+(1 row)
+
+-- -> operator
+select 'aa=>b, c=>d , b=>16'::hstore->'c';
+ ?column? 
+----------
+ d
+(1 row)
+
+select 'aa=>b, c=>d , b=>16'::hstore->'b';
+ ?column? 
+----------
+ 16
+(1 row)
+
+select 'aa=>b, c=>d , b=>16'::hstore->'aa';
+ ?column? 
+----------
+ b
+(1 row)
+
+select ('aa=>b, c=>d , b=>16'::hstore->'gg') is null;
+ ?column? 
+----------
+ t
+(1 row)
+
+select ('aa=>NULL, c=>d , b=>16'::hstore->'aa') is null;
+ ?column? 
+----------
+ t
+(1 row)
+
+select ('aa=>"NULL", c=>d , b=>16'::hstore->'aa') is null;
+ ?column? 
+----------
+ f
+(1 row)
+
+-- -> array operator
+select 'aa=>"NULL", c=>d , b=>16'::hstore -> ARRAY['aa','c'];
+  ?column?  
+------------
+ {"NULL",d}
+(1 row)
+
+select 'aa=>"NULL", c=>d , b=>16'::hstore -> ARRAY['c','aa'];
+  ?column?  
+------------
+ {d,"NULL"}
+(1 row)
+
+select 'aa=>NULL, c=>d , b=>16'::hstore -> ARRAY['aa','c',null];
+   ?column?    
+---------------
+ {NULL,d,NULL}
+(1 row)
+
+select 'aa=>1, c=>3, b=>2, d=>4'::hstore -> ARRAY[['b','d'],['aa','c']];
+   ?column?    
+---------------
+ {{2,4},{1,3}}
+(1 row)
+
+-- exists/defined
+select exist('a=>NULL, b=>qq', 'a');
+ exist 
+-------
+ t
+(1 row)
+
+select exist('a=>NULL, b=>qq', 'b');
+ exist 
+-------
+ t
+(1 row)
+
+select exist('a=>NULL, b=>qq', 'c');
+ exist 
+-------
+ f
+(1 row)
+
+select exist('a=>"NULL", b=>qq', 'a');
+ exist 
+-------
+ t
+(1 row)
+
+select defined('a=>NULL, b=>qq', 'a');
+ defined 
+---------
+ f
+(1 row)
+
+select defined('a=>NULL, b=>qq', 'b');
+ defined 
+---------
+ t
+(1 row)
+
+select defined('a=>NULL, b=>qq', 'c');
+ defined 
+---------
+ f
+(1 row)
+
+select defined('a=>"NULL", b=>qq', 'a');
+ defined 
+---------
+ t
+(1 row)
+
+select hstore 'a=>NULL, b=>qq' ? 'a';
+ ?column? 
+----------
+ t
+(1 row)
+
+select hstore 'a=>NULL, b=>qq' ? 'b';
+ ?column? 
+----------
+ t
+(1 row)
+
+select hstore 'a=>NULL, b=>qq' ? 'c';
+ ?column? 
+----------
+ f
+(1 row)
+
+select hstore 'a=>"NULL", b=>qq' ? 'a';
+ ?column? 
+----------
+ t
+(1 row)
+
+select hstore 'a=>NULL, b=>qq' ?| ARRAY['a','b'];
+ ?column? 
+----------
+ t
+(1 row)
+
+select hstore 'a=>NULL, b=>qq' ?| ARRAY['b','a'];
+ ?column? 
+----------
+ t
+(1 row)
+
+select hstore 'a=>NULL, b=>qq' ?| ARRAY['c','a'];
+ ?column? 
+----------
+ t
+(1 row)
+
+select hstore 'a=>NULL, b=>qq' ?| ARRAY['c','d'];
+ ?column? 
+----------
+ f
+(1 row)
+
+select hstore 'a=>NULL, b=>qq' ?| '{}'::text[];
+ ?column? 
+----------
+ f
+(1 row)
+
+select hstore 'a=>NULL, b=>qq' ?& ARRAY['a','b'];
+ ?column? 
+----------
+ t
+(1 row)
+
+select hstore 'a=>NULL, b=>qq' ?& ARRAY['b','a'];
+ ?column? 
+----------
+ t
+(1 row)
+
+select hstore 'a=>NULL, b=>qq' ?& ARRAY['c','a'];
+ ?column? 
+----------
+ f
+(1 row)
+
+select hstore 'a=>NULL, b=>qq' ?& ARRAY['c','d'];
+ ?column? 
+----------
+ f
+(1 row)
+
+select hstore 'a=>NULL, b=>qq' ?& '{}'::text[];
+ ?column? 
+----------
+ t
+(1 row)
+
+-- delete
+select delete('a=>1 , b=>2, c=>3'::hstore, 'a');
+     delete     
+----------------
+ "b"=>2, "c"=>3
+(1 row)
+
+select delete('a=>null , b=>2, c=>3'::hstore, 'a');
+     delete     
+----------------
+ "b"=>2, "c"=>3
+(1 row)
+
+select delete('a=>1 , b=>2, c=>3'::hstore, 'b');
+     delete     
+----------------
+ "a"=>1, "c"=>3
+(1 row)
+
+select delete('a=>1 , b=>2, c=>3'::hstore, 'c');
+     delete     
+----------------
+ "a"=>1, "b"=>2
+(1 row)
+
+select delete('a=>1 , b=>2, c=>3'::hstore, 'd');
+         delete         
+------------------------
+ "a"=>1, "b"=>2, "c"=>3
+(1 row)
+
+select 'a=>1 , b=>2, c=>3'::hstore - 'a'::text;
+    ?column?    
+----------------
+ "b"=>2, "c"=>3
+(1 row)
+
+select 'a=>null , b=>2, c=>3'::hstore - 'a'::text;
+    ?column?    
+----------------
+ "b"=>2, "c"=>3
+(1 row)
+
+select 'a=>1 , b=>2, c=>3'::hstore - 'b'::text;
+    ?column?    
+----------------
+ "a"=>1, "c"=>3
+(1 row)
+
+select 'a=>1 , b=>2, c=>3'::hstore - 'c'::text;
+    ?column?    
+----------------
+ "a"=>1, "b"=>2
+(1 row)
+
+select 'a=>1 , b=>2, c=>3'::hstore - 'd'::text;
+        ?column?        
+------------------------
+ "a"=>1, "b"=>2, "c"=>3
+(1 row)
+
+select pg_column_size('a=>1 , b=>2, c=>3'::hstore - 'b'::text)
+         = pg_column_size('a=>1, b=>2'::hstore);
+ ?column? 
+----------
+ t
+(1 row)
+
+-- delete (array)
+select delete('a=>1 , b=>2, c=>3'::hstore, ARRAY['d','e']);
+         delete         
+------------------------
+ "a"=>1, "b"=>2, "c"=>3
+(1 row)
+
+select delete('a=>1 , b=>2, c=>3'::hstore, ARRAY['d','b']);
+     delete     
+----------------
+ "a"=>1, "c"=>3
+(1 row)
+
+select delete('a=>1 , b=>2, c=>3'::hstore, ARRAY['a','c']);
+ delete 
+--------
+ "b"=>2
+(1 row)
+
+select delete('a=>1 , b=>2, c=>3'::hstore, ARRAY[['b'],['c'],['a']]);
+ delete 
+--------
+(1 row)
+
+select delete('a=>1 , b=>2, c=>3'::hstore, '{}'::text[]);
+         delete         
+------------------------
+ "a"=>1, "b"=>2, "c"=>3
+(1 row)
+
+select 'a=>1 , b=>2, c=>3'::hstore - ARRAY['d','e'];
+        ?column?        
+------------------------
+ "a"=>1, "b"=>2, "c"=>3
+(1 row)
+
+select 'a=>1 , b=>2, c=>3'::hstore - ARRAY['d','b'];
+    ?column?    
+----------------
+ "a"=>1, "c"=>3
+(1 row)
+
+select 'a=>1 , b=>2, c=>3'::hstore - ARRAY['a','c'];
+ ?column? 
+----------
+ "b"=>2
+(1 row)
+
+select 'a=>1 , b=>2, c=>3'::hstore - ARRAY[['b'],['c'],['a']];
+ ?column? 
+----------
+(1 row)
+
+select 'a=>1 , b=>2, c=>3'::hstore - '{}'::text[];
+        ?column?        
+------------------------
+ "a"=>1, "b"=>2, "c"=>3
+(1 row)
+
+select pg_column_size('a=>1 , b=>2, c=>3'::hstore - ARRAY['a','c'])
+         = pg_column_size('b=>2'::hstore);
+ ?column? 
+----------
+ t
+(1 row)
+
+select pg_column_size('a=>1 , b=>2, c=>3'::hstore - '{}'::text[])
+         = pg_column_size('a=>1, b=>2, c=>3'::hstore);
+ ?column? 
+----------
+ t
+(1 row)
+
+-- delete (hstore)
+select delete('aa=>1 , b=>2, c=>3'::hstore, 'aa=>4, b=>2'::hstore);
+     delete      
+-----------------
+ "c"=>3, "aa"=>1
+(1 row)
+
+select delete('aa=>1 , b=>2, c=>3'::hstore, 'aa=>NULL, c=>3'::hstore);
+     delete      
+-----------------
+ "b"=>2, "aa"=>1
+(1 row)
+
+select delete('aa=>1 , b=>2, c=>3'::hstore, 'aa=>1, b=>2, c=>3'::hstore);
+ delete 
+--------
+(1 row)
+
+select delete('aa=>1 , b=>2, c=>3'::hstore, 'b=>2'::hstore);
+     delete      
+-----------------
+ "c"=>3, "aa"=>1
+(1 row)
+
+select delete('aa=>1 , b=>2, c=>3'::hstore, ''::hstore);
+         delete          
+-------------------------
+ "b"=>2, "c"=>3, "aa"=>1
+(1 row)
+
+select 'aa=>1 , b=>2, c=>3'::hstore - 'aa=>4, b=>2'::hstore;
+    ?column?     
+-----------------
+ "c"=>3, "aa"=>1
+(1 row)
+
+select 'aa=>1 , b=>2, c=>3'::hstore - 'aa=>NULL, c=>3'::hstore;
+    ?column?     
+-----------------
+ "b"=>2, "aa"=>1
+(1 row)
+
+select 'aa=>1 , b=>2, c=>3'::hstore - 'aa=>1, b=>2, c=>3'::hstore;
+ ?column? 
+----------
+(1 row)
+
+select 'aa=>1 , b=>2, c=>3'::hstore - 'b=>2'::hstore;
+    ?column?     
+-----------------
+ "c"=>3, "aa"=>1
+(1 row)
+
+select 'aa=>1 , b=>2, c=>3'::hstore - ''::hstore;
+        ?column?         
+-------------------------
+ "b"=>2, "c"=>3, "aa"=>1
+(1 row)
+
+select pg_column_size('a=>1 , b=>2, c=>3'::hstore - 'b=>2'::hstore)
+         = pg_column_size('a=>1, c=>3'::hstore);
+ ?column? 
+----------
+ t
+(1 row)
+
+select pg_column_size('a=>1 , b=>2, c=>3'::hstore - ''::hstore)
+         = pg_column_size('a=>1, b=>2, c=>3'::hstore);
+ ?column? 
+----------
+ t
+(1 row)
+
+-- ||
+select 'aa=>1 , b=>2, cq=>3'::hstore || 'cq=>l, b=>g, fg=>f';
+               ?column?                
+---------------------------------------
+ "b"=>"g", "aa"=>1, "cq"=>"l", "fg"=>f
+(1 row)
+
+select 'aa=>1 , b=>2, cq=>3'::hstore || 'aq=>l';
+              ?column?               
+-------------------------------------
+ "b"=>2, "aa"=>1, "aq"=>"l", "cq"=>3
+(1 row)
+
+select 'aa=>1 , b=>2, cq=>3'::hstore || 'aa=>l';
+          ?column?          
+----------------------------
+ "b"=>2, "aa"=>"l", "cq"=>3
+(1 row)
+
+select 'aa=>1 , b=>2, cq=>3'::hstore || '';
+         ?column?         
+--------------------------
+ "b"=>2, "aa"=>1, "cq"=>3
+(1 row)
+
+select ''::hstore || 'cq=>l, b=>g, fg=>f';
+           ?column?           
+------------------------------
+ "b"=>"g", "cq"=>"l", "fg"=>f
+(1 row)
+
+select pg_column_size(''::hstore || ''::hstore) = pg_column_size(''::hstore);
+ ?column? 
+----------
+ t
+(1 row)
+
+select pg_column_size('aa=>1'::hstore || 'b=>2'::hstore)
+         = pg_column_size('aa=>1, b=>2'::hstore);
+ ?column? 
+----------
+ t
+(1 row)
+
+select pg_column_size('aa=>1, b=>2'::hstore || ''::hstore)
+         = pg_column_size('aa=>1, b=>2'::hstore);
+ ?column? 
+----------
+ t
+(1 row)
+
+select pg_column_size(''::hstore || 'aa=>1, b=>2'::hstore)
+         = pg_column_size('aa=>1, b=>2'::hstore);
+ ?column? 
+----------
+ t
+(1 row)
+
+-- hstore(text,text)
+select 'a=>g, b=>c'::hstore || hstore('asd', 'gf');
+            ?column?             
+---------------------------------
+ "a"=>"g", "b"=>"c", "asd"=>"gf"
+(1 row)
+
+select 'a=>g, b=>c'::hstore || hstore('b', 'gf');
+      ?column?       
+---------------------
+ "a"=>"g", "b"=>"gf"
+(1 row)
+
+select 'a=>g, b=>c'::hstore || hstore('b', 'NULL');
+       ?column?        
+-----------------------
+ "a"=>"g", "b"=>"NULL"
+(1 row)
+
+select 'a=>g, b=>c'::hstore || hstore('b', NULL);
+      ?column?       
+---------------------
+ "a"=>"g", "b"=>NULL
+(1 row)
+
+select ('a=>g, b=>c'::hstore || hstore(NULL, 'b')) is null;
+ ?column? 
+----------
+ t
+(1 row)
+
+select pg_column_size(hstore('b', 'gf'))
+         = pg_column_size('b=>gf'::hstore);
+ ?column? 
+----------
+ t
+(1 row)
+
+select pg_column_size('a=>g, b=>c'::hstore || hstore('b', 'gf'))
+         = pg_column_size('a=>g, b=>gf'::hstore);
+ ?column? 
+----------
+ t
+(1 row)
+
+-- slice()
+select slice(hstore 'aa=>1, b=>2, c=>3', ARRAY['g','h','i']);
+ slice 
+-------
+(1 row)
+
+select slice(hstore 'aa=>1, b=>2, c=>3', ARRAY['c','b']);
+     slice      
+----------------
+ "b"=>2, "c"=>3
+(1 row)
+
+select slice(hstore 'aa=>1, b=>2, c=>3', ARRAY['aa','b']);
+      slice      
+-----------------
+ "b"=>2, "aa"=>1
+(1 row)
+
+select slice(hstore 'aa=>1, b=>2, c=>3', ARRAY['c','b','aa']);
+          slice          
+-------------------------
+ "b"=>2, "c"=>3, "aa"=>1
+(1 row)
+
+select pg_column_size(slice(hstore 'aa=>1, b=>2, c=>3', ARRAY['c','b']))
+         = pg_column_size('b=>2, c=>3'::hstore);
+ ?column? 
+----------
+ t
+(1 row)
+
+select pg_column_size(slice(hstore 'aa=>1, b=>2, c=>3', ARRAY['c','b','aa']))
+         = pg_column_size('aa=>1, b=>2, c=>3'::hstore);
+ ?column? 
+----------
+ t
+(1 row)
+
+-- array input
+select '{}'::text[]::hstore;
+ hstore 
+--------
+(1 row)
+
+select ARRAY['a','g','b','h','asd']::hstore;
+ERROR:  array must have even number of elements
+select ARRAY['a','g','b','h','asd','i']::hstore;
+             array              
+--------------------------------
+ "a"=>"g", "b"=>"h", "asd"=>"i"
+(1 row)
+
+select ARRAY[['a','g'],['b','h'],['asd','i']]::hstore;
+             array              
+--------------------------------
+ "a"=>"g", "b"=>"h", "asd"=>"i"
+(1 row)
+
+select ARRAY[['a','g','b'],['h','asd','i']]::hstore;
+ERROR:  array must have two columns
+select ARRAY[[['a','g'],['b','h'],['asd','i']]]::hstore;
+ERROR:  wrong number of array subscripts
+select hstore('{}'::text[]);
+ hstore 
+--------
+(1 row)
+
+select hstore(ARRAY['a','g','b','h','asd']);
+ERROR:  array must have even number of elements
+select hstore(ARRAY['a','g','b','h','asd','i']);
+             hstore             
+--------------------------------
+ "a"=>"g", "b"=>"h", "asd"=>"i"
+(1 row)
+
+select hstore(ARRAY[['a','g'],['b','h'],['asd','i']]);
+             hstore             
+--------------------------------
+ "a"=>"g", "b"=>"h", "asd"=>"i"
+(1 row)
+
+select hstore(ARRAY[['a','g','b'],['h','asd','i']]);
+ERROR:  array must have two columns
+select hstore(ARRAY[[['a','g'],['b','h'],['asd','i']]]);
+ERROR:  wrong number of array subscripts
+select hstore('[0:5]={a,g,b,h,asd,i}'::text[]);
+             hstore             
+--------------------------------
+ "a"=>"g", "b"=>"h", "asd"=>"i"
+(1 row)
+
+select hstore('[0:2][1:2]={{a,g},{b,h},{asd,i}}'::text[]);
+             hstore             
+--------------------------------
+ "a"=>"g", "b"=>"h", "asd"=>"i"
+(1 row)
+
+-- pairs of arrays
+select hstore(ARRAY['a','b','asd'], ARRAY['g','h','i']);
+             hstore             
+--------------------------------
+ "a"=>"g", "b"=>"h", "asd"=>"i"
+(1 row)
+
+select hstore(ARRAY['a','b','asd'], ARRAY['g','h',NULL]);
+             hstore              
+---------------------------------
+ "a"=>"g", "b"=>"h", "asd"=>NULL
+(1 row)
+
+select hstore(ARRAY['z','y','x'], ARRAY['1','2','3']);
+            hstore            
+------------------------------
+ "x"=>"3", "y"=>"2", "z"=>"1"
+(1 row)
+
+select hstore(ARRAY['aaa','bb','c','d'], ARRAY[null::text,null,null,null]);
+                    hstore                     
+-----------------------------------------------
+ "c"=>NULL, "d"=>NULL, "bb"=>NULL, "aaa"=>NULL
+(1 row)
+
+select hstore(ARRAY['aaa','bb','c','d'], null);
+                    hstore                     
+-----------------------------------------------
+ "c"=>NULL, "d"=>NULL, "bb"=>NULL, "aaa"=>NULL
+(1 row)
+
+select quote_literal(hstore('{}'::text[], '{}'::text[]));
+ quote_literal 
+---------------
+ ''
+(1 row)
+
+select quote_literal(hstore('{}'::text[], null));
+ quote_literal 
+---------------
+ ''
+(1 row)
+
+select hstore(ARRAY['a'], '{}'::text[]);  -- error
+ERROR:  arrays must have same bounds
+select hstore('{}'::text[], ARRAY['a']);  -- error
+ERROR:  arrays must have same bounds
+select pg_column_size(hstore(ARRAY['a','b','asd'], ARRAY['g','h','i']))
+         = pg_column_size('a=>g, b=>h, asd=>i'::hstore);
+ ?column? 
+----------
+ t
+(1 row)
+
+-- records
+select hstore(v) from (values (1, 'foo', 1.2, 3::float8)) v(a,b,c,d);
+                hstore                
+--------------------------------------
+ "a"=>1, "b"=>"foo", "c"=>1.2, "d"=>3
+(1 row)
+
+create domain hstestdom1 as integer not null default 0;
+create table testhstore0 (a integer, b text, c numeric, d float8);
+create table testhstore1 (a integer, b text, c numeric, d float8, e hstestdom1);
+insert into testhstore0 values (1, 'foo', 1.2, 3::float8);
+insert into testhstore1 values (1, 'foo', 1.2, 3::float8);
+select hstore(v) from testhstore1 v;
+                    hstore                    
+----------------------------------------------
+ "a"=>1, "b"=>"foo", "c"=>1.2, "d"=>3, "e"=>0
+(1 row)
+
+select hstore(null::testhstore0);
+                   hstore                   
+--------------------------------------------
+ "a"=>NULL, "b"=>NULL, "c"=>NULL, "d"=>NULL
+(1 row)
+
+select hstore(null::testhstore1);
+                        hstore                         
+-------------------------------------------------------
+ "a"=>NULL, "b"=>NULL, "c"=>NULL, "d"=>NULL, "e"=>NULL
+(1 row)
+
+select pg_column_size(hstore(v))
+         = pg_column_size('a=>1, b=>"foo", c=>1.2, d=>3, e=>0'::hstore)
+  from testhstore1 v;
+ ?column? 
+----------
+ t
+(1 row)
+
+select populate_record(v, hstore('c', '3.45')) from testhstore1 v;
+ populate_record  
+------------------
+ (1,foo,3.45,3,0)
+(1 row)
+
+select populate_record(v, hstore('d', '3.45')) from testhstore1 v;
+  populate_record   
+--------------------
+ (1,foo,1.2,3.45,0)
+(1 row)
+
+select populate_record(v, hstore('e', '123')) from testhstore1 v;
+  populate_record  
+-------------------
+ (1,foo,1.2,3,123)
+(1 row)
+
+select populate_record(v, hstore('e', null)) from testhstore1 v;
+ERROR:  domain hstestdom1 does not allow null values
+select populate_record(v, hstore('c', null)) from testhstore1 v;
+ populate_record 
+-----------------
+ (1,foo,,3,0)
+(1 row)
+
+select populate_record(v, hstore('b', 'foo') || hstore('a', '123')) from testhstore1 v;
+  populate_record  
+-------------------
+ (123,foo,1.2,3,0)
+(1 row)
+
+select populate_record(v, hstore('b', 'foo') || hstore('e', null)) from testhstore0 v;
+ populate_record 
+-----------------
+ (1,foo,1.2,3)
+(1 row)
+
+select populate_record(v, hstore('b', 'foo') || hstore('e', null)) from testhstore1 v;
+ERROR:  domain hstestdom1 does not allow null values
+select populate_record(v, '') from testhstore0 v;
+ populate_record 
+-----------------
+ (1,foo,1.2,3)
+(1 row)
+
+select populate_record(v, '') from testhstore1 v;
+ populate_record 
+-----------------
+ (1,foo,1.2,3,0)
+(1 row)
+
+select populate_record(null::testhstore1, hstore('c', '3.45') || hstore('a', '123'));
+ERROR:  domain hstestdom1 does not allow null values
+select populate_record(null::testhstore1, hstore('c', '3.45') || hstore('e', '123'));
+ populate_record 
+-----------------
+ (,,3.45,,123)
+(1 row)
+
+select populate_record(null::testhstore0, '');
+ populate_record 
+-----------------
+ (,,,)
+(1 row)
+
+select populate_record(null::testhstore1, '');
+ERROR:  domain hstestdom1 does not allow null values
+select v #= hstore('c', '3.45') from testhstore1 v;
+     ?column?     
+------------------
+ (1,foo,3.45,3,0)
+(1 row)
+
+select v #= hstore('d', '3.45') from testhstore1 v;
+      ?column?      
+--------------------
+ (1,foo,1.2,3.45,0)
+(1 row)
+
+select v #= hstore('e', '123') from testhstore1 v;
+     ?column?      
+-------------------
+ (1,foo,1.2,3,123)
+(1 row)
+
+select v #= hstore('c', null) from testhstore1 v;
+   ?column?   
+--------------
+ (1,foo,,3,0)
+(1 row)
+
+select v #= hstore('e', null) from testhstore0 v;
+   ?column?    
+---------------
+ (1,foo,1.2,3)
+(1 row)
+
+select v #= hstore('e', null) from testhstore1 v;
+ERROR:  domain hstestdom1 does not allow null values
+select v #= (hstore('b', 'foo') || hstore('a', '123')) from testhstore1 v;
+     ?column?      
+-------------------
+ (123,foo,1.2,3,0)
+(1 row)
+
+select v #= (hstore('b', 'foo') || hstore('e', '123')) from testhstore1 v;
+     ?column?      
+-------------------
+ (1,foo,1.2,3,123)
+(1 row)
+
+select v #= hstore '' from testhstore0 v;
+   ?column?    
+---------------
+ (1,foo,1.2,3)
+(1 row)
+
+select v #= hstore '' from testhstore1 v;
+    ?column?     
+-----------------
+ (1,foo,1.2,3,0)
+(1 row)
+
+select null::testhstore1 #= (hstore('c', '3.45') || hstore('a', '123'));
+ERROR:  domain hstestdom1 does not allow null values
+select null::testhstore1 #= (hstore('c', '3.45') || hstore('e', '123'));
+   ?column?    
+---------------
+ (,,3.45,,123)
+(1 row)
+
+select null::testhstore0 #= hstore '';
+ ?column? 
+----------
+ (,,,)
+(1 row)
+
+select null::testhstore1 #= hstore '';
+ERROR:  domain hstestdom1 does not allow null values
+select v #= h from testhstore1 v, (values (hstore 'a=>123',1),('b=>foo,c=>3.21',2),('a=>null',3),('e=>123',4),('f=>blah',5)) x(h,i) order by i;
+     ?column?      
+-------------------
+ (123,foo,1.2,3,0)
+ (1,foo,3.21,3,0)
+ (,foo,1.2,3,0)
+ (1,foo,1.2,3,123)
+ (1,foo,1.2,3,0)
+(5 rows)
+
+-- keys/values
+select akeys('aa=>1 , b=>2, cq=>3'::hstore || 'cq=>l, b=>g, fg=>f');
+    akeys     
+--------------
+ {b,aa,cq,fg}
+(1 row)
+
+select akeys('""=>1');
+ akeys 
+-------
+ {""}
+(1 row)
+
+select akeys('');
+ akeys 
+-------
+ {}
+(1 row)
+
+select avals('aa=>1 , b=>2, cq=>3'::hstore || 'cq=>l, b=>g, fg=>f');
+   avals   
+-----------
+ {g,1,l,f}
+(1 row)
+
+select avals('aa=>1 , b=>2, cq=>3'::hstore || 'cq=>l, b=>g, fg=>NULL');
+    avals     
+--------------
+ {g,1,l,NULL}
+(1 row)
+
+select avals('""=>1');
+ avals 
+-------
+ {1}
+(1 row)
+
+select avals('');
+ avals 
+-------
+ {}
+(1 row)
+
+select hstore_to_array('aa=>1, cq=>l, b=>g, fg=>NULL'::hstore);
+     hstore_to_array     
+-------------------------
+ {b,g,aa,1,cq,l,fg,NULL}
+(1 row)
+
+select %% 'aa=>1, cq=>l, b=>g, fg=>NULL';
+        ?column?         
+-------------------------
+ {b,g,aa,1,cq,l,fg,NULL}
+(1 row)
+
+select hstore_to_matrix('aa=>1, cq=>l, b=>g, fg=>NULL'::hstore);
+        hstore_to_matrix         
+---------------------------------
+ {{b,g},{aa,1},{cq,l},{fg,NULL}}
+(1 row)
+
+select %# 'aa=>1, cq=>l, b=>g, fg=>NULL';
+            ?column?             
+---------------------------------
+ {{b,g},{aa,1},{cq,l},{fg,NULL}}
+(1 row)
+
+select * from skeys('aa=>1 , b=>2, cq=>3'::hstore || 'cq=>l, b=>g, fg=>f');
+ skeys 
+-------
+ b
+ aa
+ cq
+ fg
+(4 rows)
+
+select * from skeys('""=>1');
+ skeys 
+-------
+(1 row)
+
+select * from skeys('');
+ skeys 
+-------
+(0 rows)
+
+select * from svals('aa=>1 , b=>2, cq=>3'::hstore || 'cq=>l, b=>g, fg=>f');
+ svals 
+-------
+ g
+ 1
+ l
+ f
+(4 rows)
+
+select *, svals is null from svals('aa=>1 , b=>2, cq=>3'::hstore || 'cq=>l, b=>g, fg=>NULL');
+ svals | ?column? 
+-------+----------
+ g     | f
+ 1     | f
+ l     | f
+       | t
+(4 rows)
+
+select * from svals('""=>1');
+ svals 
+-------
+ 1
+(1 row)
+
+select * from svals('');
+ svals 
+-------
+(0 rows)
+
+select * from each('aaa=>bq, b=>NULL, ""=>1 ');
+ key | value 
+-----+-------
+     | 1
+ b   | 
+ aaa | bq
+(3 rows)
+
+-- @>
+select 'a=>b, b=>1, c=>NULL'::hstore @> 'a=>b';
+ ?column? 
+----------
+ t
+(1 row)
+
+select 'a=>b, b=>1, c=>NULL'::hstore @> 'a=>b, c=>NULL';
+ ?column? 
+----------
+ t
+(1 row)
+
+select 'a=>b, b=>1, c=>NULL'::hstore @> 'a=>b, g=>NULL';
+ ?column? 
+----------
+ f
+(1 row)
+
+select 'a=>b, b=>1, c=>NULL'::hstore @> 'g=>NULL';
+ ?column? 
+----------
+ f
+(1 row)
+
+select 'a=>b, b=>1, c=>NULL'::hstore @> 'a=>c';
+ ?column? 
+----------
+ f
+(1 row)
+
+select 'a=>b, b=>1, c=>NULL'::hstore @> 'a=>b';
+ ?column? 
+----------
+ t
+(1 row)
+
+select 'a=>b, b=>1, c=>NULL'::hstore @> 'a=>b, c=>q';
+ ?column? 
+----------
+ f
+(1 row)
+
+CREATE TABLE testhstore (h hstore);
+\copy testhstore from 'data/hstore.data'
+select count(*) from testhstore where h @> 'wait=>NULL';
+ count 
+-------
+     1
+(1 row)
+
+select count(*) from testhstore where h @> 'wait=>CC';
+ count 
+-------
+    15
+(1 row)
+
+select count(*) from testhstore where h @> 'wait=>CC, public=>t';
+ count 
+-------
+     2
+(1 row)
+
+select count(*) from testhstore where h @> 'age=>25';
+ count 
+-------
+     2
+(1 row)
+
+select count(*) from testhstore where h @> 'age=>25.0';
+ count 
+-------
+     2
+(1 row)
+
+select count(*) from testhstore where h @> 'age=>+25.00';
+ count 
+-------
+     2
+(1 row)
+
+select count(*) from testhstore where h ? 'public';
+ count 
+-------
+   194
+(1 row)
+
+select count(*) from testhstore where h ?| ARRAY['public','disabled'];
+ count 
+-------
+   337
+(1 row)
+
+select count(*) from testhstore where h ?& ARRAY['public','disabled'];
+ count 
+-------
+    42
+(1 row)
+
+create index hidx on testhstore using gist(h);
+set enable_seqscan=off;
+select count(*) from testhstore where h @> 'wait=>NULL';
+ count 
+-------
+     1
+(1 row)
+
+select count(*) from testhstore where h @> 'wait=>CC';
+ count 
+-------
+    15
+(1 row)
+
+select count(*) from testhstore where h @> 'wait=>CC, public=>t';
+ count 
+-------
+     2
+(1 row)
+
+select count(*) from testhstore where h @> 'age=>25';
+ count 
+-------
+     2
+(1 row)
+
+select count(*) from testhstore where h @> 'age=>25.0';
+ count 
+-------
+     2
+(1 row)
+
+select count(*) from testhstore where h @> 'age=>+25.00';
+ count 
+-------
+     2
+(1 row)
+
+select count(*) from testhstore where h ? 'public';
+ count 
+-------
+   194
+(1 row)
+
+select count(*) from testhstore where h ?| ARRAY['public','disabled'];
+ count 
+-------
+   337
+(1 row)
+
+select count(*) from testhstore where h ?& ARRAY['public','disabled'];
+ count 
+-------
+    42
+(1 row)
+
+RESET enable_seqscan;
+drop index hidx;
+create index hidx on testhstore using gin (h);
+set enable_seqscan=off;
+select count(*) from testhstore where h @> 'wait=>NULL';
+ count 
+-------
+     1
+(1 row)
+
+select count(*) from testhstore where h @> 'wait=>CC';
+ count 
+-------
+    15
+(1 row)
+
+select count(*) from testhstore where h @> 'wait=>CC, public=>t';
+ count 
+-------
+     2
+(1 row)
+
+select count(*) from testhstore where h @> 'age=>25';
+ count 
+-------
+     2
+(1 row)
+
+select count(*) from testhstore where h @> 'age=>25.0';
+ count 
+-------
+     2
+(1 row)
+
+select count(*) from testhstore where h @> 'age=>+25.00';
+ count 
+-------
+     2
+(1 row)
+
+select count(*) from testhstore where h ? 'public';
+ count 
+-------
+   194
+(1 row)
+
+select count(*) from testhstore where h ?| ARRAY['public','disabled'];
+ count 
+-------
+   337
+(1 row)
+
+select count(*) from testhstore where h ?& ARRAY['public','disabled'];
+ count 
+-------
+    42
+(1 row)
+
+RESET enable_seqscan;
+select count(*) from (select (each(h)).key from testhstore) as wow ;
+ count 
+-------
+  4783
+(1 row)
+
+select key, count(*) from (select (each(h)).key from testhstore) as wow group by key order by count desc, key;
+    key    | count 
+-----------+-------
+ line      |   884
+ query     |   207
+ pos       |   203
+ node      |   202
+ space     |   197
+ status    |   195
+ public    |   194
+ title     |   190
+ wait      |   190
+ org       |   189
+ user      |   189
+ coauthors |   188
+ disabled  |   185
+ indexed   |   184
+ cleaned   |   180
+ bad       |   179
+ date      |   179
+ world     |   176
+ state     |   172
+ subtitle  |   169
+ auth      |   168
+ abstract  |   161
+ age       |     2
+(23 rows)
+
+-- sort/hash
+select count(distinct h) from testhstore;
+ count 
+-------
+   886
+(1 row)
+
+set enable_hashagg = false;
+select count(*) from (select h from (select * from testhstore union all select * from testhstore) hs group by h) hs2;
+ count 
+-------
+   886
+(1 row)
+
+set enable_hashagg = true;
+set enable_sort = false;
+select count(*) from (select h from (select * from testhstore union all select * from testhstore) hs group by h) hs2;
+ count 
+-------
+   886
+(1 row)
+
+select distinct * from (values (hstore '' || ''),('')) v(h);
+ h 
+---
+(1 row)
+
+set enable_sort = true;
+RESET enable_hashagg;
+RESET enable_sort;
+-- btree
+drop index hidx;
+create index hidx on testhstore using btree (h);
+set enable_seqscan=off;
+select count(*) from testhstore where h #># 'p=>1';
+ count 
+-------
+   886
+(1 row)
+
+select count(*) from testhstore where h = 'pos=>98, line=>371, node=>CBA, indexed=>t';
+ count 
+-------
+     1
+(1 row)
+
+--gin hash
+drop index hidx;
+create index hidx on testhstore using gin (h gin_hstore_hash_ops);
+set enable_seqscan=off;
+select count(*) from testhstore where h @> 'wait=>NULL';
+ count 
+-------
+     1
+(1 row)
+
+select count(*) from testhstore where h @> 'wait=>CC';
+ count 
+-------
+    15
+(1 row)
+
+select count(*) from testhstore where h @> 'wait=>CC, public=>t';
+ count 
+-------
+     2
+(1 row)
+
+select count(*) from testhstore where h @> 'age=>25';
+ count 
+-------
+     2
+(1 row)
+
+select count(*) from testhstore where h @> 'age=>25.0';
+ count 
+-------
+     2
+(1 row)
+
+select count(*) from testhstore where h @> 'age=>+25.00';
+ count 
+-------
+     2
+(1 row)
+
+RESET enable_seqscan;
+drop index hidx;
+-- json
+select hstore_to_json('"a key" =>1, b => t, c => null, d=> 12345, e => 012345, f=> 1.234, g=> 2.345e+4');
+                                   hstore_to_json                                   
+------------------------------------------------------------------------------------
+ {"b": true, "c": null, "d": 12345, "e": 12345, "f": 1.234, "g": 23450, "a key": 1}
+(1 row)
+
+select cast( hstore  '"a key" =>1, b => t, c => null, d=> 12345, e => 012345, f=> 1.234, g=> 2.345e+4' as json);
+                                        json                                        
+------------------------------------------------------------------------------------
+ {"b": true, "c": null, "d": 12345, "e": 12345, "f": 1.234, "g": 23450, "a key": 1}
+(1 row)
+
+select hstore_to_json_loose('"a key" =>1, b => t, c => null, d=> 12345, e => 012345, f=> 1.234, g=> 2.345e+4');
+                                hstore_to_json_loose                                
+------------------------------------------------------------------------------------
+ {"b": true, "c": null, "d": 12345, "e": 12345, "f": 1.234, "g": 23450, "a key": 1}
+(1 row)
+
+create table test_json_agg (f1 text, f2 hstore);
+insert into test_json_agg values ('rec1','"a key" =>1, b => t, c => null, d=> 12345, e => 012345, f=> 1.234, g=> 2.345e+4'),
+       ('rec2','"a key" =>2, b => f, c => "null", d=> -12345, e => 012345.6, f=> -1.234, g=> 0.345e-4');
+select json_agg(q) from test_json_agg q;
+                                                      json_agg                                                      
+--------------------------------------------------------------------------------------------------------------------
+ [{"f1":"rec1","f2":{"b": true, "c": null, "d": 12345, "e": 12345, "f": 1.234, "g": 23450, "a key": 1}},           +
+  {"f1":"rec2","f2":{"b": false, "c": "null", "d": -12345, "e": 12345.6, "f": -1.234, "g": 0.0000345, "a key": 2}}]
+(1 row)
+
+select json_agg(q) from (select f1, hstore_to_json_loose(f2) as f2 from test_json_agg) q;
+                                                      json_agg                                                      
+--------------------------------------------------------------------------------------------------------------------
+ [{"f1":"rec1","f2":{"b": true, "c": null, "d": 12345, "e": 12345, "f": 1.234, "g": 23450, "a key": 1}},           +
+  {"f1":"rec2","f2":{"b": false, "c": "null", "d": -12345, "e": 12345.6, "f": -1.234, "g": 0.0000345, "a key": 2}}]
+(1 row)
+
diff --git a/expected/nested.out b/expected/nested.out
new file mode 100644 (file)
index 0000000..f7df8cf
--- /dev/null
@@ -0,0 +1,2261 @@
+SELECT 'ff => {a=>12, b=>16}'::hstore;
+          hstore          
+--------------------------
+ "ff"=>{"a"=>12, "b"=>16}
+(1 row)
+
+SELECT 'ff => {a=>12, b=>16}, qq=> 123'::hstore;
+               hstore                
+-------------------------------------
+ "ff"=>{"a"=>12, "b"=>16}, "qq"=>123
+(1 row)
+
+SELECT 'aa => {a,aaa}, qq=>{ a=>12, b=>16 , c=> { c1, c2}, d=>{d1=>d1, d2=>d2, d1=>d3} }'::hstore;
+                                             hstore                                             
+------------------------------------------------------------------------------------------------
+ "aa"=>["a", "aaa"], "qq"=>{"a"=>12, "b"=>16, "c"=>["c1", "c2"], "d"=>{"d1"=>"d3", "d2"=>"d2"}}
+(1 row)
+
+SELECT '"aa"=>{a,aaa}, "qq"=>{"a"=>"12", "b"=>"16", "c"=>{c1,c2}, "d"=>{"d1"=>"d1", "d2"=>"d2"}}'::hstore;
+                                               hstore                                               
+----------------------------------------------------------------------------------------------------
+ "aa"=>["a", "aaa"], "qq"=>{"a"=>"12", "b"=>"16", "c"=>["c1", "c2"], "d"=>{"d1"=>"d1", "d2"=>"d2"}}
+(1 row)
+
+SELECT '"aa"=>{a,aaa}, "qq"=>{"a"=>"12", "b"=>"16", "c"=>{c1,c2,{c3},{c4=>4}}, "d"=>{"d1"=>"d1", "d2"=>"d2"}}'::hstore;
+                                                        hstore                                                         
+-----------------------------------------------------------------------------------------------------------------------
+ "aa"=>["a", "aaa"], "qq"=>{"a"=>"12", "b"=>"16", "c"=>["c1", "c2", ["c3"], {"c4"=>4}], "d"=>{"d1"=>"d1", "d2"=>"d2"}}
+(1 row)
+
+SELECT 'ff => {a,aaa}'::hstore;
+       hstore       
+--------------------
+ "ff"=>["a", "aaa"]
+(1 row)
+
+select 'null'::hstore;
+ hstore 
+--------
+ NULL
+(1 row)
+
+select '{null}'::hstore;
+ hstore 
+--------
+ [NULL]
+(1 row)
+
+select ''::hstore;
+ hstore 
+--------
+(1 row)
+
+select '{}'::hstore;
+ hstore 
+--------
+(1 row)
+
+--test optional outer braces
+SELECT 'a=>1'::hstore;
+ hstore 
+--------
+ "a"=>1
+(1 row)
+
+SELECT '{a=>1}'::hstore;
+ hstore 
+--------
+ "a"=>1
+(1 row)
+
+SELECT '{a,b}'::hstore;
+   hstore   
+------------
+ ["a", "b"]
+(1 row)
+
+SELECT '{a,{b}}'::hstore;
+    hstore    
+--------------
+ ["a", ["b"]]
+(1 row)
+
+SELECT '{{a},b}'::hstore;
+    hstore    
+--------------
+ [["a"], "b"]
+(1 row)
+
+SELECT '{a,{b},{c}}'::hstore;
+       hstore        
+---------------------
+ ["a", ["b"], ["c"]]
+(1 row)
+
+SELECT '{{a},{b},c}'::hstore;
+       hstore        
+---------------------
+ [["a"], ["b"], "c"]
+(1 row)
+
+SELECT '{{a},b,{c}}'::hstore;
+       hstore        
+---------------------
+ [["a"], "b", ["c"]]
+(1 row)
+
+SELECT '{a,{b=>1}}'::hstore;
+     hstore      
+-----------------
+ ["a", {"b"=>1}]
+(1 row)
+
+SELECT '{{a},{b=>1}}'::hstore;
+      hstore       
+-------------------
+ [["a"], {"b"=>1}]
+(1 row)
+
+SELECT 'a'::hstore;
+ hstore 
+--------
+ "a"
+(1 row)
+
+SELECT '{a}'::hstore;
+ hstore 
+--------
+ ["a"]
+(1 row)
+
+SELECT ''::hstore;
+ hstore 
+--------
+(1 row)
+
+SELECT '{}'::hstore;
+ hstore 
+--------
+(1 row)
+
+--nested json
+SELECT hstore_to_json('a=>1');
+ hstore_to_json 
+----------------
+ {"a": 1}
+(1 row)
+
+SELECT hstore_to_json('{a=>1}');
+ hstore_to_json 
+----------------
+ {"a": 1}
+(1 row)
+
+SELECT hstore_to_json('{a,b}');
+ hstore_to_json 
+----------------
+ ["a", "b"]
+(1 row)
+
+SELECT hstore_to_json('{a,{b}}');
+ hstore_to_json 
+----------------
+ ["a", ["b"]]
+(1 row)
+
+SELECT hstore_to_json('{{a},b}');
+ hstore_to_json 
+----------------
+ [["a"], "b"]
+(1 row)
+
+SELECT hstore_to_json('{a,{b},{c}}');
+   hstore_to_json    
+---------------------
+ ["a", ["b"], ["c"]]
+(1 row)
+
+SELECT hstore_to_json('{{a},{b},c}');
+   hstore_to_json    
+---------------------
+ [["a"], ["b"], "c"]
+(1 row)
+
+SELECT hstore_to_json('{{a},b,{c}}');
+   hstore_to_json    
+---------------------
+ [["a"], "b", ["c"]]
+(1 row)
+
+SELECT hstore_to_json('{a,{b=>1}}');
+ hstore_to_json  
+-----------------
+ ["a", {"b": 1}]
+(1 row)
+
+SELECT hstore_to_json('{{a},{b=>1}}');
+  hstore_to_json   
+-------------------
+ [["a"], {"b": 1}]
+(1 row)
+
+SELECT hstore_to_json('{{a},{b=>1},{c}}');
+      hstore_to_json      
+--------------------------
+ [["a"], {"b": 1}, ["c"]]
+(1 row)
+
+SELECT hstore_to_json('a');
+ hstore_to_json 
+----------------
+ "a"
+(1 row)
+
+SELECT hstore_to_json('{a}');
+ hstore_to_json 
+----------------
+ ["a"]
+(1 row)
+
+SELECT hstore_to_json('');
+ hstore_to_json 
+----------------
+ {}
+(1 row)
+
+SELECT hstore_to_json('{}');
+ hstore_to_json 
+----------------
+ {}
+(1 row)
+
+SELECT hstore_to_json('"aa"=>{a,aaa}, "qq"=>{"a"=>"12", "b"=>"16", "c"=>{c1,c2,{c3},{c4=>4}}, "d"=>{"d1"=>"d1", "d2"=>"d2"}}'::hstore);
+                                                     hstore_to_json                                                      
+-------------------------------------------------------------------------------------------------------------------------
+ {"aa": ["a", "aaa"], "qq": {"a": "12", "b": "16", "c": ["c1", "c2", ["c3"], {"c4": 4}], "d": {"d1": "d1", "d2": "d2"}}}
+(1 row)
+
+--
+SELECT 'ff => {a=>12, b=>16}, qq=> 123, x=>{1,2}, Y=>NULL'::hstore -> 'ff', 
+          'ff => {a=>12, b=>16}, qq=> 123, x=>{1,2}, Y=>NULL'::hstore -> 'qq', 
+          ('ff => {a=>12, b=>16}, qq=> 123, x=>{1,2}, Y=>NULL'::hstore -> 'Y') IS NULL AS t, 
+          'ff => {a=>12, b=>16}, qq=> 123, x=>{1,2}, Y=>NULL'::hstore -> 'x'; 
+     ?column?     | ?column? | t | ?column? 
+------------------+----------+---+----------
+ "a"=>12, "b"=>16 | 123      | t | [1, 2]
+(1 row)
+
+SELECT '[ a, b, c, d]'::hstore -> 'a';
+ ?column? 
+----------
+ a
+(1 row)
+
+--
+CREATE TABLE testtype (i int, h hstore, a int[], j json);
+INSERT INTO testtype VALUES (1, 'a=>1', '{1,2,3}', '{"x": 2}');
+SELECT populate_record(v, 'i=>2'::hstore) FROM testtype v;
+            populate_record            
+---------------------------------------
+ (2,"""a""=>1","{1,2,3}","{""x"": 2}")
+(1 row)
+
+SELECT populate_record(v, 'i=>2, a=>{7,8,9}'::hstore) FROM testtype v;
+            populate_record            
+---------------------------------------
+ (2,"""a""=>1","{7,8,9}","{""x"": 2}")
+(1 row)
+
+SELECT populate_record(v, 'i=>2, h=>{b=>3}, a=>{7,8,9}'::hstore) FROM testtype v;
+            populate_record            
+---------------------------------------
+ (2,"""b""=>3","{7,8,9}","{""x"": 2}")
+(1 row)
+
+SELECT populate_record(v, 'i=>2, h=>{b=>3}, a=>{7,8,9}, j=>{a=>{1,2,3}}'::hstore) FROM testtype v;
+                populate_record                
+-----------------------------------------------
+ (2,"""b""=>3","{7,8,9}","{""a"": [1, 2, 3]}")
+(1 row)
+
+--complex delete
+SELECT 'b=>{a,c}'::hstore - 'a'::text;
+    ?column?     
+-----------------
+ "b"=>["a", "c"]
+(1 row)
+
+SELECT 'b=>{a,c}, a=>1'::hstore - 'a'::text;
+    ?column?     
+-----------------
+ "b"=>["a", "c"]
+(1 row)
+
+SELECT 'b=>{a,c}, a=>[2,3]'::hstore - 'a'::text;
+    ?column?     
+-----------------
+ "b"=>["a", "c"]
+(1 row)
+
+SELECT 'b=>{a,c}, a=>[2,3]'::hstore - 'a'::text;
+    ?column?     
+-----------------
+ "b"=>["a", "c"]
+(1 row)
+
+SELECT '[2,3,a]'::hstore - 'a'::text;
+ ?column? 
+----------
+ [2, 3]
+(1 row)
+
+SELECT '[a,2,3,a]'::hstore - 'a'::text;
+ ?column? 
+----------
+ [2, 3]
+(1 row)
+
+SELECT '[a,a]'::hstore - 'a'::text;
+ ?column? 
+----------
+(1 row)
+
+SELECT '[a]'::hstore - 'a'::text;
+ ?column? 
+----------
+(1 row)
+
+SELECT 'a=>1'::hstore - 'a'::text;
+ ?column? 
+----------
+(1 row)
+
+SELECT ''::hstore - 'a'::text;
+ ?column? 
+----------
+(1 row)
+
+SELECT '{a, 1 , b,2, c,3}'::hstore - ARRAY['d','b'];
+      ?column?       
+---------------------
+ ["a", 1, 2, "c", 3]
+(1 row)
+
+SELECT '{a=>{1,2}, v=>23, b=>c}'::hstore - 'v'::hstore;
+       ?column?        
+-----------------------
+ "a"=>[1, 2], "b"=>"c"
+(1 row)
+
+SELECT '{a=>{1,2}, v=>23, b=>c}'::hstore - 'v=>23'::hstore;
+       ?column?        
+-----------------------
+ "a"=>[1, 2], "b"=>"c"
+(1 row)
+
+SELECT '{a=>{1,2}, v=>23, b=>c}'::hstore - 'v=>{1,2}'::hstore;
+            ?column?            
+--------------------------------
+ "a"=>[1, 2], "b"=>"c", "v"=>23
+(1 row)
+
+SELECT '{a=>{1,2}, v=>23, b=>c}'::hstore - 'a=>{1,2}'::hstore;
+     ?column?      
+-------------------
+ "b"=>"c", "v"=>23
+(1 row)
+
+SELECT '{a, {1,2}, v, 23, b, c}'::hstore - 'v'::hstore;
+          ?column?           
+-----------------------------
+ ["a", [1, 2], 23, "b", "c"]
+(1 row)
+
+SELECT '{a, {1,2}, v, 23, b, c}'::hstore - 'v=>23'::hstore;
+        ?column?         
+-------------------------
+ ["a", [1, 2], "b", "c"]
+(1 row)
+
+SELECT '{a, {1,2}, v, 23, b, c}'::hstore - '[v,23]'::hstore;
+        ?column?         
+-------------------------
+ ["a", [1, 2], "b", "c"]
+(1 row)
+
+SELECT '{a, {1,2}, v, 23, b, c}'::hstore - '[v,{1,2}]'::hstore;
+      ?column?       
+---------------------
+ ["a", 23, "b", "c"]
+(1 row)
+
+--joining
+SELECT 'aa=>1 , b=>2, cq=>3'::hstore || '{cq,l, b,g, fg,f, 1,2}'::hstore;
+                   ?column?                    
+-----------------------------------------------
+ "1"=>2, "b"=>"g", "aa"=>1, "cq"=>"l", "fg"=>f
+(1 row)
+
+SELECT '{aa,1 , b,2, cq,3}'::hstore || '{cq,l, b,g, fg,f, 1,2}'::hstore;
+                            ?column?                            
+----------------------------------------------------------------
+ ["aa", 1, "b", 2, "cq", 3, "cq", "l", "b", "g", "fg", f, 1, 2]
+(1 row)
+
+SELECT  'x'::hstore || 'a=>"1"':: hstore;
+    ?column?     
+-----------------
+ ["x", "a", "1"]
+(1 row)
+
+--slice
+SELECT slice_array(hstore 'aa=>1, b=>2, c=>3', ARRAY['g','h','i']);
+   slice_array    
+------------------
+ {NULL,NULL,NULL}
+(1 row)
+
+SELECT slice_array(hstore '{aa,1, b,2, c,3}', ARRAY['g','h','i']);
+   slice_array    
+------------------
+ {NULL,NULL,NULL}
+(1 row)
+
+SELECT slice_array(hstore 'aa=>1, b=>2, c=>3', ARRAY['b','c']);
+ slice_array 
+-------------
+ {2,3}
+(1 row)
+
+SELECT slice_array(hstore '{aa,1, b,2, c,3}', ARRAY['b','c']);
+ slice_array 
+-------------
+ {b,c}
+(1 row)
+
+SELECT slice_array(hstore 'aa=>1, b=>{2=>1}, c=>{1,2}', ARRAY['b','c']);
+      slice_array      
+-----------------------
+ {"\"2\"=>1","[1, 2]"}
+(1 row)
+
+SELECT slice(hstore '{aa=>1, b=>2, c=>3}', ARRAY['g','h','i']);
+ slice 
+-------
+(1 row)
+
+SELECT slice(hstore '{aa,1, b,2, c,3}', ARRAY['g','h','i']);
+ slice 
+-------
+(1 row)
+
+SELECT slice(hstore '{aa=>1, b=>2, c=>3}', ARRAY['b','c']);
+     slice      
+----------------
+ "b"=>2, "c"=>3
+(1 row)
+
+SELECT slice(hstore '{aa,1, b,2, c,3}', ARRAY['b','c']);
+   slice    
+------------
+ ["b", "c"]
+(1 row)
+
+SELECT slice(hstore '{aa=>1, b=>{2=>1}, c=>{1,2}}', ARRAY['b','c']);
+           slice            
+----------------------------
+ "b"=>{"2"=>1}, "c"=>[1, 2]
+(1 row)
+
+--to array
+SELECT %% 'aa=>1, cq=>l, b=>{a,n}, fg=>NULL';
+                ?column?                
+----------------------------------------
+ {b,"[\"a\", \"n\"]",aa,1,cq,l,fg,NULL}
+(1 row)
+
+SELECT %% '{aa,1, cq,l, b,g, fg,NULL}';
+        ?column?         
+-------------------------
+ {aa,1,cq,l,b,g,fg,NULL}
+(1 row)
+
+SELECT hstore_to_matrix( 'aa=>1, cq=>l, b=>{a,n}, fg=>NULL');
+                hstore_to_matrix                
+------------------------------------------------
+ {{b,"[\"a\", \"n\"]"},{aa,1},{cq,l},{fg,NULL}}
+(1 row)
+
+SELECT hstore_to_matrix( '{aa,1, cq,l, b,g, fg,NULL}');
+        hstore_to_matrix         
+---------------------------------
+ {{aa,1},{cq,l},{b,g},{fg,NULL}}
+(1 row)
+
+--contains
+SELECT 'a=>b'::hstore @> 'a=>b, c=>b';
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT 'a=>b, c=>b'::hstore @> 'a=>b';
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'a=>{1,2}, c=>b'::hstore @> 'a=>{1,2}';
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'a=>{2,1}, c=>b'::hstore @> 'a=>{1,2}';
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'a=>{1=>2}, c=>b'::hstore @> 'a=>{1,2}';
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT 'a=>{2=>1}, c=>b'::hstore @> 'a=>{1,2}';
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT 'a=>{1=>2}, c=>b'::hstore @> 'a=>{1=>2}';
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'a=>{2=>1}, c=>b'::hstore @> 'a=>{1=>2}';
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT '{a,b}'::hstore @> '{a,b, c,b}';
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT '{a,b, c,b}'::hstore @> '{a,b}';
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT '{a,b, c,{1,2}}'::hstore @> '{a,{1,2}}';
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT '{a,b, c,{1,2}}'::hstore @> '{b,{1,2}}';
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'a=>{1,2}, c=>b'::hstore @> 'a=>{1}';
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'a=>{1,2}, c=>b'::hstore @> 'a=>{2}';
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'a=>{1,2}, c=>b'::hstore @> 'a=>{3}';
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT 'a=>{1,2,{c=>3, x=>4}}, c=>b'::hstore @> 'a=>{{c=>3}}';
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'a=>{1,2,{c=>3, x=>4}}, c=>b'::hstore @> 'a=>{{x=>4}}';
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'a=>{1,2,{c=>3, x=>4}}, c=>b'::hstore @> 'a=>{{x=>4},3}';
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT 'a=>{1,2,{c=>3, x=>4}}, c=>b'::hstore @> 'a=>{{x=>4},1}';
+ ?column? 
+----------
+ t
+(1 row)
+
+-- %>
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 'n';
+ ?column? 
+----------
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 'a';
+ ?column? 
+----------
+ 1
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 'b';
+ ?column? 
+----------
+ [1, 2]
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 'c';
+ ?column? 
+----------
+ "1"=>2
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 'd';
+  ?column?   
+-------------
+ "1"=>[2, 3]
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 'd' %> '1';
+ ?column? 
+----------
+ [2, 3]
+(1 row)
+
+SELECT '[1,2,3,{a,b}]'::hstore %> '1';
+ ?column? 
+----------
+(1 row)
+
+SELECT '["1",2,3,{a,b}]'::hstore %> '1';
+ ?column? 
+----------
+ "1"
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 5;
+ ?column? 
+----------
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 4;
+ ?column? 
+----------
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 3;
+  ?column?   
+-------------
+ "1"=>[2, 3]
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 2;
+ ?column? 
+----------
+ "1"=>2
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 1;
+ ?column? 
+----------
+ [1, 2]
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 0;
+ ?column? 
+----------
+ 1
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore %> 5;
+ ?column? 
+----------
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore %> 4;
+ ?column? 
+----------
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore %> 3;
+ ?column? 
+----------
+ [1, 2]
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore %> 2;
+ ?column? 
+----------
+ "c"
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore %> 1;
+ ?column? 
+----------
+ "b"
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore %> 0;
+ ?column? 
+----------
+ "a"
+(1 row)
+
+-- ->
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> 5;
+ ?column? 
+----------
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> 4;
+ ?column? 
+----------
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> 3;
+  ?column?   
+-------------
+ "1"=>[2, 3]
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> 2;
+ ?column? 
+----------
+ "1"=>2
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> 1;
+ ?column? 
+----------
+ [1, 2]
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> 0;
+ ?column? 
+----------
+ 1
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> 5;
+ ?column? 
+----------
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> 4;
+ ?column? 
+----------
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> 3;
+ ?column? 
+----------
+ [1, 2]
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> 2;
+ ?column? 
+----------
+ c
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> 1;
+ ?column? 
+----------
+ b
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> 0;
+ ?column? 
+----------
+ a
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> -6;
+ ?column? 
+----------
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> -5;
+ ?column? 
+----------
+ 1
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> -4;
+ ?column? 
+----------
+ [1, 2]
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> -3;
+ ?column? 
+----------
+ "1"=>2
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> -2;
+  ?column?   
+-------------
+ "1"=>[2, 3]
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> -1;
+ ?column? 
+----------
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> -6;
+ ?column? 
+----------
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> -5;
+ ?column? 
+----------
+ a
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> -4;
+ ?column? 
+----------
+ b
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> -3;
+ ?column? 
+----------
+ c
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> -2;
+ ?column? 
+----------
+ [1, 2]
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> -1;
+ ?column? 
+----------
+(1 row)
+
+-- #>
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{0}';
+ ?column? 
+----------
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{a}';
+ ?column? 
+----------
+ b
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{c}';
+ ?column?  
+-----------
+ [1, 2, 3]
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{c, 0}';
+ ?column? 
+----------
+ 1
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{c, 1}';
+ ?column? 
+----------
+ 2
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{c, 2}';
+ ?column? 
+----------
+ 3
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{c, 3}';
+ ?column? 
+----------
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{c, -1}';
+ ?column? 
+----------
+ 3
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{c, -2}';
+ ?column? 
+----------
+ 2
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{c, -3}';
+ ?column? 
+----------
+ 1
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{c, -4}';
+ ?column? 
+----------
+(1 row)
+
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #> '{0}';
+ ?column? 
+----------
+ 0
+(1 row)
+
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #> '{3}';
+ ?column? 
+----------
+ [3, 4]
+(1 row)
+
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #> '{4}';
+  ?column?   
+-------------
+ "5"=>"five"
+(1 row)
+
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #> '{4,5}';
+ ?column? 
+----------
+ five
+(1 row)
+
+-- #%>
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{0}';
+ ?column? 
+----------
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{a}';
+ ?column? 
+----------
+ "b"
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{c}';
+ ?column?  
+-----------
+ [1, 2, 3]
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{c, 0}';
+ ?column? 
+----------
+ 1
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{c, 1}';
+ ?column? 
+----------
+ 2
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{c, 2}';
+ ?column? 
+----------
+ 3
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{c, 3}';
+ ?column? 
+----------
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{c, -1}';
+ ?column? 
+----------
+ 3
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{c, -2}';
+ ?column? 
+----------
+ 2
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{c, -3}';
+ ?column? 
+----------
+ 1
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{c, -4}';
+ ?column? 
+----------
+(1 row)
+
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #%> '{0}';
+ ?column? 
+----------
+ 0
+(1 row)
+
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #%> '{3}';
+ ?column? 
+----------
+ [3, 4]
+(1 row)
+
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #%> '{4}';
+  ?column?   
+-------------
+ "5"=>"five"
+(1 row)
+
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #%> '{4,5}';
+ ?column? 
+----------
+ "five"
+(1 row)
+
+-- ?
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? 5;
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? 4;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? 3;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? 2;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? 1;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? 0;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? 5;
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? 4;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? 3;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? 2;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? 1;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? 0;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? -6;
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? -5;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? -4;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? -3;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? -2;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? -1;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? -6;
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? -5;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? -4;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? -3;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? -2;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? -1;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{0}'::text[];
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{a}'::text[];
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{c}'::text[];
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{b}'::text[];
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{c, 0}'::text[];
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{c, 1}'::text[];
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{c, 2}'::text[];
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{c, 3}'::text[];
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{c, -1}'::text[];
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{c, -2}'::text[];
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{c, -3}'::text[];
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{c, -4}'::text[];
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{c, -5}'::text[];
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #? '{0}'::text[];
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #? '{3}'::text[];
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #? '{4}'::text[];
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #? '{4,5}'::text[];
+ ?column? 
+----------
+ t
+(1 row)
+
+--deep delete
+SELECT 'a=>1'::hstore #- '{x}';
+ ?column? 
+----------
+ "a"=>1
+(1 row)
+
+SELECT 'a=>1'::hstore #- '{a}';
+ ?column? 
+----------
+(1 row)
+
+SELECT 'a=>1'::hstore #- '{NULL}';
+ ?column? 
+----------
+ "a"=>1
+(1 row)
+
+SELECT 'a=>1, b=>2, c=>3'::hstore #- '{x}';
+        ?column?        
+------------------------
+ "a"=>1, "b"=>2, "c"=>3
+(1 row)
+
+SELECT 'a=>1, b=>2, c=>3'::hstore #- '{a}';
+    ?column?    
+----------------
+ "b"=>2, "c"=>3
+(1 row)
+
+SELECT 'a=>1, b=>2, c=>3'::hstore #- '{b}';
+    ?column?    
+----------------
+ "a"=>1, "c"=>3
+(1 row)
+
+SELECT 'a=>1, b=>2, c=>3'::hstore #- '{c}';
+    ?column?    
+----------------
+ "a"=>1, "b"=>2
+(1 row)
+
+SELECT 'a=>1'::hstore #- '{x,1}';
+ ?column? 
+----------
+ "a"=>1
+(1 row)
+
+SELECT 'a=>1'::hstore #- '{a,1}';
+ ?column? 
+----------
+ "a"=>1
+(1 row)
+
+SELECT 'a=>1'::hstore #- '{NULL,1}';
+ ?column? 
+----------
+ "a"=>1
+(1 row)
+
+SELECT 'a=>1, b=>2, c=>3'::hstore #- '{x,1}';
+        ?column?        
+------------------------
+ "a"=>1, "b"=>2, "c"=>3
+(1 row)
+
+SELECT 'a=>1, b=>2, c=>3'::hstore #- '{a,1}';
+        ?column?        
+------------------------
+ "a"=>1, "b"=>2, "c"=>3
+(1 row)
+
+SELECT 'a=>1, b=>2, c=>3'::hstore #- '{b,1}';
+        ?column?        
+------------------------
+ "a"=>1, "b"=>2, "c"=>3
+(1 row)
+
+SELECT 'a=>1, b=>2, c=>3'::hstore #- '{c,1}';
+        ?column?        
+------------------------
+ "a"=>1, "b"=>2, "c"=>3
+(1 row)
+
+SELECT '[a]'::hstore #- '{2}';
+ ?column? 
+----------
+ ["a"]
+(1 row)
+
+SELECT '[a]'::hstore #- '{1}';
+ ?column? 
+----------
+ ["a"]
+(1 row)
+
+SELECT '[a]'::hstore #- '{0}';
+ ?column? 
+----------
+(1 row)
+
+SELECT '[a]'::hstore #- '{-1}';
+ ?column? 
+----------
+(1 row)
+
+SELECT '[a]'::hstore #- '{-2}';
+ ?column? 
+----------
+ ["a"]
+(1 row)
+
+SELECT '[a,b,c]'::hstore #- '{3}';
+    ?column?     
+-----------------
+ ["a", "b", "c"]
+(1 row)
+
+SELECT '[a,b,c]'::hstore #- '{2}';
+  ?column?  
+------------
+ ["a", "b"]
+(1 row)
+
+SELECT '[a,b,c]'::hstore #- '{1}';
+  ?column?  
+------------
+ ["a", "c"]
+(1 row)
+
+SELECT '[a,b,c]'::hstore #- '{0}';
+  ?column?  
+------------
+ ["b", "c"]
+(1 row)
+
+SELECT '[a,b,c]'::hstore #- '{-1}';
+  ?column?  
+------------
+ ["a", "b"]
+(1 row)
+
+SELECT '[a,b,c]'::hstore #- '{-2}';
+  ?column?  
+------------
+ ["a", "c"]
+(1 row)
+
+SELECT '[a,b,c]'::hstore #- '{-3}';
+  ?column?  
+------------
+ ["b", "c"]
+(1 row)
+
+SELECT '[a,b,c]'::hstore #- '{-4}';
+    ?column?     
+-----------------
+ ["a", "b", "c"]
+(1 row)
+
+SELECT '[a,b,c]'::hstore #- '{0,0}';
+    ?column?     
+-----------------
+ ["a", "b", "c"]
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{x}';
+                             ?column?                              
+-------------------------------------------------------------------
+ "a"=>1, "b"=>[1, 2], "c"=>{"1"=>2}, "d"=>{"1"=>[2, 3]}, "n"=>NULL
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{a}';
+                         ?column?                          
+-----------------------------------------------------------
+ "b"=>[1, 2], "c"=>{"1"=>2}, "d"=>{"1"=>[2, 3]}, "n"=>NULL
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{b}';
+                       ?column?                       
+------------------------------------------------------
+ "a"=>1, "c"=>{"1"=>2}, "d"=>{"1"=>[2, 3]}, "n"=>NULL
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{c}';
+                      ?column?                      
+----------------------------------------------------
+ "a"=>1, "b"=>[1, 2], "d"=>{"1"=>[2, 3]}, "n"=>NULL
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{d}';
+                   ?column?                    
+-----------------------------------------------
+ "a"=>1, "b"=>[1, 2], "c"=>{"1"=>2}, "n"=>NULL
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{b, 0}';
+                            ?column?                            
+----------------------------------------------------------------
+ "a"=>1, "b"=>[2], "c"=>{"1"=>2}, "d"=>{"1"=>[2, 3]}, "n"=>NULL
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{b, -1}';
+                            ?column?                            
+----------------------------------------------------------------
+ "a"=>1, "b"=>[1], "c"=>{"1"=>2}, "d"=>{"1"=>[2, 3]}, "n"=>NULL
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{b, -1}' #- '{b, -1}';
+                            ?column?                             
+-----------------------------------------------------------------
+ "a"=>1, "b"=>NULL, "c"=>{"1"=>2}, "d"=>{"1"=>[2, 3]}, "n"=>NULL
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{c, 1}';
+                           ?column?                            
+---------------------------------------------------------------
+ "a"=>1, "b"=>[1, 2], "c"=>NULL, "d"=>{"1"=>[2, 3]}, "n"=>NULL
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{c, 2}';
+                             ?column?                              
+-------------------------------------------------------------------
+ "a"=>1, "b"=>[1, 2], "c"=>{"1"=>2}, "d"=>{"1"=>[2, 3]}, "n"=>NULL
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{d, 1, -2}';
+                            ?column?                            
+----------------------------------------------------------------
+ "a"=>1, "b"=>[1, 2], "c"=>{"1"=>2}, "d"=>{"1"=>[3]}, "n"=>NULL
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{d, 1, 1}';
+                            ?column?                            
+----------------------------------------------------------------
+ "a"=>1, "b"=>[1, 2], "c"=>{"1"=>2}, "d"=>{"1"=>[2]}, "n"=>NULL
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{d, 1, 0}';
+                            ?column?                            
+----------------------------------------------------------------
+ "a"=>1, "b"=>[1, 2], "c"=>{"1"=>2}, "d"=>{"1"=>[3]}, "n"=>NULL
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{d, 1, 0}' #- '{d, 1, 0}';
+                            ?column?                             
+-----------------------------------------------------------------
+ "a"=>1, "b"=>[1, 2], "c"=>{"1"=>2}, "d"=>{"1"=>NULL}, "n"=>NULL
+(1 row)
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{d, 1, 0}' #- '{d, 1, 0}' #- '{d, 1, 0}';
+                            ?column?                             
+-----------------------------------------------------------------
+ "a"=>1, "b"=>[1, 2], "c"=>{"1"=>2}, "d"=>{"1"=>NULL}, "n"=>NULL
+(1 row)
+
+-- delete(int)
+SELECT '[a,b,c]'::hstore - 3;
+    ?column?     
+-----------------
+ ["a", "b", "c"]
+(1 row)
+
+SELECT '[a,b,c]'::hstore - 2;
+  ?column?  
+------------
+ ["a", "b"]
+(1 row)
+
+SELECT '[a,b,c]'::hstore - 1;
+  ?column?  
+------------
+ ["a", "c"]
+(1 row)
+
+SELECT '[a,b,c]'::hstore - 0;
+  ?column?  
+------------
+ ["b", "c"]
+(1 row)
+
+SELECT '[a,b,c]'::hstore - -1;
+  ?column?  
+------------
+ ["a", "b"]
+(1 row)
+
+SELECT '[a,b,c]'::hstore - -2;
+  ?column?  
+------------
+ ["a", "c"]
+(1 row)
+
+SELECT '[a,b,c]'::hstore - -3;
+  ?column?  
+------------
+ ["b", "c"]
+(1 row)
+
+SELECT '[a,b,c]'::hstore - -4;
+    ?column?     
+-----------------
+ ["a", "b", "c"]
+(1 row)
+
+SELECT 'a=>1, b=>2, c=>3'::hstore - 3;
+        ?column?        
+------------------------
+ "a"=>1, "b"=>2, "c"=>3
+(1 row)
+
+SELECT 'a=>1, b=>2, c=>3'::hstore - 2;
+    ?column?    
+----------------
+ "a"=>1, "b"=>2
+(1 row)
+
+SELECT 'a=>1, b=>2, c=>3'::hstore - 1;
+    ?column?    
+----------------
+ "a"=>1, "c"=>3
+(1 row)
+
+SELECT 'a=>1, b=>2, c=>3'::hstore - 0;
+    ?column?    
+----------------
+ "b"=>2, "c"=>3
+(1 row)
+
+SELECT 'a=>1, b=>2, c=>3'::hstore - -1;
+    ?column?    
+----------------
+ "a"=>1, "b"=>2
+(1 row)
+
+SELECT 'a=>1, b=>2, c=>3'::hstore - -2;
+    ?column?    
+----------------
+ "a"=>1, "c"=>3
+(1 row)
+
+SELECT 'a=>1, b=>2, c=>3'::hstore - -3;
+    ?column?    
+----------------
+ "b"=>2, "c"=>3
+(1 row)
+
+SELECT 'a=>1, b=>2, c=>3'::hstore - -4;
+        ?column?        
+------------------------
+ "a"=>1, "b"=>2, "c"=>3
+(1 row)
+
+--replace
+SELECT replace('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{n}', '{1,2,3}');
+                                replace                                 
+------------------------------------------------------------------------
+ "a"=>1, "b"=>[1, 2], "c"=>{"1"=>2}, "d"=>{"1"=>[2, 3]}, "n"=>[1, 2, 3]
+(1 row)
+
+SELECT replace('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{b,-1}', '{1,2,3}');
+                                  replace                                  
+---------------------------------------------------------------------------
+ "a"=>1, "b"=>[1, [1, 2, 3]], "c"=>{"1"=>2}, "d"=>{"1"=>[2, 3]}, "n"=>NULL
+(1 row)
+
+SELECT replace('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{d,1,0}', '{1,2,3}');
+                                  replace                                  
+---------------------------------------------------------------------------
+ "a"=>1, "b"=>[1, 2], "c"=>{"1"=>2}, "d"=>{"1"=>[[1, 2, 3], 3]}, "n"=>NULL
+(1 row)
+
+SELECT replace('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{d,NULL,0}', '{1,2,3}');
+                              replace                              
+-------------------------------------------------------------------
+ "a"=>1, "b"=>[1, 2], "c"=>{"1"=>2}, "d"=>{"1"=>[2, 3]}, "n"=>NULL
+(1 row)
+
+--deep concat
+SELECT concat_path('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{}', 'n=>not_null');
+                               concat_path                               
+-------------------------------------------------------------------------
+ "a"=>1, "b"=>[1, 2], "c"=>{"1"=>2}, "d"=>{"1"=>[2, 3]}, "n"=>"not_null"
+(1 row)
+
+SELECT concat_path('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{n}', 'n=>not_null');
+                                  concat_path                                   
+--------------------------------------------------------------------------------
+ "a"=>1, "b"=>[1, 2], "c"=>{"1"=>2}, "d"=>{"1"=>[2, 3]}, "n"=>{"n"=>"not_null"}
+(1 row)
+
+SELECT concat_path('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{n}', 'not_null');
+                               concat_path                               
+-------------------------------------------------------------------------
+ "a"=>1, "b"=>[1, 2], "c"=>{"1"=>2}, "d"=>{"1"=>[2, 3]}, "n"=>"not_null"
+(1 row)
+
+SELECT concat_path('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{n}', '{not_null}');
+                                concat_path                                
+---------------------------------------------------------------------------
+ "a"=>1, "b"=>[1, 2], "c"=>{"1"=>2}, "d"=>{"1"=>[2, 3]}, "n"=>["not_null"]
+(1 row)
+
+SELECT concat_path('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{}', 'b=>{3,4}');
+                            concat_path                            
+-------------------------------------------------------------------
+ "a"=>1, "b"=>[3, 4], "c"=>{"1"=>2}, "d"=>{"1"=>[2, 3]}, "n"=>NULL
+(1 row)
+
+SELECT concat_path('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{b}', '{3,4}');
+                               concat_path                               
+-------------------------------------------------------------------------
+ "a"=>1, "b"=>[1, 2, 3, 4], "c"=>{"1"=>2}, "d"=>{"1"=>[2, 3]}, "n"=>NULL
+(1 row)
+
+SELECT concat_path('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{d,1}', '{4,5}');
+                               concat_path                               
+-------------------------------------------------------------------------
+ "a"=>1, "b"=>[1, 2], "c"=>{"1"=>2}, "d"=>{"1"=>[2, 3, 4, 5]}, "n"=>NULL
+(1 row)
+
+SELECT concat_path('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{d,1}', '4=>5');
+                                concat_path                                
+---------------------------------------------------------------------------
+ "a"=>1, "b"=>[1, 2], "c"=>{"1"=>2}, "d"=>{"1"=>[2, 3, "4", 5]}, "n"=>NULL
+(1 row)
+
+SELECT concat_path('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{d}', '2=>{4,5}');
+                                  concat_path                                   
+--------------------------------------------------------------------------------
+ "a"=>1, "b"=>[1, 2], "c"=>{"1"=>2}, "d"=>{"1"=>[2, 3], "2"=>[4, 5]}, "n"=>NULL
+(1 row)
+
+SELECT concat_path('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{NULL,1}', '4=>5');
+                            concat_path                            
+-------------------------------------------------------------------
+ "a"=>1, "b"=>[1, 2], "c"=>{"1"=>2}, "d"=>{"1"=>[2, 3]}, "n"=>NULL
+(1 row)
+
+SELECT concat_path('x'::hstore, '{}'::text[], 'a=>"1"':: hstore);
+   concat_path   
+-----------------
+ ["x", "a", "1"]
+(1 row)
+
+--cast 
+SELECT ('{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}'::text)::hstore AS err;
+ERROR:  bad hstore representation
+DETAIL:  syntax error, unexpected STRING_P, expecting '}' or ',' at end of input
+SELECT ('{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}'::json)::hstore AS ok;
+                         ok                         
+----------------------------------------------------
+ "f2"=>{"f3"=>1}, "f4"=>{"f5"=>99, "f6"=>"stringy"}
+(1 row)
+
+--hvals
+SELECT q->'tags' FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore) AS q;
+ ?column? 
+----------
+ 1
+ 3
+(2 rows)
+
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{}') AS q;
+                      q                       
+----------------------------------------------
+ [{"sh"=>2, "tags"=>1}, {"sh"=>4, "tags"=>3}]
+(1 row)
+
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-3}') AS q;
+ q 
+---
+(0 rows)
+
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-2}') AS q;
+         q          
+--------------------
+ "sh"=>2, "tags"=>1
+(1 row)
+
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-1}') AS q;
+         q          
+--------------------
+ "sh"=>4, "tags"=>3
+(1 row)
+
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{0}') AS q;
+         q          
+--------------------
+ "sh"=>2, "tags"=>1
+(1 row)
+
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{1}') AS q;
+         q          
+--------------------
+ "sh"=>4, "tags"=>3
+(1 row)
+
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{2}') AS q;
+ q 
+---
+(0 rows)
+
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{NULL}') AS q;
+         q          
+--------------------
+ "sh"=>2, "tags"=>1
+ "sh"=>4, "tags"=>3
+(2 rows)
+
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-3,tags}') AS q;
+ q 
+---
+(0 rows)
+
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-2,tags}') AS q;
+ q 
+---
+ 1
+(1 row)
+
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-1,tags}') AS q;
+ q 
+---
+ 3
+(1 row)
+
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{0,tags}') AS q;
+ q 
+---
+ 1
+(1 row)
+
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{1,tags}') AS q;
+ q 
+---
+ 3
+(1 row)
+
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{2,tags}') AS q;
+ q 
+---
+(0 rows)
+
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{NULL,tags}') AS q;
+ q 
+---
+ 1
+ 3
+(2 rows)
+
+SELECT q FROM hvals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{}') AS q;
+                                q                                
+-----------------------------------------------------------------
+ "1"=>"first", "a"=>{"b"=>"c", "c"=>"b"}, "b"=>[1, 2], "c"=>"cc"
+(1 row)
+
+SELECT q FROM hvals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{1}') AS q;
+    q    
+---------
+ "first"
+(1 row)
+
+SELECT q FROM hvals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{a}') AS q;
+         q          
+--------------------
+ "b"=>"c", "c"=>"b"
+(1 row)
+
+SELECT q FROM hvals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{b}') AS q;
+   q    
+--------
+ [1, 2]
+(1 row)
+
+SELECT q FROM hvals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{c}') AS q;
+  q   
+------
+ "cc"
+(1 row)
+
+SELECT q FROM hvals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{NULL}') AS q;
+         q          
+--------------------
+ "first"
+ "b"=>"c", "c"=>"b"
+ [1, 2]
+ "cc"
+(4 rows)
+
+SELECT q FROM hvals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{a,c}') AS q;
+  q  
+-----
+ "b"
+(1 row)
+
+SELECT q FROM hvals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{NULL,c}') AS q;
+  q  
+-----
+ "b"
+(1 row)
+
+SELECT q FROM hvals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{b,NULL}') AS q;
+ q 
+---
+ 1
+ 2
+(2 rows)
+
+SELECT q FROM hvals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{NULL,1}') AS q;
+ q 
+---
+ 2
+(1 row)
+
+SELECT q FROM hvals('a=>{b=>c, c=>b, 1=>first}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{NULL,1}') AS q;
+    q    
+---------
+ "first"
+ 2
+(2 rows)
+
+--svals path
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{}') AS q;
+                      q                       
+----------------------------------------------
+ [{"sh"=>2, "tags"=>1}, {"sh"=>4, "tags"=>3}]
+(1 row)
+
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-3}') AS q;
+ q 
+---
+(0 rows)
+
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-2}') AS q;
+         q          
+--------------------
+ "sh"=>2, "tags"=>1
+(1 row)
+
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-1}') AS q;
+         q          
+--------------------
+ "sh"=>4, "tags"=>3
+(1 row)
+
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{0}') AS q;
+         q          
+--------------------
+ "sh"=>2, "tags"=>1
+(1 row)
+
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{1}') AS q;
+         q          
+--------------------
+ "sh"=>4, "tags"=>3
+(1 row)
+
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{2}') AS q;
+ q 
+---
+(0 rows)
+
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{NULL}') AS q;
+         q          
+--------------------
+ "sh"=>2, "tags"=>1
+ "sh"=>4, "tags"=>3
+(2 rows)
+
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-3,tags}') AS q;
+ q 
+---
+(0 rows)
+
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-2,tags}') AS q;
+ q 
+---
+ 1
+(1 row)
+
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-1,tags}') AS q;
+ q 
+---
+ 3
+(1 row)
+
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{0,tags}') AS q;
+ q 
+---
+ 1
+(1 row)
+
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{1,tags}') AS q;
+ q 
+---
+ 3
+(1 row)
+
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{2,tags}') AS q;
+ q 
+---
+(0 rows)
+
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{NULL,tags}') AS q;
+ q 
+---
+ 1
+ 3
+(2 rows)
+
+SELECT q FROM svals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{}') AS q;
+                                q                                
+-----------------------------------------------------------------
+ "1"=>"first", "a"=>{"b"=>"c", "c"=>"b"}, "b"=>[1, 2], "c"=>"cc"
+(1 row)
+
+SELECT q FROM svals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{1}') AS q;
+   q   
+-------
+ first
+(1 row)
+
+SELECT q FROM svals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{a}') AS q;
+         q          
+--------------------
+ "b"=>"c", "c"=>"b"
+(1 row)
+
+SELECT q FROM svals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{b}') AS q;
+   q    
+--------
+ [1, 2]
+(1 row)
+
+SELECT q FROM svals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{c}') AS q;
+ q  
+----
+ cc
+(1 row)
+
+SELECT q FROM svals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{NULL}') AS q;
+         q          
+--------------------
+ first
+ "b"=>"c", "c"=>"b"
+ [1, 2]
+ cc
+(4 rows)
+
+SELECT q FROM svals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{a,c}') AS q;
+ q 
+---
+ b
+(1 row)
+
+SELECT q FROM svals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{NULL,c}') AS q;
+ q 
+---
+ b
+(1 row)
+
+SELECT q FROM svals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{b,NULL}') AS q;
+ q 
+---
+ 1
+ 2
+(2 rows)
+
+SELECT q FROM svals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{NULL,1}') AS q;
+ q 
+---
+ 2
+(1 row)
+
+SELECT q FROM svals('a=>{b=>c, c=>b, 1=>first}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{NULL,1}') AS q;
+   q   
+-------
+ first
+ 2
+(2 rows)
+
+--each
+SELECT * FROM each('a=>b, c=>cc'::hstore) AS q;
+ key | value 
+-----+-------
+ a   | b
+ c   | cc
+(2 rows)
+
+SELECT * FROM each('[a, b, c, cc]'::hstore) AS q;
+ key | value 
+-----+-------
+     | a
+     | b
+     | c
+     | cc
+(4 rows)
+
+SELECT * FROM each('a=>{b=>c, c=>b, 1=>first}, b=>{1,2}, c=>cc, 1=>first, n=>null'::hstore) AS q;
+ key |              value               
+-----+----------------------------------
+ 1   | first
+ a   | "1"=>"first", "b"=>"c", "c"=>"b"
+ b   | [1, 2]
+ c   | cc
+ n   | 
+(5 rows)
+
+SELECT * FROM each_hstore('a=>b, c=>cc'::hstore) AS q;
+ key | value 
+-----+-------
+ a   | "b"
+ c   | "cc"
+(2 rows)
+
+SELECT * FROM each_hstore('[a, b, c, cc]'::hstore) AS q;
+ key | value 
+-----+-------
+     | "a"
+     | "b"
+     | "c"
+     | "cc"
+(4 rows)
+
+SELECT * FROM each_hstore('a=>{b=>c, c=>b, 1=>first}, b=>{1,2}, c=>cc, 1=>first, n=>null'::hstore) AS q;
+ key |              value               
+-----+----------------------------------
+ 1   | "first"
+ a   | "1"=>"first", "b"=>"c", "c"=>"b"
+ b   | [1, 2]
+ c   | "cc"
+ n   | 
+(5 rows)
+
+--decoration
+SELECT 'a=>1, b=>{c=>3}, d=>[4,[5]]'::hstore AS h, '[a, {b=>c}, [c, d, e]]'::hstore AS a;
+                  h                   |                 a                  
+--------------------------------------+------------------------------------
+ "a"=>1, "b"=>{"c"=>3}, "d"=>[4, [5]] | ["a", {"b"=>"c"}, ["c", "d", "e"]]
+(1 row)
+
+SET hstore.pretty_print = true;
+SELECT 'a=>1, b=>{c=>3}, d=>[4,[5]], e=>[1,2,3,4], f=>g, g=>j'::hstore AS h, 
+          '[a, {b=>c, c=>d}, [c, d, e, [1,2], h, {f=>g, g=>f}]]'::hstore AS a;
+     h      |           a            
+------------+------------------------
+ "a"=>1,   +| [                     +
+ "b"=>     +|     "a",              +
+ {         +|     {                 +
+     "c"=>3+|         "b"=>"c",     +
+ },        +|         "c"=>"d"      +
+ "d"=>     +|     },                +
+ [         +|     [                 +
+     4,    +|         "c",          +
+     [     +|         "d",          +
+         5 +|         "e",          +
+     ]     +|         [             +
+ ],        +|             1,        +
+ "e"=>     +|             2         +
+ [         +|         ],            +
+     1,    +|         "h",          +
+     2,    +|         {             +
+     3,    +|             "f"=>"g", +
+     4     +|             "g"=>f    +
+ ],        +|         }             +
+ "f"=>"g", +|     ]                 +
+ "g"=>"j"   | ]
+(1 row)
+
+RESET hstore.pretty_print;
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore);
+                             hstore_print                              
+-----------------------------------------------------------------------
+ "a"=>t, "f"=>t, "t"=>"f", "123"=>"string", "arr"=>[1, 2, 3, "3", "x"]
+(1 row)
+
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, loose := true );
+                           hstore_print                            
+-------------------------------------------------------------------
+ "a"=>t, "f"=>t, "t"=>f, "123"=>"string", "arr"=>[1, 2, 3, 3, "x"]
+(1 row)
+
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, root_hash_decorated := true );
+                              hstore_print                               
+-------------------------------------------------------------------------
+ {"a"=>t, "f"=>t, "t"=>"f", "123"=>"string", "arr"=>[1, 2, 3, "3", "x"]}
+(1 row)
+
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, array_curly_braces := true );
+                             hstore_print                              
+-----------------------------------------------------------------------
+ "a"=>t, "f"=>t, "t"=>"f", "123"=>"string", "arr"=>{1, 2, 3, "3", "x"}
+(1 row)
+
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, json := true );
+                                hstore_print                                 
+-----------------------------------------------------------------------------
+ "a": true, "f": true, "t": "f", "123": "string", "arr": [1, 2, 3, "3", "x"]
+(1 row)
+
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, json := true, loose := true );
+                                hstore_print                                 
+-----------------------------------------------------------------------------
+ "a": true, "f": true, "t": false, "123": "string", "arr": [1, 2, 3, 3, "x"]
+(1 row)
+
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, json := true, root_hash_decorated := true );
+                                 hstore_print                                  
+-------------------------------------------------------------------------------
+ {"a": true, "f": true, "t": "f", "123": "string", "arr": [1, 2, 3, "3", "x"]}
+(1 row)
+
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, json := true, array_curly_braces := true );
+                                hstore_print                                 
+-----------------------------------------------------------------------------
+ "a": true, "f": true, "t": "f", "123": "string", "arr": {1, 2, 3, "3", "x"}
+(1 row)
+
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, loose := true, root_hash_decorated := true );
+                            hstore_print                             
+---------------------------------------------------------------------
+ {"a"=>t, "f"=>t, "t"=>f, "123"=>"string", "arr"=>[1, 2, 3, 3, "x"]}
+(1 row)
+
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, loose := true, array_curly_braces := true );
+                           hstore_print                            
+-------------------------------------------------------------------
+ "a"=>t, "f"=>t, "t"=>f, "123"=>"string", "arr"=>{1, 2, 3, 3, "x"}
+(1 row)
+
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, root_hash_decorated := true, array_curly_braces := true );
+                              hstore_print                               
+-------------------------------------------------------------------------
+ {"a"=>t, "f"=>t, "t"=>"f", "123"=>"string", "arr"=>{1, 2, 3, "3", "x"}}
+(1 row)
+
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, root_hash_decorated := true, array_curly_braces := true, loose := true);
+                            hstore_print                             
+---------------------------------------------------------------------
+ {"a"=>t, "f"=>t, "t"=>f, "123"=>"string", "arr"=>{1, 2, 3, 3, "x"}}
+(1 row)
+
diff --git a/expected/types.out b/expected/types.out
new file mode 100644 (file)
index 0000000..4206c58
--- /dev/null
@@ -0,0 +1,762 @@
+SELECT '"foo"=>true'::hstore;
+  hstore  
+----------
+ "foo"=>t
+(1 row)
+
+SELECT 'foo=>true'::hstore;
+  hstore  
+----------
+ "foo"=>t
+(1 row)
+
+SELECT '"true"=>true'::hstore;
+  hstore   
+-----------
+ "true"=>t
+(1 row)
+
+SELECT 'true=>true'::hstore;
+  hstore   
+-----------
+ "true"=>t
+(1 row)
+
+SELECT '"t"=>true'::hstore;
+ hstore 
+--------
+ "t"=>t
+(1 row)
+
+SELECT 't=>true'::hstore;
+ hstore 
+--------
+ "t"=>t
+(1 row)
+
+SELECT '"false"=>true'::hstore;
+   hstore   
+------------
+ "false"=>t
+(1 row)
+
+SELECT 'false=>true'::hstore;
+   hstore   
+------------
+ "false"=>t
+(1 row)
+
+SELECT '"f"=>true'::hstore;
+ hstore 
+--------
+ "f"=>t
+(1 row)
+
+SELECT 'f=>true'::hstore;
+ hstore 
+--------
+ "f"=>t
+(1 row)
+
+SELECT '"foo"=>false'::hstore;
+  hstore  
+----------
+ "foo"=>f
+(1 row)
+
+SELECT 'foo=>false'::hstore;
+  hstore  
+----------
+ "foo"=>f
+(1 row)
+
+SELECT '"false"=>false'::hstore;
+   hstore   
+------------
+ "false"=>f
+(1 row)
+
+SELECT 'false=>false'::hstore;
+   hstore   
+------------
+ "false"=>f
+(1 row)
+
+SELECT '"t"=>false'::hstore;
+ hstore 
+--------
+ "t"=>f
+(1 row)
+
+SELECT 't=>false'::hstore;
+ hstore 
+--------
+ "t"=>f
+(1 row)
+
+SELECT '"false"=>false'::hstore;
+   hstore   
+------------
+ "false"=>f
+(1 row)
+
+SELECT 'false=>false'::hstore;
+   hstore   
+------------
+ "false"=>f
+(1 row)
+
+SELECT '"f"=>false'::hstore;
+ hstore 
+--------
+ "f"=>f
+(1 row)
+
+SELECT 'f=>false'::hstore;
+ hstore 
+--------
+ "f"=>f
+(1 row)
+
+SELECT '"1"=>x'::hstore;
+  hstore  
+----------
+ "1"=>"x"
+(1 row)
+
+SELECT '1=>x'::hstore;
+  hstore  
+----------
+ "1"=>"x"
+(1 row)
+
+SELECT 'foo=>1'::hstore;
+  hstore  
+----------
+ "foo"=>1
+(1 row)
+
+SELECT 'foo=>1.'::hstore;
+  hstore  
+----------
+ "foo"=>1
+(1 row)
+
+SELECT 'foo=>1.0'::hstore;
+   hstore   
+------------
+ "foo"=>1.0
+(1 row)
+
+SELECT 'foo=>1.01'::hstore;
+   hstore    
+-------------
+ "foo"=>1.01
+(1 row)
+
+SELECT 'foo=>1.01e'::hstore;
+     hstore     
+----------------
+ "foo"=>"1.01e"
+(1 row)
+
+SELECT 'foo=>1.01e1'::hstore;
+   hstore    
+-------------
+ "foo"=>10.1
+(1 row)
+
+SELECT 'foo=>1.01e+1'::hstore;
+   hstore    
+-------------
+ "foo"=>10.1
+(1 row)
+
+SELECT 'foo=>1.01e-1'::hstore;
+    hstore    
+--------------
+ "foo"=>0.101
+(1 row)
+
+SELECT 'foo=>.1'::hstore;
+   hstore   
+------------
+ "foo"=>0.1
+(1 row)
+
+SELECT 'foo=>.1e'::hstore;
+    hstore    
+--------------
+ "foo"=>".1e"
+(1 row)
+
+SELECT 'foo=>.1e1'::hstore;
+  hstore  
+----------
+ "foo"=>1
+(1 row)
+
+SELECT 'foo=>.1e+1'::hstore;
+  hstore  
+----------
+ "foo"=>1
+(1 row)
+
+SELECT 'foo=>.1e-1'::hstore;
+   hstore    
+-------------
+ "foo"=>0.01
+(1 row)
+
+SELECT 'foo=>0.1e-1'::hstore;
+   hstore    
+-------------
+ "foo"=>0.01
+(1 row)
+
+SELECT 'foo=>00.1e-1'::hstore;
+   hstore    
+-------------
+ "foo"=>0.01
+(1 row)
+
+SELECT 'foo=>+1'::hstore;
+  hstore  
+----------
+ "foo"=>1
+(1 row)
+
+SELECT 'foo=>+1.'::hstore;
+  hstore  
+----------
+ "foo"=>1
+(1 row)
+
+SELECT 'foo=>+1.0'::hstore;
+   hstore   
+------------
+ "foo"=>1.0
+(1 row)
+
+SELECT 'foo=>+1.01'::hstore;
+   hstore    
+-------------
+ "foo"=>1.01
+(1 row)
+
+SELECT 'foo=>+1.01e'::hstore;
+     hstore      
+-----------------
+ "foo"=>"+1.01e"
+(1 row)
+
+SELECT 'foo=>+1.01e1'::hstore;
+   hstore    
+-------------
+ "foo"=>10.1
+(1 row)
+
+SELECT 'foo=>+1.01e+1'::hstore;
+   hstore    
+-------------
+ "foo"=>10.1
+(1 row)
+
+SELECT 'foo=>+1.01e-1'::hstore;
+    hstore    
+--------------
+ "foo"=>0.101
+(1 row)
+
+SELECT 'foo=>+.1'::hstore;
+   hstore   
+------------
+ "foo"=>0.1
+(1 row)
+
+SELECT 'foo=>+.1e'::hstore;
+    hstore     
+---------------
+ "foo"=>"+.1e"
+(1 row)
+
+SELECT 'foo=>+.1e1'::hstore;
+  hstore  
+----------
+ "foo"=>1
+(1 row)
+
+SELECT 'foo=>+.1e+1'::hstore;
+  hstore  
+----------
+ "foo"=>1
+(1 row)
+
+SELECT 'foo=>+.1e-1'::hstore;
+   hstore    
+-------------
+ "foo"=>0.01
+(1 row)
+
+SELECT 'foo=>-1'::hstore;
+  hstore   
+-----------
+ "foo"=>-1
+(1 row)
+
+SELECT 'foo=>-1.'::hstore;
+  hstore   
+-----------
+ "foo"=>-1
+(1 row)
+
+SELECT 'foo=>-1.0'::hstore;
+   hstore    
+-------------
+ "foo"=>-1.0
+(1 row)
+
+SELECT 'foo=>-1.01'::hstore;
+    hstore    
+--------------
+ "foo"=>-1.01
+(1 row)
+
+SELECT 'foo=>-1.01e'::hstore;
+     hstore      
+-----------------
+ "foo"=>"-1.01e"
+(1 row)
+
+SELECT 'foo=>-1.01e1'::hstore;
+    hstore    
+--------------
+ "foo"=>-10.1
+(1 row)
+
+SELECT 'foo=>-1.01e+1'::hstore;
+    hstore    
+--------------
+ "foo"=>-10.1
+(1 row)
+
+SELECT 'foo=>-1.01e-1'::hstore;
+    hstore     
+---------------
+ "foo"=>-0.101
+(1 row)
+
+SELECT 'foo=>-.1'::hstore;
+   hstore    
+-------------
+ "foo"=>-0.1
+(1 row)
+
+SELECT 'foo=>-.1e'::hstore;
+    hstore     
+---------------
+ "foo"=>"-.1e"
+(1 row)
+
+SELECT 'foo=>-.1e1'::hstore;
+  hstore   
+-----------
+ "foo"=>-1
+(1 row)
+
+SELECT 'foo=>-.1e+1'::hstore;
+  hstore   
+-----------
+ "foo"=>-1
+(1 row)
+
+SELECT 'foo=>-.1e-1'::hstore;
+    hstore    
+--------------
+ "foo"=>-0.01
+(1 row)
+
+SELECT 'foo=>1e2000'::hstore;
+     hstore      
+-----------------
+ "foo"=>"1e2000"
+(1 row)
+
+SELECT 'foo=>1e12, bar=>x'::hstore ^> 'foo';
+   ?column?    
+---------------
+ 1000000000000
+(1 row)
+
+SELECT 'foo=>1e12, bar=>x'::hstore ^> 'bar';
+ ?column? 
+----------
+         
+(1 row)
+
+SELECT 'foo=>1e12, bar=>x'::hstore ^> 0;
+ ?column? 
+----------
+         
+(1 row)
+
+SELECT 'foo=>1e12, bar=>x'::hstore ^> 1;
+   ?column?    
+---------------
+ 1000000000000
+(1 row)
+
+SELECT '[foo, 1e12, bar, x]'::hstore ^> 'foo';
+ ?column? 
+----------
+         
+(1 row)
+
+SELECT '[foo, 1e12, bar, x]'::hstore ^> 'bar';
+ ?column? 
+----------
+         
+(1 row)
+
+SELECT '[foo, 1e12, bar, x]'::hstore ^> 0;
+ ?column? 
+----------
+         
+(1 row)
+
+SELECT '[foo, 1e12, bar, x]'::hstore ^> 1;
+   ?column?    
+---------------
+ 1000000000000
+(1 row)
+
+SELECT 'foo=>{x, 1e-12}'::hstore #^> '{foo, 0}';
+ ?column? 
+----------
+         
+(1 row)
+
+SELECT 'foo=>{x, 1e-12}'::hstore #^> '{foo, 1}';
+    ?column?    
+----------------
+ 0.000000000001
+(1 row)
+
+SELECT 'foo=>t, bar=>x'::hstore ?> 'foo';
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'foo=>t, bar=>x'::hstore ?> 'bar';
+ ?column? 
+----------
+(1 row)
+
+SELECT 'foo=>t, bar=>x'::hstore ?> 0;
+ ?column? 
+----------
+(1 row)
+
+SELECT 'foo=>t, bar=>x'::hstore ?> 1;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT '[foo, t, bar, x]'::hstore ?> 'foo';
+ ?column? 
+----------
+(1 row)
+
+SELECT '[foo, t, bar, x]'::hstore ?> 'bar';
+ ?column? 
+----------
+(1 row)
+
+SELECT '[foo, t, bar, x]'::hstore ?> 0;
+ ?column? 
+----------
+(1 row)
+
+SELECT '[foo, t, bar, x]'::hstore ?> 1;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'foo=>{x, t}'::hstore #?> '{foo, 0}';
+ ?column? 
+----------
+(1 row)
+
+SELECT 'foo=>{x, t}'::hstore #?> '{foo, 1}';
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 'foo=>f, bar=>x'::hstore ?> 'foo';
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT 'foo=>f, bar=>x'::hstore ?> 'bar';
+ ?column? 
+----------
+(1 row)
+
+SELECT 'foo=>f, bar=>x'::hstore ?> 0;
+ ?column? 
+----------
+(1 row)
+
+SELECT 'foo=>f, bar=>x'::hstore ?> 1;
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT '[foo, f, bar, x]'::hstore ?> 'foo';
+ ?column? 
+----------
+(1 row)
+
+SELECT '[foo, f, bar, x]'::hstore ?> 'bar';
+ ?column? 
+----------
+(1 row)
+
+SELECT '[foo, f, bar, x]'::hstore ?> 0;
+ ?column? 
+----------
+(1 row)
+
+SELECT '[foo, f, bar, x]'::hstore ?> 1;
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT 'foo=>{x, f}'::hstore #?> '{foo, 0}';
+ ?column? 
+----------
+(1 row)
+
+SELECT 'foo=>{x, f}'::hstore #?> '{foo, 1}';
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT hstore_typeof('a=>b') AS hash;
+ hash 
+------
+ hash
+(1 row)
+
+SELECT hstore_typeof('{a=>b}') AS hash;
+ hash 
+------
+ hash
+(1 row)
+
+SELECT hstore_typeof('{a, b}') AS array;
+ array 
+-------
+ array
+(1 row)
+
+SELECT hstore_typeof('{{a=>b}}') AS array;
+ array 
+-------
+ array
+(1 row)
+
+SELECT hstore_typeof('[a, b]') AS array;
+ array 
+-------
+ array
+(1 row)
+
+SELECT hstore_typeof('') AS "NULL";
+ NULL 
+------
+(1 row)
+
+SELECT hstore_typeof('NULL') AS "null";
+ null 
+------
+ null
+(1 row)
+
+SELECT hstore_typeof('1.0') AS numeric;
+ numeric 
+---------
+ numeric
+(1 row)
+
+SELECT hstore_typeof('t') AS bool;
+ bool 
+------
+ bool
+(1 row)
+
+SELECT hstore_typeof('f') AS bool;
+ bool 
+------
+ bool
+(1 row)
+
+SELECT hstore('xxx', 't'::bool);
+  hstore  
+----------
+ "xxx"=>t
+(1 row)
+
+SELECT hstore('xxx', 'f'::bool);
+  hstore  
+----------
+ "xxx"=>f
+(1 row)
+
+SELECT hstore('xxx', 3.14);
+   hstore    
+-------------
+ "xxx"=>3.14
+(1 row)
+
+SELECT hstore('xxx', 3.14::numeric);
+   hstore    
+-------------
+ "xxx"=>3.14
+(1 row)
+
+SELECT hstore('xxx', '3.14'::numeric);
+   hstore    
+-------------
+ "xxx"=>3.14
+(1 row)
+
+SELECT hstore(NULL);
+ hstore 
+--------
+(1 row)
+
+SELECT hstore('NULL');
+ hstore 
+--------
+ NULL
+(1 row)
+
+SELECT hstore('t'::bool) AS "true", hstore('f'::bool) AS "false";
+ true | false 
+------+-------
+ t    | f
+(1 row)
+
+SELECT hstore(3.14), hstore(3.14::numeric), hstore('3.14'::numeric);
+ hstore | hstore | hstore 
+--------+--------+--------
+ 3.14   | 3.14   | 3.14
+(1 row)
+
+SELECT hstore('xxx', 'foo=>t, bar=>3.14, zzz=>xxx'::hstore);
+                    hstore                    
+----------------------------------------------
+ "xxx"=>{"bar"=>3.14, "foo"=>t, "zzz"=>"xxx"}
+(1 row)
+
+SELECT array_to_hstore('{{1,1,4},{23,3,5}}'::int2[]);
+     array_to_hstore     
+-------------------------
+ [[1, 1, 4], [23, 3, 5]]
+(1 row)
+
+SELECT array_to_hstore('{{1,1,4},{23,3,5}}'::int4[]);
+     array_to_hstore     
+-------------------------
+ [[1, 1, 4], [23, 3, 5]]
+(1 row)
+
+SELECT array_to_hstore('{{1,1,4},{23,3,5}}'::int8[]);
+     array_to_hstore     
+-------------------------
+ [[1, 1, 4], [23, 3, 5]]
+(1 row)
+
+SELECT array_to_hstore('{{1,1,4},{23,3,5}}'::float4[]);
+     array_to_hstore     
+-------------------------
+ [[1, 1, 4], [23, 3, 5]]
+(1 row)
+
+SELECT array_to_hstore('{{1,1,4},{23,3,5}}'::float8[]);
+     array_to_hstore     
+-------------------------
+ [[1, 1, 4], [23, 3, 5]]
+(1 row)
+
+SELECT array_to_hstore('{{1,1,f},{f,t,NULL}}'::bool[]);
+      array_to_hstore      
+---------------------------
+ [[t, t, f], [f, t, NULL]]
+(1 row)
+
+SELECT array_to_hstore('{{1,1,4},{23,3,5}}'::text[]);
+           array_to_hstore           
+-------------------------------------
+ [["1", "1", "4"], ["23", "3", "5"]]
+(1 row)
+
+SELECT array_to_hstore('{{1,1,4},{23,3,5}}'::varchar[]);
+           array_to_hstore           
+-------------------------------------
+ [["1", "1", "4"], ["23", "3", "5"]]
+(1 row)
+
+SELECT array_to_hstore('{{{1,11},{1,1},{4,41}},{{23,231},{3,31},{5,51}}}'::int4[]);
+                       array_to_hstore                       
+-------------------------------------------------------------
+ [[[1, 11], [1, 1], [4, 41], [23, 231]], [[3, 31], [5, 51]]]
+(1 row)
+
+SELECT hstore('array', array_to_hstore('{{{1,11},{1,1},{4,41}},{{23,231},{3,31},{5,51}}}'::int4[]));
+                                hstore                                
+----------------------------------------------------------------------
+ "array"=>[[[1, 11], [1, 1], [4, 41], [23, 231]], [[3, 31], [5, 51]]]
+(1 row)
+
+SELECT 'a=>"00012333", b=>"12233", c=>00012333, d=>12233'::hstore;
+                        hstore                         
+-------------------------------------------------------
+ "a"=>"00012333", "b"=>"12233", "c"=>12333, "d"=>12233
+(1 row)
+
+SELECT hstore_to_json('a=>"00012333", b=>"12233", c=>00012333, d=>12233'::hstore);
+                     hstore_to_json                      
+---------------------------------------------------------
+ {"a": "00012333", "b": "12233", "c": 12333, "d": 12233}
+(1 row)
+
+SELECT hstore_to_json_loose('a=>"00012333", b=>"12233", c=>00012333, d=>12233'::hstore);
+                 hstore_to_json_loose                  
+-------------------------------------------------------
+ {"a": "00012333", "b": 12233, "c": 12333, "d": 12233}
+(1 row)
+
diff --git a/hstore--1.0--1.1.sql b/hstore--1.0--1.1.sql
new file mode 100644 (file)
index 0000000..4e32a57
--- /dev/null
@@ -0,0 +1,7 @@
+/* contrib/hstore/hstore--1.0--1.1.sql */
+
+-- complain if script is sourced in psql, rather than via ALTER EXTENSION
+\echo Use "ALTER EXTENSION hstore UPDATE TO '1.1'" to load this file. \quit
+
+ALTER EXTENSION hstore DROP OPERATOR => (text, text);
+DROP OPERATOR => (text, text);
diff --git a/hstore--1.1--1.2.sql b/hstore--1.1--1.2.sql
new file mode 100644 (file)
index 0000000..a868ffe
--- /dev/null
@@ -0,0 +1,48 @@
+/* contrib/hstore/hstore--1.1--1.2.sql */
+
+-- complain if script is sourced in psql, rather than via ALTER EXTENSION
+\echo Use "ALTER EXTENSION hstore UPDATE TO '1.2'" to load this file. \quit
+
+
+-- A version of 1.1 was shipped with these objects mistakenly in 9.3.0.
+-- Therefore we only add them if we detect that they aren't already there and
+-- dependent on the extension.
+
+DO LANGUAGE plpgsql
+
+$$
+
+BEGIN
+
+   PERFORM 1
+   FROM pg_proc p
+       JOIN  pg_depend d
+          ON p.proname = 'hstore_to_json_loose'
+            AND d.classid = 'pg_proc'::regclass
+            AND d.objid = p.oid
+            AND d.refclassid = 'pg_extension'::regclass
+       JOIN pg_extension x
+          ON d.refobjid = x.oid
+            AND  x.extname = 'hstore';
+
+   IF NOT FOUND
+   THEN
+
+        CREATE FUNCTION hstore_to_json(hstore)
+        RETURNS json
+        AS 'MODULE_PATHNAME', 'hstore_to_json'
+        LANGUAGE C IMMUTABLE STRICT;
+
+        CREATE CAST (hstore AS json)
+          WITH FUNCTION hstore_to_json(hstore);
+
+        CREATE FUNCTION hstore_to_json_loose(hstore)
+        RETURNS json
+        AS 'MODULE_PATHNAME', 'hstore_to_json_loose'
+        LANGUAGE C IMMUTABLE STRICT;
+
+   END IF;
+
+END;
+
+$$;
diff --git a/hstore--1.2--1.3.sql b/hstore--1.2--1.3.sql
new file mode 100644 (file)
index 0000000..13e310b
--- /dev/null
@@ -0,0 +1,322 @@
+/* contrib/hstore/hstore--1.2--1.3.sql */
+
+-- complain if script is sourced in psql, rather than via CREATE EXTENSION
+\echo Use "ALTER EXTENSION hstore UPDATE TO '1.2'" to load this file. \quit
+
+CREATE FUNCTION fetchval_numeric(hstore,text)
+RETURNS numeric
+AS 'MODULE_PATHNAME','hstore_fetchval_numeric'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR ^> (
+       LEFTARG = hstore,
+       RIGHTARG = text,
+       PROCEDURE = fetchval_numeric
+);
+
+CREATE FUNCTION fetchval_boolean(hstore,text)
+RETURNS boolean
+AS 'MODULE_PATHNAME','hstore_fetchval_boolean'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR ?> (
+       LEFTARG = hstore,
+       RIGHTARG = text,
+       PROCEDURE = fetchval_boolean
+);
+
+CREATE FUNCTION fetchval(hstore,int)
+RETURNS text
+AS 'MODULE_PATHNAME','hstore_fetchval_n'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR -> (
+       LEFTARG = hstore,
+       RIGHTARG = int,
+       PROCEDURE = fetchval
+);
+
+CREATE FUNCTION fetchval_numeric(hstore,int)
+RETURNS numeric
+AS 'MODULE_PATHNAME','hstore_fetchval_n_numeric'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR ^> (
+       LEFTARG = hstore,
+       RIGHTARG = int,
+       PROCEDURE = fetchval_numeric
+);
+
+CREATE FUNCTION fetchval_boolean(hstore,int)
+RETURNS boolean
+AS 'MODULE_PATHNAME','hstore_fetchval_n_boolean'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR ?> (
+       LEFTARG = hstore,
+       RIGHTARG = int,
+       PROCEDURE = fetchval_boolean
+);
+
+CREATE FUNCTION fetchval(hstore,text[])
+RETURNS text
+AS 'MODULE_PATHNAME','hstore_fetchval_path'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR #> (
+       LEFTARG = hstore,
+       RIGHTARG = text[],
+       PROCEDURE = fetchval
+);
+
+CREATE FUNCTION fetchval_numeric(hstore,text[])
+RETURNS numeric
+AS 'MODULE_PATHNAME','hstore_fetchval_path_numeric'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR #^> (
+       LEFTARG = hstore,
+       RIGHTARG = text[],
+       PROCEDURE = fetchval_numeric
+);
+
+CREATE FUNCTION fetchval_boolean(hstore,text[])
+RETURNS boolean
+AS 'MODULE_PATHNAME','hstore_fetchval_path_boolean'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR #?> (
+       LEFTARG = hstore,
+       RIGHTARG = text[],
+       PROCEDURE = fetchval_boolean
+);
+
+CREATE FUNCTION fetchval_hstore(hstore,text)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_fetchval_hstore'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR %> (
+       LEFTARG = hstore,
+       RIGHTARG = text,
+       PROCEDURE = fetchval_hstore
+);
+
+CREATE FUNCTION fetchval_hstore(hstore,int)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_fetchval_n_hstore'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR %> (
+       LEFTARG = hstore,
+       RIGHTARG = int,
+       PROCEDURE = fetchval_hstore
+);
+
+CREATE FUNCTION fetchval_hstore(hstore,text[])
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_fetchval_path_hstore'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR #%> (
+       LEFTARG = hstore,
+       RIGHTARG = text[],
+       PROCEDURE = fetchval_hstore
+);
+
+CREATE FUNCTION json_to_hstore(json)
+RETURNS hstore
+AS 'MODULE_PATHNAME','json_to_hstore'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE CAST (json AS hstore)
+WITH FUNCTION json_to_hstore(json);
+
+CREATE FUNCTION isexists(hstore,int)
+RETURNS bool
+AS 'MODULE_PATHNAME','hstore_exists_idx'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION exist(hstore,int)
+RETURNS bool
+AS 'MODULE_PATHNAME','hstore_exists_idx'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR ? (
+       LEFTARG = hstore,
+       RIGHTARG = int,
+       PROCEDURE = exist,
+       RESTRICT = contsel,
+       JOIN = contjoinsel
+);
+
+CREATE FUNCTION isexists(hstore,text[])
+RETURNS bool
+AS 'MODULE_PATHNAME','hstore_exists_path'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION exist(hstore,text[])
+RETURNS bool
+AS 'MODULE_PATHNAME','hstore_exists_path'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR #? (
+       LEFTARG = hstore,
+       RIGHTARG = text[],
+       PROCEDURE = exist,
+       RESTRICT = contsel,
+       JOIN = contjoinsel
+);
+
+CREATE FUNCTION delete_path(hstore,text[])
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_delete_path'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR #- (
+       LEFTARG = hstore,
+       RIGHTARG = text[],
+       PROCEDURE = delete_path
+);
+
+CREATE FUNCTION delete(hstore,int)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_delete_idx'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR - (
+       LEFTARG = hstore,
+       RIGHTARG = int,
+       PROCEDURE = delete
+);
+
+CREATE FUNCTION replace(hstore,text[],hstore)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_replace'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION svals(hstore, text[])
+RETURNS setof text
+AS 'MODULE_PATHNAME','hstore_svals_path'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION hvals(hstore)
+RETURNS setof hstore
+AS 'MODULE_PATHNAME','hstore_hvals'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION hvals(hstore, text[])
+RETURNS setof hstore
+AS 'MODULE_PATHNAME','hstore_hvals_path'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION concat_path(hstore,text[],hstore)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_deep_concat'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION each_hstore(IN hs hstore,
+       OUT key text,
+       OUT value hstore)
+RETURNS SETOF record
+AS 'MODULE_PATHNAME','hstore_each_hstore'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION hstore_typeof(hstore)
+RETURNS text 
+AS 'MODULE_PATHNAME','hstore_typeof'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION hstore(text,bool)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_from_bool'
+LANGUAGE C IMMUTABLE; -- not STRICT; needs to allow (key,NULL)
+
+CREATE FUNCTION hstore(text,numeric)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_from_numeric'
+LANGUAGE C IMMUTABLE; -- not STRICT; needs to allow (key,NULL)
+
+CREATE FUNCTION hstore(text)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_scalar_from_text'
+LANGUAGE C IMMUTABLE; -- not STRICT; needs to allow (key,NULL)
+
+CREATE FUNCTION hstore(bool)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_scalar_from_bool'
+LANGUAGE C IMMUTABLE; -- not STRICT; needs to allow (key,NULL)
+
+CREATE FUNCTION hstore(numeric)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_scalar_from_numeric'
+LANGUAGE C IMMUTABLE; -- not STRICT; needs to allow (key,NULL)
+
+
+-- GIN support: hash based opclass
+
+FUNCTION gin_extract_hstore_hash(internal, internal)
+RETURNS internal
+AS 'MODULE_PATHNAME'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE FUNCTION gin_extract_hstore_hash_query(internal, internal, int2, internal, internal)
+RETURNS internal
+AS 'MODULE_PATHNAME'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE FUNCTION gin_consistent_hstore_hash(internal, int2, internal, int4, internal, internal)
+RETURNS bool
+AS 'MODULE_PATHNAME'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE OPERATOR CLASS gin_hstore_hash_ops
+FOR TYPE hstore USING gin
+AS
+       OPERATOR        7       @>,
+       FUNCTION        1       btint4cmp(int4,int4),
+       FUNCTION        2       gin_extract_hstore_hash(internal, internal),
+       FUNCTION        3       gin_extract_hstore_hash_query(internal, internal, int2, internal, internal),
+       FUNCTION        4       gin_consistent_hstore_hash(internal, int2, internal, int4, internal, internal),
+STORAGE         int4;
+
+CREATE FUNCTION array_to_hstore(anyarray)
+RETURNS hstore
+AS 'MODULE_PATHNAME','array_to_hstore'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION hstore_pretty_print()
+RETURNS int4
+AS 'MODULE_PATHNAME'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE FUNCTION hstore_array_curly_braces()
+RETURNS int4
+AS 'MODULE_PATHNAME'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE FUNCTION hstore_json()
+RETURNS int4
+AS 'MODULE_PATHNAME'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE FUNCTION hstore_root_hash_decorated()
+RETURNS int4
+AS 'MODULE_PATHNAME'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE FUNCTION hstore_loose()
+RETURNS int4
+AS 'MODULE_PATHNAME'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE FUNCTION hstore_print(hstore,
+                                                        pretty_print bool DEFAULT false,
+                                                        array_curly_braces bool DEFAULT false,
+                                                        root_hash_decorated bool DEFAULT false,
+                                                        json bool DEFAULT false,
+                                                        loose bool DEFAULT false)
+RETURNS text
+AS 'MODULE_PATHNAME', 'hstore_print'
+LANGUAGE C IMMUTABLE STRICT;
+
diff --git a/hstore--1.3.sql b/hstore--1.3.sql
new file mode 100644 (file)
index 0000000..24e0b4b
--- /dev/null
@@ -0,0 +1,838 @@
+/* contrib/hstore/hstore--1.3.sql */
+
+-- complain if script is sourced in psql, rather than via CREATE EXTENSION
+\echo Use "CREATE EXTENSION hstore" to load this file. \quit
+
+CREATE TYPE hstore;
+
+CREATE FUNCTION hstore_in(cstring)
+RETURNS hstore
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION hstore_out(hstore)
+RETURNS cstring
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION hstore_recv(internal)
+RETURNS hstore
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION hstore_send(hstore)
+RETURNS bytea
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE TYPE hstore (
+        INTERNALLENGTH = -1,
+        INPUT = hstore_in,
+        OUTPUT = hstore_out,
+        RECEIVE = hstore_recv,
+        SEND = hstore_send,
+        STORAGE = extended
+);
+
+CREATE FUNCTION hstore_version_diag(hstore)
+RETURNS integer
+AS 'MODULE_PATHNAME','hstore_version_diag'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION fetchval(hstore,text)
+RETURNS text
+AS 'MODULE_PATHNAME','hstore_fetchval'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR -> (
+       LEFTARG = hstore,
+       RIGHTARG = text,
+       PROCEDURE = fetchval
+);
+
+CREATE FUNCTION fetchval_numeric(hstore,text)
+RETURNS numeric
+AS 'MODULE_PATHNAME','hstore_fetchval_numeric'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR ^> (
+       LEFTARG = hstore,
+       RIGHTARG = text,
+       PROCEDURE = fetchval_numeric
+);
+
+CREATE FUNCTION fetchval_boolean(hstore,text)
+RETURNS boolean
+AS 'MODULE_PATHNAME','hstore_fetchval_boolean'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR ?> (
+       LEFTARG = hstore,
+       RIGHTARG = text,
+       PROCEDURE = fetchval_boolean
+);
+
+CREATE FUNCTION fetchval(hstore,int)
+RETURNS text
+AS 'MODULE_PATHNAME','hstore_fetchval_n'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR -> (
+       LEFTARG = hstore,
+       RIGHTARG = int,
+       PROCEDURE = fetchval
+);
+
+CREATE FUNCTION fetchval_numeric(hstore,int)
+RETURNS numeric
+AS 'MODULE_PATHNAME','hstore_fetchval_n_numeric'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR ^> (
+       LEFTARG = hstore,
+       RIGHTARG = int,
+       PROCEDURE = fetchval_numeric
+);
+
+CREATE FUNCTION fetchval_boolean(hstore,int)
+RETURNS boolean
+AS 'MODULE_PATHNAME','hstore_fetchval_n_boolean'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR ?> (
+       LEFTARG = hstore,
+       RIGHTARG = int,
+       PROCEDURE = fetchval_boolean
+);
+
+CREATE FUNCTION fetchval(hstore,text[])
+RETURNS text
+AS 'MODULE_PATHNAME','hstore_fetchval_path'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR #> (
+       LEFTARG = hstore,
+       RIGHTARG = text[],
+       PROCEDURE = fetchval
+);
+
+CREATE FUNCTION fetchval_numeric(hstore,text[])
+RETURNS numeric
+AS 'MODULE_PATHNAME','hstore_fetchval_path_numeric'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR #^> (
+       LEFTARG = hstore,
+       RIGHTARG = text[],
+       PROCEDURE = fetchval_numeric
+);
+
+CREATE FUNCTION fetchval_boolean(hstore,text[])
+RETURNS boolean
+AS 'MODULE_PATHNAME','hstore_fetchval_path_boolean'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR #?> (
+       LEFTARG = hstore,
+       RIGHTARG = text[],
+       PROCEDURE = fetchval_boolean
+);
+
+CREATE FUNCTION fetchval_hstore(hstore,text)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_fetchval_hstore'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR %> (
+       LEFTARG = hstore,
+       RIGHTARG = text,
+       PROCEDURE = fetchval_hstore
+);
+
+CREATE FUNCTION fetchval_hstore(hstore,int)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_fetchval_n_hstore'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR %> (
+       LEFTARG = hstore,
+       RIGHTARG = int,
+       PROCEDURE = fetchval_hstore
+);
+
+CREATE FUNCTION fetchval_hstore(hstore,text[])
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_fetchval_path_hstore'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR #%> (
+       LEFTARG = hstore,
+       RIGHTARG = text[],
+       PROCEDURE = fetchval_hstore
+);
+
+CREATE FUNCTION slice_array(hstore,text[])
+RETURNS text[]
+AS 'MODULE_PATHNAME','hstore_slice_to_array'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR -> (
+       LEFTARG = hstore,
+       RIGHTARG = text[],
+       PROCEDURE = slice_array
+);
+
+CREATE FUNCTION slice(hstore,text[])
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_slice_to_hstore'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION isexists(hstore,text)
+RETURNS bool
+AS 'MODULE_PATHNAME','hstore_exists'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION exist(hstore,text)
+RETURNS bool
+AS 'MODULE_PATHNAME','hstore_exists'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR ? (
+       LEFTARG = hstore,
+       RIGHTARG = text,
+       PROCEDURE = exist,
+       RESTRICT = contsel,
+       JOIN = contjoinsel
+);
+
+CREATE FUNCTION isexists(hstore,int)
+RETURNS bool
+AS 'MODULE_PATHNAME','hstore_exists_idx'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION exist(hstore,int)
+RETURNS bool
+AS 'MODULE_PATHNAME','hstore_exists_idx'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR ? (
+       LEFTARG = hstore,
+       RIGHTARG = int,
+       PROCEDURE = exist,
+       RESTRICT = contsel,
+       JOIN = contjoinsel
+);
+
+CREATE FUNCTION isexists(hstore,text[])
+RETURNS bool
+AS 'MODULE_PATHNAME','hstore_exists_path'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION exist(hstore,text[])
+RETURNS bool
+AS 'MODULE_PATHNAME','hstore_exists_path'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR #? (
+       LEFTARG = hstore,
+       RIGHTARG = text[],
+       PROCEDURE = exist,
+       RESTRICT = contsel,
+       JOIN = contjoinsel
+);
+
+CREATE FUNCTION exists_any(hstore,text[])
+RETURNS bool
+AS 'MODULE_PATHNAME','hstore_exists_any'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR ?| (
+       LEFTARG = hstore,
+       RIGHTARG = text[],
+       PROCEDURE = exists_any,
+       RESTRICT = contsel,
+       JOIN = contjoinsel
+);
+
+CREATE FUNCTION exists_all(hstore,text[])
+RETURNS bool
+AS 'MODULE_PATHNAME','hstore_exists_all'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR ?& (
+       LEFTARG = hstore,
+       RIGHTARG = text[],
+       PROCEDURE = exists_all,
+       RESTRICT = contsel,
+       JOIN = contjoinsel
+);
+
+CREATE FUNCTION isdefined(hstore,text)
+RETURNS bool
+AS 'MODULE_PATHNAME','hstore_defined'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION defined(hstore,text)
+RETURNS bool
+AS 'MODULE_PATHNAME','hstore_defined'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION delete(hstore,text)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_delete'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION delete(hstore,int)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_delete_idx'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION delete(hstore,text[])
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_delete_array'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION delete(hstore,hstore)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_delete_hstore'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION delete_path(hstore,text[])
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_delete_path'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR - (
+       LEFTARG = hstore,
+       RIGHTARG = text,
+       PROCEDURE = delete
+);
+
+CREATE OPERATOR - (
+       LEFTARG = hstore,
+       RIGHTARG = int,
+       PROCEDURE = delete
+);
+
+CREATE OPERATOR - (
+       LEFTARG = hstore,
+       RIGHTARG = text[],
+       PROCEDURE = delete
+);
+
+CREATE OPERATOR - (
+       LEFTARG = hstore,
+       RIGHTARG = hstore,
+       PROCEDURE = delete
+);
+
+CREATE OPERATOR #- (
+       LEFTARG = hstore,
+       RIGHTARG = text[],
+       PROCEDURE = delete_path
+);
+
+CREATE FUNCTION replace(hstore,text[],hstore)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_replace'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION hs_concat(hstore,hstore)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_concat'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR || (
+       LEFTARG = hstore,
+       RIGHTARG = hstore,
+       PROCEDURE = hs_concat
+);
+
+CREATE FUNCTION concat_path(hstore,text[],hstore)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_deep_concat'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION hs_contains(hstore,hstore)
+RETURNS bool
+AS 'MODULE_PATHNAME','hstore_contains'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION hs_contained(hstore,hstore)
+RETURNS bool
+AS 'MODULE_PATHNAME','hstore_contained'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR @> (
+       LEFTARG = hstore,
+       RIGHTARG = hstore,
+       PROCEDURE = hs_contains,
+       COMMUTATOR = '<@',
+       RESTRICT = contsel,
+       JOIN = contjoinsel
+);
+
+CREATE OPERATOR <@ (
+       LEFTARG = hstore,
+       RIGHTARG = hstore,
+       PROCEDURE = hs_contained,
+       COMMUTATOR = '@>',
+       RESTRICT = contsel,
+       JOIN = contjoinsel
+);
+
+-- obsolete:
+CREATE OPERATOR @ (
+       LEFTARG = hstore,
+       RIGHTARG = hstore,
+       PROCEDURE = hs_contains,
+       COMMUTATOR = '~',
+       RESTRICT = contsel,
+       JOIN = contjoinsel
+);
+
+CREATE OPERATOR ~ (
+       LEFTARG = hstore,
+       RIGHTARG = hstore,
+       PROCEDURE = hs_contained,
+       COMMUTATOR = '@',
+       RESTRICT = contsel,
+       JOIN = contjoinsel
+);
+
+CREATE FUNCTION tconvert(text,text)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_from_text'
+LANGUAGE C IMMUTABLE; -- not STRICT; needs to allow (key,NULL)
+
+CREATE FUNCTION hstore(text,text)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_from_text'
+LANGUAGE C IMMUTABLE; -- not STRICT; needs to allow (key,NULL)
+
+CREATE FUNCTION hstore(text,bool)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_from_bool'
+LANGUAGE C IMMUTABLE; -- not STRICT; needs to allow (key,NULL)
+
+CREATE FUNCTION hstore(text,numeric)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_from_numeric'
+LANGUAGE C IMMUTABLE; -- not STRICT; needs to allow (key,NULL)
+
+CREATE FUNCTION hstore(text,hstore)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_from_th'
+LANGUAGE C IMMUTABLE; -- not STRICT; needs to allow (key,NULL)
+
+CREATE FUNCTION hstore(text)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_scalar_from_text'
+LANGUAGE C IMMUTABLE; -- not STRICT; needs to allow (key,NULL)
+
+CREATE FUNCTION hstore(bool)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_scalar_from_bool'
+LANGUAGE C IMMUTABLE; -- not STRICT; needs to allow (key,NULL)
+
+CREATE FUNCTION hstore(numeric)
+RETURNS hstore
+AS 'MODULE_PATHNAME','hstore_scalar_from_numeric'
+LANGUAGE C IMMUTABLE; -- not STRICT; needs to allow (key,NULL)
+
+CREATE FUNCTION hstore(text[],text[])
+RETURNS hstore
+AS 'MODULE_PATHNAME', 'hstore_from_arrays'
+LANGUAGE C IMMUTABLE; -- not STRICT; allows (keys,null)
+
+CREATE FUNCTION hstore(text[])
+RETURNS hstore
+AS 'MODULE_PATHNAME', 'hstore_from_array'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE CAST (text[] AS hstore)
+  WITH FUNCTION hstore(text[]);
+
+CREATE FUNCTION hstore_to_json(hstore)
+RETURNS json
+AS 'MODULE_PATHNAME', 'hstore_to_json'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE CAST (hstore AS json)
+  WITH FUNCTION hstore_to_json(hstore);
+
+CREATE FUNCTION hstore_to_json_loose(hstore)
+RETURNS json
+AS 'MODULE_PATHNAME', 'hstore_to_json_loose'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE FUNCTION hstore(record)
+RETURNS hstore
+AS 'MODULE_PATHNAME', 'hstore_from_record'
+LANGUAGE C IMMUTABLE; -- not STRICT; allows (null::recordtype)
+
+CREATE FUNCTION hstore_to_array(hstore)
+RETURNS text[]
+AS 'MODULE_PATHNAME','hstore_to_array'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR %% (
+       RIGHTARG = hstore,
+       PROCEDURE = hstore_to_array
+);
+
+CREATE FUNCTION hstore_to_matrix(hstore)
+RETURNS text[]
+AS 'MODULE_PATHNAME','hstore_to_matrix'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR %# (
+       RIGHTARG = hstore,
+       PROCEDURE = hstore_to_matrix
+);
+
+CREATE FUNCTION akeys(hstore)
+RETURNS text[]
+AS 'MODULE_PATHNAME','hstore_akeys'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION avals(hstore)
+RETURNS text[]
+AS 'MODULE_PATHNAME','hstore_avals'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION skeys(hstore)
+RETURNS setof text
+AS 'MODULE_PATHNAME','hstore_skeys'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION svals(hstore)
+RETURNS setof text
+AS 'MODULE_PATHNAME','hstore_svals'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION svals(hstore, text[])
+RETURNS setof text
+AS 'MODULE_PATHNAME','hstore_svals_path'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION hvals(hstore)
+RETURNS setof hstore
+AS 'MODULE_PATHNAME','hstore_hvals'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION hvals(hstore, text[])
+RETURNS setof hstore
+AS 'MODULE_PATHNAME','hstore_hvals_path'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION each(IN hs hstore,
+    OUT key text,
+    OUT value text)
+RETURNS SETOF record
+AS 'MODULE_PATHNAME','hstore_each'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION each_hstore(IN hs hstore,
+    OUT key text,
+    OUT value hstore)
+RETURNS SETOF record
+AS 'MODULE_PATHNAME','hstore_each_hstore'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION hstore_typeof(hstore)
+RETURNS text 
+AS 'MODULE_PATHNAME','hstore_typeof'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION populate_record(anyelement,hstore)
+RETURNS anyelement
+AS 'MODULE_PATHNAME', 'hstore_populate_record'
+LANGUAGE C IMMUTABLE; -- not STRICT; allows (null::rectype,hstore)
+
+CREATE OPERATOR #= (
+       LEFTARG = anyelement,
+       RIGHTARG = hstore,
+       PROCEDURE = populate_record
+);
+
+CREATE FUNCTION json_to_hstore(json)
+RETURNS hstore
+AS 'MODULE_PATHNAME','json_to_hstore'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE CAST (json AS hstore)
+WITH FUNCTION json_to_hstore(json);
+
+CREATE FUNCTION array_to_hstore(anyarray)
+RETURNS hstore
+AS 'MODULE_PATHNAME','array_to_hstore'
+LANGUAGE C STRICT IMMUTABLE;
+
+-- btree support
+
+CREATE FUNCTION hstore_eq(hstore,hstore)
+RETURNS boolean
+AS 'MODULE_PATHNAME','hstore_eq'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION hstore_ne(hstore,hstore)
+RETURNS boolean
+AS 'MODULE_PATHNAME','hstore_ne'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION hstore_gt(hstore,hstore)
+RETURNS boolean
+AS 'MODULE_PATHNAME','hstore_gt'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION hstore_ge(hstore,hstore)
+RETURNS boolean
+AS 'MODULE_PATHNAME','hstore_ge'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION hstore_lt(hstore,hstore)
+RETURNS boolean
+AS 'MODULE_PATHNAME','hstore_lt'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION hstore_le(hstore,hstore)
+RETURNS boolean
+AS 'MODULE_PATHNAME','hstore_le'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION hstore_cmp(hstore,hstore)
+RETURNS integer
+AS 'MODULE_PATHNAME','hstore_cmp'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR = (
+       LEFTARG = hstore,
+       RIGHTARG = hstore,
+       PROCEDURE = hstore_eq,
+       COMMUTATOR = =,
+       NEGATOR = <>,
+       RESTRICT = eqsel,
+       JOIN = eqjoinsel,
+       MERGES,
+       HASHES
+);
+CREATE OPERATOR <> (
+       LEFTARG = hstore,
+       RIGHTARG = hstore,
+       PROCEDURE = hstore_ne,
+       COMMUTATOR = <>,
+       NEGATOR = =,
+       RESTRICT = neqsel,
+       JOIN = neqjoinsel
+);
+
+-- the comparison operators have funky names (and are undocumented)
+-- in an attempt to discourage anyone from actually using them. they
+-- only exist to support the btree opclass
+
+CREATE OPERATOR #<# (
+       LEFTARG = hstore,
+       RIGHTARG = hstore,
+       PROCEDURE = hstore_lt,
+       COMMUTATOR = #>#,
+       NEGATOR = #>=#,
+       RESTRICT = scalarltsel,
+       JOIN = scalarltjoinsel
+);
+CREATE OPERATOR #<=# (
+       LEFTARG = hstore,
+       RIGHTARG = hstore,
+       PROCEDURE = hstore_le,
+       COMMUTATOR = #>=#,
+       NEGATOR = #>#,
+       RESTRICT = scalarltsel,
+       JOIN = scalarltjoinsel
+);
+CREATE OPERATOR #># (
+       LEFTARG = hstore,
+       RIGHTARG = hstore,
+       PROCEDURE = hstore_gt,
+       COMMUTATOR = #<#,
+       NEGATOR = #<=#,
+       RESTRICT = scalargtsel,
+       JOIN = scalargtjoinsel
+);
+CREATE OPERATOR #>=# (
+       LEFTARG = hstore,
+       RIGHTARG = hstore,
+       PROCEDURE = hstore_ge,
+       COMMUTATOR = #<=#,
+       NEGATOR = #<#,
+       RESTRICT = scalargtsel,
+       JOIN = scalargtjoinsel
+);
+
+CREATE OPERATOR CLASS btree_hstore_ops
+DEFAULT FOR TYPE hstore USING btree
+AS
+       OPERATOR        1       #<# ,
+       OPERATOR        2       #<=# ,
+       OPERATOR        3       = ,
+       OPERATOR        4       #>=# ,
+       OPERATOR        5       #># ,
+       FUNCTION        1       hstore_cmp(hstore,hstore);
+
+-- hash support
+
+CREATE FUNCTION hstore_hash(hstore)
+RETURNS integer
+AS 'MODULE_PATHNAME','hstore_hash'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE OPERATOR CLASS hash_hstore_ops
+DEFAULT FOR TYPE hstore USING hash
+AS
+       OPERATOR        1       = ,
+       FUNCTION        1       hstore_hash(hstore);
+
+-- GiST support
+
+CREATE TYPE ghstore;
+
+CREATE FUNCTION ghstore_in(cstring)
+RETURNS ghstore
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE FUNCTION ghstore_out(ghstore)
+RETURNS cstring
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT IMMUTABLE;
+
+CREATE TYPE ghstore (
+        INTERNALLENGTH = -1,
+        INPUT = ghstore_in,
+        OUTPUT = ghstore_out
+);
+
+CREATE FUNCTION ghstore_compress(internal)
+RETURNS internal
+AS 'MODULE_PATHNAME'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE FUNCTION ghstore_decompress(internal)
+RETURNS internal
+AS 'MODULE_PATHNAME'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE FUNCTION ghstore_penalty(internal,internal,internal)
+RETURNS internal
+AS 'MODULE_PATHNAME'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE FUNCTION ghstore_picksplit(internal, internal)
+RETURNS internal
+AS 'MODULE_PATHNAME'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE FUNCTION ghstore_union(internal, internal)
+RETURNS internal
+AS 'MODULE_PATHNAME'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE FUNCTION ghstore_same(internal, internal, internal)
+RETURNS internal
+AS 'MODULE_PATHNAME'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE FUNCTION ghstore_consistent(internal,internal,int,oid,internal)
+RETURNS bool
+AS 'MODULE_PATHNAME'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE OPERATOR CLASS gist_hstore_ops
+DEFAULT FOR TYPE hstore USING gist
+AS
+       OPERATOR        7       @> ,
+       OPERATOR        9       ?(hstore,text) ,
+       OPERATOR        10      ?|(hstore,text[]) ,
+       OPERATOR        11      ?&(hstore,text[]) ,
+        --OPERATOR        8       <@ ,
+        OPERATOR        13      @ ,
+        --OPERATOR        14      ~ ,
+        FUNCTION        1       ghstore_consistent (internal, internal, int, oid, internal),
+        FUNCTION        2       ghstore_union (internal, internal),
+        FUNCTION        3       ghstore_compress (internal),
+        FUNCTION        4       ghstore_decompress (internal),
+        FUNCTION        5       ghstore_penalty (internal, internal, internal),
+        FUNCTION        6       ghstore_picksplit (internal, internal),
+        FUNCTION        7       ghstore_same (internal, internal, internal),
+        STORAGE         ghstore;
+
+-- GIN support: default opclass
+
+CREATE FUNCTION gin_extract_hstore(internal, internal)
+RETURNS internal
+AS 'MODULE_PATHNAME'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE FUNCTION gin_extract_hstore_query(internal, internal, int2, internal, internal)
+RETURNS internal
+AS 'MODULE_PATHNAME'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE FUNCTION gin_consistent_hstore(internal, int2, internal, int4, internal, internal)
+RETURNS bool
+AS 'MODULE_PATHNAME'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE OPERATOR CLASS gin_hstore_ops
+DEFAULT FOR TYPE hstore USING gin
+AS
+       OPERATOR        7       @>,
+       OPERATOR        9       ?(hstore,text),
+       OPERATOR        10      ?|(hstore,text[]),
+       OPERATOR        11      ?&(hstore,text[]),
+       FUNCTION        1       bttextcmp(text,text),
+       FUNCTION        2       gin_extract_hstore(internal, internal),
+       FUNCTION        3       gin_extract_hstore_query(internal, internal, int2, internal, internal),
+       FUNCTION        4       gin_consistent_hstore(internal, int2, internal, int4, internal, internal),
+       STORAGE         text;
+
+-- GIN support: hash based opclass
+
+CREATE FUNCTION gin_extract_hstore_hash(internal, internal)
+RETURNS internal
+AS 'MODULE_PATHNAME'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE FUNCTION gin_extract_hstore_hash_query(internal, internal, int2, internal, internal)
+RETURNS internal
+AS 'MODULE_PATHNAME'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE FUNCTION gin_consistent_hstore_hash(internal, int2, internal, int4, internal, internal)
+RETURNS bool
+AS 'MODULE_PATHNAME'
+LANGUAGE C IMMUTABLE STRICT;
+
+CREATE OPERATOR CLASS gin_hstore_hash_ops
+FOR TYPE hstore USING gin
+AS
+       OPERATOR        7       @>,
+       FUNCTION        1       btint4cmp(int4,int4),
+       FUNCTION        2       gin_extract_hstore_hash(internal, internal),
+       FUNCTION        3       gin_extract_hstore_hash_query(internal, internal, int2, internal, internal),
+       FUNCTION        4       gin_consistent_hstore_hash(internal, int2, internal, int4, internal, internal),
+       STORAGE         int4;
+
+-- output
+
+CREATE FUNCTION hstore_print(hstore, 
+                                                        pretty_print bool DEFAULT false,
+                                                        array_curly_braces bool DEFAULT false,
+                                                        root_hash_decorated bool DEFAULT false,
+                                                        json bool DEFAULT false,
+                                                        loose bool DEFAULT false)
+RETURNS text
+AS 'MODULE_PATHNAME', 'hstore_print'
+LANGUAGE C IMMUTABLE STRICT;
+
+
+
diff --git a/hstore--unpackaged--1.0.sql b/hstore--unpackaged--1.0.sql
new file mode 100644 (file)
index 0000000..b7e73f4
--- /dev/null
@@ -0,0 +1,92 @@
+/* contrib/hstore/hstore--unpackaged--1.0.sql */
+
+-- complain if script is sourced in psql, rather than via CREATE EXTENSION
+\echo Use "CREATE EXTENSION hstore" to load this file. \quit
+
+ALTER EXTENSION hstore ADD type hstore;
+ALTER EXTENSION hstore ADD function hstore_in(cstring);
+ALTER EXTENSION hstore ADD function hstore_out(hstore);
+ALTER EXTENSION hstore ADD function hstore_recv(internal);
+ALTER EXTENSION hstore ADD function hstore_send(hstore);
+ALTER EXTENSION hstore ADD function hstore_version_diag(hstore);
+ALTER EXTENSION hstore ADD function fetchval(hstore,text);
+ALTER EXTENSION hstore ADD operator ->(hstore,text);
+ALTER EXTENSION hstore ADD function slice_array(hstore,text[]);
+ALTER EXTENSION hstore ADD operator ->(hstore,text[]);
+ALTER EXTENSION hstore ADD function slice(hstore,text[]);
+ALTER EXTENSION hstore ADD function isexists(hstore,text);
+ALTER EXTENSION hstore ADD function exist(hstore,text);
+ALTER EXTENSION hstore ADD operator ?(hstore,text);
+ALTER EXTENSION hstore ADD function exists_any(hstore,text[]);
+ALTER EXTENSION hstore ADD operator ?|(hstore,text[]);
+ALTER EXTENSION hstore ADD function exists_all(hstore,text[]);
+ALTER EXTENSION hstore ADD operator ?&(hstore,text[]);
+ALTER EXTENSION hstore ADD function isdefined(hstore,text);
+ALTER EXTENSION hstore ADD function defined(hstore,text);
+ALTER EXTENSION hstore ADD function delete(hstore,text);
+ALTER EXTENSION hstore ADD function delete(hstore,text[]);
+ALTER EXTENSION hstore ADD function delete(hstore,hstore);
+ALTER EXTENSION hstore ADD operator -(hstore,text);
+ALTER EXTENSION hstore ADD operator -(hstore,text[]);
+ALTER EXTENSION hstore ADD operator -(hstore,hstore);
+ALTER EXTENSION hstore ADD function hs_concat(hstore,hstore);
+ALTER EXTENSION hstore ADD operator ||(hstore,hstore);
+ALTER EXTENSION hstore ADD function hs_contains(hstore,hstore);
+ALTER EXTENSION hstore ADD function hs_contained(hstore,hstore);
+ALTER EXTENSION hstore ADD operator <@(hstore,hstore);
+ALTER EXTENSION hstore ADD operator @>(hstore,hstore);
+ALTER EXTENSION hstore ADD operator ~(hstore,hstore);
+ALTER EXTENSION hstore ADD operator @(hstore,hstore);
+ALTER EXTENSION hstore ADD function tconvert(text,text);
+ALTER EXTENSION hstore ADD function hstore(text,text);
+ALTER EXTENSION hstore ADD operator =>(text,text);
+ALTER EXTENSION hstore ADD function hstore(text[],text[]);
+ALTER EXTENSION hstore ADD function hstore(text[]);
+ALTER EXTENSION hstore ADD cast (text[] as hstore);
+ALTER EXTENSION hstore ADD function hstore(record);
+ALTER EXTENSION hstore ADD function hstore_to_array(hstore);
+ALTER EXTENSION hstore ADD operator %%(NONE,hstore);
+ALTER EXTENSION hstore ADD function hstore_to_matrix(hstore);
+ALTER EXTENSION hstore ADD operator %#(NONE,hstore);
+ALTER EXTENSION hstore ADD function akeys(hstore);
+ALTER EXTENSION hstore ADD function avals(hstore);
+ALTER EXTENSION hstore ADD function skeys(hstore);
+ALTER EXTENSION hstore ADD function svals(hstore);
+ALTER EXTENSION hstore ADD function each(hstore);
+ALTER EXTENSION hstore ADD function populate_record(anyelement,hstore);
+ALTER EXTENSION hstore ADD operator #=(anyelement,hstore);
+ALTER EXTENSION hstore ADD function hstore_eq(hstore,hstore);
+ALTER EXTENSION hstore ADD function hstore_ne(hstore,hstore);
+ALTER EXTENSION hstore ADD function hstore_gt(hstore,hstore);
+ALTER EXTENSION hstore ADD function hstore_ge(hstore,hstore);
+ALTER EXTENSION hstore ADD function hstore_lt(hstore,hstore);
+ALTER EXTENSION hstore ADD function hstore_le(hstore,hstore);
+ALTER EXTENSION hstore ADD function hstore_cmp(hstore,hstore);
+ALTER EXTENSION hstore ADD operator <>(hstore,hstore);
+ALTER EXTENSION hstore ADD operator =(hstore,hstore);
+ALTER EXTENSION hstore ADD operator #>#(hstore,hstore);
+ALTER EXTENSION hstore ADD operator #>=#(hstore,hstore);
+ALTER EXTENSION hstore ADD operator #<#(hstore,hstore);
+ALTER EXTENSION hstore ADD operator #<=#(hstore,hstore);
+ALTER EXTENSION hstore ADD operator family btree_hstore_ops using btree;
+ALTER EXTENSION hstore ADD operator class btree_hstore_ops using btree;
+ALTER EXTENSION hstore ADD function hstore_hash(hstore);
+ALTER EXTENSION hstore ADD operator family hash_hstore_ops using hash;
+ALTER EXTENSION hstore ADD operator class hash_hstore_ops using hash;
+ALTER EXTENSION hstore ADD type ghstore;
+ALTER EXTENSION hstore ADD function ghstore_in(cstring);
+ALTER EXTENSION hstore ADD function ghstore_out(ghstore);
+ALTER EXTENSION hstore ADD function ghstore_compress(internal);
+ALTER EXTENSION hstore ADD function ghstore_decompress(internal);
+ALTER EXTENSION hstore ADD function ghstore_penalty(internal,internal,internal);
+ALTER EXTENSION hstore ADD function ghstore_picksplit(internal,internal);
+ALTER EXTENSION hstore ADD function ghstore_union(internal,internal);
+ALTER EXTENSION hstore ADD function ghstore_same(internal,internal,internal);
+ALTER EXTENSION hstore ADD function ghstore_consistent(internal,internal,integer,oid,internal);
+ALTER EXTENSION hstore ADD operator family gist_hstore_ops using gist;
+ALTER EXTENSION hstore ADD operator class gist_hstore_ops using gist;
+ALTER EXTENSION hstore ADD function gin_extract_hstore(internal,internal);
+ALTER EXTENSION hstore ADD function gin_extract_hstore_query(internal,internal,smallint,internal,internal);
+ALTER EXTENSION hstore ADD function gin_consistent_hstore(internal,smallint,internal,integer,internal,internal);
+ALTER EXTENSION hstore ADD operator family gin_hstore_ops using gin;
+ALTER EXTENSION hstore ADD operator class gin_hstore_ops using gin;
diff --git a/hstore.control b/hstore.control
new file mode 100644 (file)
index 0000000..dcc3b68
--- /dev/null
@@ -0,0 +1,5 @@
+# hstore extension
+comment = 'data type for storing sets of (key, value) pairs'
+default_version = '1.3'
+module_pathname = '$libdir/hstore'
+relocatable = true
diff --git a/hstore.h b/hstore.h
new file mode 100644 (file)
index 0000000..956b194
--- /dev/null
+++ b/hstore.h
@@ -0,0 +1,292 @@
+/*
+ * contrib/hstore/hstore.h
+ */
+#ifndef __HSTORE_H__
+#define __HSTORE_H__
+
+#include "fmgr.h"
+#include "lib/stringinfo.h"
+#include "utils/array.h"
+#include "utils/numeric.h"
+
+/*
+ * HEntry: there is one of these for each key _and_ value in an hstore
+ *
+ * the position offset points to the _end_ so that we can get the length
+ * by subtraction from the previous entry.     the ISFIRST flag lets us tell
+ * whether there is a previous entry.
+ */
+typedef struct
+{
+       uint32          entry;
+} HEntry;
+
+#define HENTRY_ISFIRST         0x80000000
+#define HENTRY_ISSTRING        (0x00000000) /* keep binary compatibility */
+#define HENTRY_ISNUMERIC       (0x10000000)
+#define HENTRY_ISNEST          (0x20000000)
+#define HENTRY_ISNULL          (0x40000000) /* keep binary compatibility */
+#define HENTRY_ISBOOL          (0x10000000 | 0x20000000)
+#define HENTRY_ISFALSE         HENTRY_ISBOOL
+#define HENTRY_ISTRUE          (0x10000000 | 0x20000000 | 0x40000000)
+
+/* HENTRY_ISHASH, HENTRY_ISARRAY and HENTRY_ISSCALAR is only used in send/recv */
+#define HENTRY_ISHASH          (0x20000000)
+#define HENTRY_ISARRAY         (0x20000000 | 0x40000000)
+#define HENTRY_ISSCALAR                (0x10000000 | 0x40000000)
+
+#define HENTRY_POSMASK         0x0FFFFFFF
+#define HENTRY_TYPEMASK        (~(HENTRY_POSMASK | HENTRY_ISFIRST))
+
+/* note possible multiple evaluations, also access to prior array element */
+#define HSE_ISFIRST(he_)               (((he_).entry & HENTRY_ISFIRST) != 0)
+#define HSE_ISSTRING(he_)              (((he_).entry & HENTRY_TYPEMASK) == \
+                                                                                       HENTRY_ISSTRING)
+#define HSE_ISNUMERIC(he_)             (((he_).entry & HENTRY_TYPEMASK) == \
+                                                                                       HENTRY_ISNUMERIC)
+#define HSE_ISNEST(he_)                (((he_).entry & HENTRY_TYPEMASK) == \
+                                                                                       HENTRY_ISNEST)
+#define HSE_ISNULL(he_)                (((he_).entry & HENTRY_TYPEMASK) == \
+                                                                                       HENTRY_ISNULL)
+#define HSE_ISBOOL(he_)                (((he_).entry & HENTRY_ISBOOL)   == \
+                                                                                       HENTRY_ISBOOL)
+#define HSE_ISBOOL_TRUE(he_)   (((he_).entry & HENTRY_TYPEMASK) == \
+                                                                                       HENTRY_ISTRUE)
+#define HSE_ISBOOL_FALSE(he_)  (HSE_ISBOOL(he_) && !HSE_ISBOOL_TRUE(he_))
+
+#define HSE_ENDPOS(he_) ((he_).entry & HENTRY_POSMASK)
+#define HSE_OFF(he_) (HSE_ISFIRST(he_) ? 0 : HSE_ENDPOS((&(he_))[-1]))
+#define HSE_LEN(he_) (HSE_ISFIRST(he_) \
+                                         ? HSE_ENDPOS(he_) \
+                                         : HSE_ENDPOS(he_) - HSE_ENDPOS((&(he_))[-1]))
+
+/*
+ * determined by the size of "endpos" (ie HENTRY_POSMASK)
+ */
+#define HSTORE_MAX_KEY_LEN             HENTRY_POSMASK
+#define HSTORE_MAX_VALUE_LEN   HENTRY_POSMASK
+
+typedef struct
+{
+       int32           vl_len_;                /* varlena header (do not touch directly!) */
+       /* header of hash or array hstore type */
+       /* array of HEntry follows */
+} HStore;
+
+/*
+ * It's not possible to get more than 2^28 items into an hstore, so we reserve
+ * the top few bits of the size field.  See hstore_compat.c for one reason
+ * why.  Some bits are left for future use here.  MaxAllocSize makes the
+ * practical count limit slightly more than 2^28 / 3, or INT_MAX / 24, the
+ * limit for an hstore full of 4-byte keys and null values.  Therefore, we
+ * don't explicitly check the format-imposed limit.
+ */
+#define HS_FLAG_NEWVERSION             0x80000000
+#define HS_FLAG_ARRAY                  0x40000000
+#define HS_FLAG_HSTORE                 0x20000000
+#define HS_FLAG_SCALAR                 0x10000000
+
+#define HS_COUNT_MASK                  0x0FFFFFFF
+
+#define HS_ISEMPTY(hsp_)               (VARSIZE(hsp_) <= VARHDRSZ)
+#define HS_ROOT_COUNT(hsp_)    (HS_ISEMPTY(hsp_) ? 0 : \
+                                                                ( *(uint32*)VARDATA(hsp_) & HS_COUNT_MASK))
+#define HS_ROOT_IS_HASH(hsp_)  (HS_ISEMPTY(hsp_) ? 0 : \
+                                                                ( *(uint32*)VARDATA(hsp_) & HS_FLAG_HSTORE))
+#define HS_ROOT_IS_ARRAY(hsp_)         (HS_ISEMPTY(hsp_) ? 0 : \
+                                                                ( *(uint32*)VARDATA(hsp_) & HS_FLAG_ARRAY))
+#define HS_ROOT_IS_SCALAR(hsp_) (HS_ISEMPTY(hsp_) ? 0 : \
+                                                                ( *(uint32*)VARDATA(hsp_) & HS_FLAG_SCALAR))
+
+/* DatumGetHStoreP includes support for reading old-format hstore values */
+extern HStore *hstoreUpgrade(Datum orig);
+
+#define DatumGetHStoreP(d) hstoreUpgrade(d)
+
+#define PG_GETARG_HS(x) DatumGetHStoreP(PG_GETARG_DATUM(x))
+
+typedef struct HStorePair HStorePair;
+typedef struct HStoreValue HStoreValue;
+
+struct HStoreValue {
+       enum {
+               hsvNull,
+               hsvString,
+               hsvNumeric,
+               hsvBool,
+               hsvArray,
+               hsvHash,
+               hsvBinary  /* binary form of hsvArray/hsvHash */
+       } type;
+
+       uint32          size; /* estimation size of node (including subnodes) */
+
+       union {
+               Numeric                 numeric;
+               bool                    boolean;
+               struct {
+                       uint32          len;
+                       char            *val; /* could be not null-terminated */
+               } string;
+
+               struct {
+                       int                     nelems;
+                       HStoreValue     *elems;
+                       /*
+                        * scalar actually shares representation with array
+                        */
+                       bool            scalar;
+               } array;
+
+               struct {
+                       int                     npairs;
+                       HStorePair      *pairs;
+               } hash;
+
+               struct {
+                       uint32          len;
+                       char            *data;
+               } binary;
+       };
+
+};
+
+struct HStorePair {
+       HStoreValue     key;
+       HStoreValue     value;
+       uint32          order; /* to keep order of pairs with equal key */
+};
+
+
+extern HStoreValue* parseHStore(const char *str, int len, bool json);
+
+/*
+ * hstore support functios
+ */
+
+#define WHS_KEY                (0x001)
+#define WHS_VALUE              (0x002)
+#define WHS_ELEM                       (0x004)
+#define WHS_BEGIN_ARRAY        (0x008)
+#define WHS_END_ARRAY          (0x010)
+#define WHS_BEGIN_HASH     (0x020)
+#define WHS_END_HASH        (0x040)
+
+typedef void (*walk_hstore_cb)(void* /*arg*/, HStoreValue* /* value */,
+                                                                                       uint32 /* flags */, uint32 /* level */);
+extern void walkUncompressedHStore(HStoreValue *v,
+                                                                  walk_hstore_cb cb, void *cb_arg);
+
+extern int compareHStoreStringValue(const void *a, const void *b, void *arg);
+extern int compareHStorePair(const void *a, const void *b, void *arg);
+
+extern int compareHStoreBinaryValue(char *a, char *b);
+extern int compareHStoreValue(HStoreValue *a, HStoreValue *b);
+
+extern HStoreValue* findUncompressedHStoreValueByValue(char *buffer,
+                                                                                                          uint32 flags,
+                                                                                                          uint32 *lowbound,
+                                                                                                          HStoreValue* key);
+extern HStoreValue* findUncompressedHStoreValue(char *buffer, uint32 flags,
+                                                                                               uint32 *lowbound,
+                                                                                               char *key, uint32 keylen);
+
+extern HStoreValue* getHStoreValue(char *buffer, uint32 flags, int32 i);
+
+extern bool stringIsNumber(char *string, int len, bool jsonNumber);
+
+typedef enum HStoreOutputKind {
+       JsonOutput = 0x01,
+       LooseOutput = 0x02,
+       ArrayCurlyBraces = 0x04,
+       RootHashDecorated = 0x08,
+       PrettyPrint = 0x10
+} HStoreOutputKind;
+
+extern char* hstoreToCString(StringInfo out, char *in,
+                                                        int len /* just estimation */,
+                                                        HStoreOutputKind kind);
+extern text* HStoreValueToText(HStoreValue *v);
+
+typedef struct ToHStoreState
+{
+       HStoreValue             v;
+       uint32                  size;
+       struct ToHStoreState    *next;
+} ToHStoreState;
+
+extern HStoreValue* pushHStoreValue(ToHStoreState **state,
+                                                                       int r /* WHS_* */, HStoreValue *v);
+extern void uniqueHStoreValue(HStoreValue *v);
+extern uint32 compressHStore(HStoreValue *v, char *buffer);
+
+
+typedef struct HStoreIterator
+{
+       uint32                                  type;
+       uint32                                  nelems;
+       HEntry                                  *array;
+       bool                                    isScalar;
+       char                                    *data;
+       char                                    *buffer; /* unparsed buffer */
+
+       int                                             i;
+
+       /*
+        * enum members should be freely OR'ed with HS_FLAG_ARRAY/HS_FLAG_HSTORE
+        * with possiblity of decoding. See optimization in HStoreIteratorGet()
+        */
+       enum {
+               hsi_start       = 0x00,
+               hsi_key         = 0x01,
+               hsi_value       = 0x02,
+               hsi_elem        = 0x04
+       } state;
+
+       struct HStoreIterator   *next;
+} HStoreIterator;
+
+extern         HStoreIterator* HStoreIteratorInit(char *buffer);
+extern int /* WHS_* */ HStoreIteratorGet(HStoreIterator **it, HStoreValue *v,
+                                                                                 bool skipNested);
+
+#define HStoreContainsStrategyNumber   7
+#define HStoreExistsStrategyNumber     9
+#define HStoreExistsAnyStrategyNumber  10
+#define HStoreExistsAllStrategyNumber  11
+#define HStoreOldContainsStrategyNumber 13             /* backwards compatibility */
+
+/*
+ * defining HSTORE_POLLUTE_NAMESPACE=0 will prevent use of old function names;
+ * for now, we default to on for the benefit of people restoring old dumps
+ */
+#ifndef HSTORE_POLLUTE_NAMESPACE
+#define HSTORE_POLLUTE_NAMESPACE 1
+#endif
+
+#if HSTORE_POLLUTE_NAMESPACE
+#define HSTORE_POLLUTE(newname_,oldname_) \
+       PG_FUNCTION_INFO_V1(oldname_);            \
+       Datum oldname_(PG_FUNCTION_ARGS);         \
+       Datum newname_(PG_FUNCTION_ARGS);         \
+       Datum oldname_(PG_FUNCTION_ARGS) { return newname_(fcinfo); } \
+       extern int no_such_variable
+#else
+#define HSTORE_POLLUTE(newname_,oldname_) \
+       extern int no_such_variable
+#endif
+
+/*
+ * When using a GIN/GiST index for hstore, we choose to index both keys and values.
+ * The storage format is "text" values, with K, V, E or N prepended to the string
+ * to indicate key, value, element or null values.  (As of 9.1 it might be better to
+ * store null values as nulls, but we'll keep it this way for on-disk
+ * compatibility.) Before nested hstore GIN indexes used KV notation, so there is 
+ * no problem with upgrade, but GiST indexes should be rebuilded.
+ */
+#define ELEMFLAG    'E'
+#define KEYFLAG     'K'
+#define VALFLAG     'V'
+#define NULLFLAG    'N'
+
+#endif   /* __HSTORE_H__ */
diff --git a/hstore_compat.c b/hstore_compat.c
new file mode 100644 (file)
index 0000000..563456b
--- /dev/null
@@ -0,0 +1,449 @@
+/*
+ * contrib/hstore/hstore_compat.c
+
+Current nested hstore layout (see historical notes below):
+
+Hstore consists of varlena header, 4 bits (special flags), 28 bits for
+nelems/npairs, array of hentries and element array. Special flags are
+HS_FLAG_NEWVERSION,  HS_FLAG_ARRAY, HS_FLAG_HASH, HS_FLAG_SCALAR. Hentry
+starts from 4 special bits: 1st bit (ISFIRST) is set if there is no previous
+entry, next 3 bits are used to indicate type of hstore value (ISSTRING,
+ISNUMERIC, ISNEST, ISNULL, ISBOOL). Other 28 bits are ending position of
+hentry value relative to the beginning of element array.
+
+Hash key-value accessed as follow:
+first key starts from zero and ends at Hentry[0],i-th key starts from
+Hentry[i*2-1] and ends at Hentry[i*2], i-th value starts from
+align(HEntry[i*2]) and ends at HEntry[i*2 + 1]. Key-Value pairs are
+lexicographically ordered by keys.
+
+Array's first element starts from zero and ends at Hentry[0], and
+i-th element starts from align(HEntry[i - 1]) and ends at HEntry[i]. Elements
+are not ordered.
+
+Notes:
+Scalar stored as a single-element array.
+
+Limitations:
+Number of elements in array: 2^28
+Number of pairs in hash: 2^28
+Length of string: 2^28 bytes
+Length of nested hash or array: 2^28 bytes
+
+ *
+ * Notes on old/new hstore format disambiguation.
+ *
+ * There are three formats to consider:
+ * 1) old contrib/hstore (referred to as hstore-old)
+ * 2) prerelease pgfoundry hstore
+ * 3) new contrib/hstore (v2)
+ * 4) nested contrib/hstore (v3)
+ *
+ * (3) and (4) are upward binary compatible.
+ * (2) and (3) are identical except for the HS_FLAG_NEWVERSION
+ * bit, which is set in (3) but not (2).
+ *
+ * Values that are already in format (3), or which are
+ * unambiguously in format (2), are handled by the first
+ * "return immediately" test in hstoreUpgrade().
+ *
+ * To stress a point: we ONLY get here with possibly-ambiguous
+ * values if we're doing some sort of in-place migration from an
+ * old prerelease pgfoundry hstore-new; and we explicitly don't
+ * support that without fixing up any potentially padded values
+ * first. Most of the code here is serious overkill, but the
+ * performance penalty isn't serious (especially compared to the
+ * palloc() that we have to do anyway) and the belt-and-braces
+ * validity checks provide some reassurance. (If for some reason
+ * we get a value that would have worked on the old code, but
+ * which would be botched by the conversion code, the validity
+ * checks will fail it first so we get an error rather than bad
+ * data.)
+ *
+ * Note also that empty hstores are the same in (2) and (3), so
+ * there are some special-case paths for them.
+ *
+ * We tell the difference between formats (2) and (3) as follows (but
+ * note that there are some edge cases where we can't tell; see
+ * comments in hstoreUpgrade):
+ *
+ * First, since there must be at least one entry, we look at
+ * how the bits line up. The new format looks like:
+ *
+ * 10kkkkkkkkkkkkkkkkkkkkkkkkkkkkkk  (k..k = keylen)
+ * 0nvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv  (v..v = keylen+vallen)
+ *
+ * The old format looks like one of these, depending on endianness
+ * and bitfield layout: (k..k = keylen, v..v = vallen, p..p = pos,
+ * n = isnull)
+ *
+ * kkkkkkkkkkkkkkkkvvvvvvvvvvvvvvvv
+ * nppppppppppppppppppppppppppppppp
+ *
+ * kkkkkkkkkkkkkkkkvvvvvvvvvvvvvvvv
+ * pppppppppppppppppppppppppppppppn
+ *
+ * vvvvvvvvvvvvvvvvkkkkkkkkkkkkkkkk
+ * nppppppppppppppppppppppppppppppp
+ *
+ * vvvvvvvvvvvvvvvvkkkkkkkkkkkkkkkk
+ * pppppppppppppppppppppppppppppppn   (usual i386 format)
+ *
+ * If the entry is in old format, for the first entry "pos" must be 0.
+ * We can obviously see that either keylen or vallen must be >32768
+ * for there to be any ambiguity (which is why lengths less than that
+ * are fasttracked in hstore.h) Since "pos"==0, the "v" field in the
+ * new-format interpretation can only be 0 or 1, which constrains all
+ * but three bits of the old-format's k and v fields. But in addition
+ * to all of this, the data length implied by the keylen and vallen
+ * must fit in the varlena size. So the only ambiguous edge case for
+ * hstores with only one entry occurs between a new-format entry with
+ * an excess (~32k) of padding, and an old-format entry. But we know
+ * which format to use in that case based on how we were compiled, so
+ * no actual data corruption can occur.
+ *
+ * If there is more than one entry, the requirement that keys do not
+ * decrease in length, and that positions increase contiguously, and
+ * that the end of the data not be beyond the end of the varlena
+ * itself, disambiguates in almost all other cases. There is a small
+ * set of ambiguous cases which could occur if the old-format value
+ * has a large excess of padding and just the right pattern of key
+ * sizes, but these are also handled based on how we were compiled.
+ *
+ * The otherwise undocumented function hstore_version_diag is provided
+ * for testing purposes.
+ */
+#include "postgres.h"
+
+
+#include "hstore.h"
+
+/*
+ * This is the structure used for entries in the old contrib/hstore
+ * implementation. Notice that this is the same size as the new entry
+ * (two 32-bit words per key/value pair) and that the header is the
+ * same, so the old and new versions of ARRPTR, STRPTR, CALCDATASIZE
+ * etc. are compatible.
+ *
+ * If the above statement isn't true on some bizarre platform, we're
+ * a bit hosed (see StaticAssertStmt in hstoreValidOldFormat).
+ */
+typedef struct
+{
+       uint16          keylen;
+       uint16          vallen;
+       uint32
+                               valisnull:1,
+                               pos:31;
+} HOldEntry;
+
+/*
+ * New Old version (new not-nested version of hstore, v2 version)
+ * V2 and v3 (nested) are upward binary compatible. But
+ * framework was fully changed. Keep here old definitions (v2)
+ */
+
+
+typedef struct
+{
+       int32       vl_len_;        /* varlena header (do not touch directly!) */
+       uint32      size_;          /* flags and number of items in hstore */
+       /* array of HEntry follows */
+} HStoreV2;
+
+static int     hstoreValidNewFormat(HStoreV2 *hs);
+static int     hstoreValidOldFormat(HStoreV2 *hs);
+
+#define HS_COUNT(hsp_)     (HS_ISEMPTY(hsp_) ? 0 : ((hsp_)->size_ & HS_COUNT_MASK))
+#define HS_SETCOUNT(hsp_,c_)    ((hsp_)->size_ = (c_) | HS_FLAG_NEWVERSION | ((hsp_)->size_ & ~HS_COUNT_MASK))
+
+/*
+ * "x" comes from an existing HS_COUNT() (as discussed, <= INT_MAX/24) or a
+ * Pairs array length (due to MaxAllocSize, <= INT_MAX/40).  "lenstr" is no
+ * more than INT_MAX, that extreme case arising in hstore_from_arrays().
+ * Therefore, this calculation is limited to about INT_MAX / 5 + INT_MAX.
+ */
+#define HSHRDSIZE   (sizeof(HStoreV2))
+#define CALCDATASIZE(x, lenstr) ( (x) * 2 * sizeof(HEntry) + HSHRDSIZE + (lenstr) )
+/* note multiple evaluations of x */
+#define ARRPTR(x)       ( (HEntry*) ( (HStoreV2*)(x) + 1 ) )
+#define STRPTR(x)       ( (char*)(ARRPTR(x) + HS_ROOT_COUNT((HStoreV2*)(x)) * 2) )
+
+/* note multiple/non evaluations */
+#define HS_KEYLEN(arr_,i_) (HSE_LEN((arr_)[2*(i_)]))
+
+/* ensure the varlena size of an existing hstore is correct */
+#define HS_FIXSIZE(hsp_,count_)                                         \
+       do {                                                                \
+               int bl = (count_) ? HSE_ENDPOS(ARRPTR(hsp_)[2*(count_)-1]) : 0; \
+               SET_VARSIZE((hsp_), CALCDATASIZE((count_),bl));                 \
+       } while (0)
+
+/*
+ * Validity test for a new-format hstore.
+ *     0 = not valid
+ *     1 = valid but with "slop" in the length
+ *     2 = exactly valid
+ */
+static int
+hstoreValidNewFormat(HStoreV2 *hs)
+{
+       int                     count = HS_COUNT(hs);
+       HEntry     *entries = ARRPTR(hs);
+       int                     buflen = (count) ? HSE_ENDPOS(entries[2 * (count) - 1]) : 0;
+       int                     vsize = CALCDATASIZE(count, buflen);
+       int                     i;
+
+       if (hs->size_ & HS_FLAG_NEWVERSION)
+               return 2;
+
+       if (count == 0)
+               return 2;
+
+       if (!HSE_ISFIRST(entries[0]))
+               return 0;
+
+       if (vsize > VARSIZE(hs))
+               return 0;
+
+       /* entry position must be nondecreasing */
+
+       for (i = 1; i < 2 * count; ++i)
+       {
+               if (HSE_ISFIRST(entries[i])
+                       || (HSE_ENDPOS(entries[i]) < HSE_ENDPOS(entries[i - 1])))
+                       return 0;
+       }
+
+       /* key length must be nondecreasing and keys must not be null */
+
+       for (i = 1; i < count; ++i)
+       {
+               if (HS_KEYLEN(entries, i) < HS_KEYLEN(entries, i - 1))
+                       return 0;
+               if (HSE_ISNULL(entries[2 * i]))
+                       return 0;
+       }
+
+       if (vsize != VARSIZE(hs))
+               return 1;
+
+       return 2;
+}
+
+/*
+ * Validity test for an old-format hstore.
+ *     0 = not valid
+ *     1 = valid but with "slop" in the length
+ *     2 = exactly valid
+ */
+static int
+hstoreValidOldFormat(HStoreV2 *hs)
+{
+       int                     count = hs->size_;
+       HOldEntry  *entries = (HOldEntry *) ARRPTR(hs);
+       int                     vsize;
+       int                     lastpos = 0;
+       int                     i;
+
+       if (hs->size_ & HS_FLAG_NEWVERSION)
+               return 0;
+
+       /* New format uses an HEntry for key and another for value */
+       StaticAssertStmt(sizeof(HOldEntry) == 2 * sizeof(HEntry),
+                                        "old hstore format is not upward-compatible");
+
+       if (count == 0)
+               return 2;
+
+       if (count > 0xFFFFFFF)
+               return 0;
+
+       if (CALCDATASIZE(count, 0) > VARSIZE(hs))
+               return 0;
+
+       if (entries[0].pos != 0)
+               return 0;
+
+       /* key length must be nondecreasing */
+
+       for (i = 1; i < count; ++i)
+       {
+               if (entries[i].keylen < entries[i - 1].keylen)
+                       return 0;
+       }
+
+       /*
+        * entry position must be strictly increasing, except for the first entry
+        * (which can be ""=>"" and thus zero-length); and all entries must be
+        * properly contiguous
+        */
+
+       for (i = 0; i < count; ++i)
+       {
+               if (entries[i].pos != lastpos)
+                       return 0;
+               lastpos += (entries[i].keylen
+                                       + ((entries[i].valisnull) ? 0 : entries[i].vallen));
+       }
+
+       vsize = CALCDATASIZE(count, lastpos);
+
+       if (vsize > VARSIZE(hs))
+               return 0;
+
+       if (vsize != VARSIZE(hs))
+               return 1;
+
+       return 2;
+}
+
+
+/*
+ * hstoreUpgrade: PG_DETOAST_DATUM plus support for conversion of old hstores
+ */
+HStore *
+hstoreUpgrade(Datum orig)
+{
+       HStoreV2           *hs = (HStoreV2 *) PG_DETOAST_DATUM(orig);
+       int                     valid_new;
+       int                     valid_old;
+       bool            writable;
+
+       /* Return immediately if no conversion needed */
+       if (VARSIZE_ANY(hs) <= VARHDRSZ ||
+               (hs->size_ & HS_FLAG_NEWVERSION) ||
+               hs->size_ == 0 ||
+               (VARSIZE(hs) < 32768 && HSE_ISFIRST((ARRPTR(hs)[0]))))
+       {
+               if (VARSIZE_ANY_EXHDR(hs) == sizeof(hs->size_))
+               {
+                       /* 'new' format but not nested. And empty */
+                       hs = palloc(sizeof(VARHDRSZ));
+                       SET_VARSIZE(hs, VARHDRSZ);
+               }
+
+               return (HStore*)hs;
+       }
+
+       valid_new = hstoreValidNewFormat(hs);
+       valid_old = hstoreValidOldFormat(hs);
+       /* Do we have a writable copy? */
+       writable = ((void *) hs != (void *) DatumGetPointer(orig));
+
+       if (!valid_old || hs->size_ == 0)
+       {
+               if (valid_new)
+               {
+                       /*
+                        * force the "new version" flag and the correct varlena length,
+                        * but only if we have a writable copy already (which we almost
+                        * always will, since short new-format values won't come through
+                        * here)
+                        */
+                       if (writable)
+                       {
+                               HS_SETCOUNT(hs, HS_COUNT(hs));
+                               HS_FIXSIZE(hs, HS_COUNT(hs));
+                       }
+                       return (HStore*)hs;
+               }
+               else
+               {
+                       elog(ERROR, "invalid hstore value found");
+               }
+       }
+
+       /*
+        * this is the tricky edge case. It is only possible in some quite extreme
+        * cases (the hstore must have had a lot of wasted padding space at the
+        * end). But the only way a "new" hstore value could get here is if we're
+        * upgrading in place from a pre-release version of hstore-new (NOT
+        * contrib/hstore), so we work off the following assumptions: 1. If you're
+        * moving from old contrib/hstore to hstore-new, you're required to fix up
+        * any potential conflicts first, e.g. by running ALTER TABLE ... USING
+        * col::text::hstore; on all hstore columns before upgrading. 2. If you're
+        * moving from old contrib/hstore to new contrib/hstore, then "new" values
+        * are impossible here 3. If you're moving from pre-release hstore-new to
+        * hstore-new, then "old" values are impossible here 4. If you're moving
+        * from pre-release hstore-new to new contrib/hstore, you're not doing so
+        * as an in-place upgrade, so there is no issue So the upshot of all this
+        * is that we can treat all the edge cases as "new" if we're being built
+        * as hstore-new, and "old" if we're being built as contrib/hstore.
+        *
+        * XXX the WARNING can probably be downgraded to DEBUG1 once this has been
+        * beta-tested. But for now, it would be very useful to know if anyone can
+        * actually reach this case in a non-contrived setting.
+        */
+
+       if (valid_new)
+       {
+#if HSTORE_IS_HSTORE_NEW
+               elog(WARNING, "ambiguous hstore value resolved as hstore-new");
+
+               /*
+                * force the "new version" flag and the correct varlena length, but
+                * only if we have a writable copy already (which we almost always
+                * will, since short new-format values won't come through here)
+                */
+               if (writable)
+               {
+                       HS_SETCOUNT(hs, HS_COUNT(hs));
+                       HS_FIXSIZE(hs, HS_COUNT(hs));
+               }
+               return hs;
+#else
+               elog(WARNING, "ambiguous hstore value resolved as hstore-old");
+#endif
+       }
+
+       /*
+        * must have an old-style value. Overwrite it in place as a new-style one,
+        * making sure we have a writable copy first.
+        */
+
+       if (!writable)
+               hs = (HStoreV2 *) PG_DETOAST_DATUM_COPY(orig);
+
+       {
+               int                     count = hs->size_;
+               HEntry     *new_entries = ARRPTR(hs);
+               HOldEntry  *old_entries = (HOldEntry *) ARRPTR(hs);
+               int                     i;
+
+               for (i = 0; i < count; ++i)
+               {
+                       uint32          pos = old_entries[i].pos;
+                       uint32          keylen = old_entries[i].keylen;
+                       uint32          vallen = old_entries[i].vallen;
+                       bool            isnull = old_entries[i].valisnull;
+
+                       if (isnull)
+                               vallen = 0;
+
+                       new_entries[2 * i].entry = (pos + keylen) & HENTRY_POSMASK;
+                       new_entries[2 * i + 1].entry = (((pos + keylen + vallen) & HENTRY_POSMASK)
+                                                                                       | ((isnull) ? HENTRY_ISNULL : 0));
+               }
+
+               if (count)
+                       new_entries[0].entry |= HENTRY_ISFIRST;
+               HS_SETCOUNT(hs, count);
+               HS_FIXSIZE(hs, count);
+       }
+
+       return (HStore*)hs;
+}
+
+
+PG_FUNCTION_INFO_V1(hstore_version_diag);
+Datum          hstore_version_diag(PG_FUNCTION_ARGS);
+Datum
+hstore_version_diag(PG_FUNCTION_ARGS)
+{
+       HStoreV2           *hs = (HStoreV2 *) PG_DETOAST_DATUM(PG_GETARG_DATUM(0));
+       int                     valid_new = hstoreValidNewFormat(hs);
+       int                     valid_old = hstoreValidOldFormat(hs);
+
+       PG_RETURN_INT32(valid_old * 10 + valid_new);
+}
diff --git a/hstore_gin.c b/hstore_gin.c
new file mode 100644 (file)
index 0000000..282facb
--- /dev/null
@@ -0,0 +1,451 @@
+/*
+ * contrib/hstore/hstore_gin.c
+ */
+#include "postgres.h"
+
+#include "access/gin.h"
+#include "access/skey.h"
+#include "catalog/pg_type.h"
+#include "utils/builtins.h"
+
+#include "hstore.h"
+
+
+PG_FUNCTION_INFO_V1(gin_extract_hstore);
+Datum          gin_extract_hstore(PG_FUNCTION_ARGS);
+
+/* Build an indexable text value */
+static text *
+makeitem(char *str, int len, char flag)
+{
+       text       *item;
+
+       item = (text *) palloc(VARHDRSZ + len + 1);
+       SET_VARSIZE(item, VARHDRSZ + len + 1);
+
+       *VARDATA(item) = flag;
+
+       if (str && len > 0)
+               memcpy(VARDATA(item) + 1, str, len);
+
+       return item;
+}
+
+static text *
+makeitemFromValue(HStoreValue *v, char flag)
+{
+       text            *item;
+       char            *cstr;
+
+       switch(v->type)
+       {
+               case hsvNull:
+                       item = makeitem(NULL, 0, NULLFLAG);
+                       break;
+               case hsvBool:
+                       item = makeitem((v->boolean) ? " t" : " f", 2, flag);
+                       break;
+               case hsvNumeric:
+                       /*
+                        * It's needed to get some text representaion of
+                        * numeric independed from locale setting and 
+                        * preciosion. We use hashed value - it's safe
+                        * because recheck flag will be set anyway
+                        */
+                       cstr = palloc(8 /* hex numbers */ + 1 /* \0 */);
+                       snprintf(cstr, 9, "%08x",  DatumGetInt32(DirectFunctionCall1(hash_numeric,
+                                                                                                       NumericGetDatum(v->numeric))));
+                       item = makeitem(cstr, 8, flag);
+                       pfree(cstr);
+                       break;
+               case hsvString:
+                       item = makeitem(v->string.val, v->string.len, flag);
+                       break;
+               default:
+                       elog(ERROR, "Wrong hstore type");
+       }
+
+       return item;
+}
+
+
+Datum
+gin_extract_hstore(PG_FUNCTION_ARGS)
+{
+       HStore                  *hs = PG_GETARG_HS(0);
+       int32                   *nentries = (int32 *) PG_GETARG_POINTER(1);
+       Datum                   *entries = NULL;
+       int                             total = 2 * HS_ROOT_COUNT(hs);
+       int                             i = 0, r;
+       HStoreIterator  *it;
+       HStoreValue             v;
+
+       if (total == 0)
+       {
+               *nentries = 0;
+               PG_RETURN_POINTER(NULL);
+       }
+
+       entries = (Datum *) palloc(sizeof(Datum) * total);
+
+       it = HStoreIteratorInit(VARDATA(hs));
+
+       while((r = HStoreIteratorGet(&it, &v, false)) != 0)
+       {
+               if (i >= total)
+               {
+                       total *= 2;
+                       entries = (Datum *) repalloc(entries, sizeof(Datum) * total);
+               }
+
+               switch(r)
+               {
+                       case WHS_KEY:
+                               entries[i++] = PointerGetDatum(makeitemFromValue(&v, KEYFLAG));
+                               break;
+                       case WHS_VALUE:
+                               entries[i++] = PointerGetDatum(makeitemFromValue(&v, VALFLAG));
+                               break;
+                       case WHS_ELEM:
+                               entries[i++] = PointerGetDatum(makeitemFromValue(&v, ELEMFLAG));
+                               break;
+                       default:
+                               break;
+               }
+       }
+
+       *nentries = i;
+
+       PG_RETURN_POINTER(entries);
+}
+
+PG_FUNCTION_INFO_V1(gin_extract_hstore_query);
+Datum          gin_extract_hstore_query(PG_FUNCTION_ARGS);
+
+Datum
+gin_extract_hstore_query(PG_FUNCTION_ARGS)
+{
+       int32      *nentries = (int32 *) PG_GETARG_POINTER(1);
+       StrategyNumber strategy = PG_GETARG_UINT16(2);
+       int32      *searchMode = (int32 *) PG_GETARG_POINTER(6);
+       Datum      *entries;
+
+       if (strategy == HStoreContainsStrategyNumber)
+       {
+               /* Query is an hstore, so just apply gin_extract_hstore... */
+               entries = (Datum *)
+                       DatumGetPointer(DirectFunctionCall2(gin_extract_hstore,
+                                                                                               PG_GETARG_DATUM(0),
+                                                                                               PointerGetDatum(nentries)));
+               /* ... except that "contains {}" requires a full index scan */
+               if (entries == NULL)
+                       *searchMode = GIN_SEARCH_MODE_ALL;
+       }
+       else if (strategy == HStoreExistsStrategyNumber)
+       {
+               text       *query = PG_GETARG_TEXT_PP(0);
+               text       *item;
+
+               *nentries = 1;
+               entries = (Datum *) palloc(sizeof(Datum));
+               item = makeitem(VARDATA_ANY(query), VARSIZE_ANY_EXHDR(query), KEYFLAG);
+               entries[0] = PointerGetDatum(item);
+       }
+       else if (strategy == HStoreExistsAnyStrategyNumber ||
+                        strategy == HStoreExistsAllStrategyNumber)
+       {
+               ArrayType  *query = PG_GETARG_ARRAYTYPE_P(0);
+               Datum      *key_datums;
+               bool       *key_nulls;
+               int                     key_count;
+               int                     i,
+                                       j;
+               text       *item;
+
+               deconstruct_array(query,
+                                                 TEXTOID, -1, false, 'i',
+                                                 &key_datums, &key_nulls, &key_count);
+
+               entries = (Datum *) palloc(sizeof(Datum) * key_count);
+
+               for (i = 0, j = 0; i < key_count; ++i)
+               {
+                       /* Nulls in the array are ignored, cf hstoreArrayToPairs */
+                       if (key_nulls[i])
+                               continue;
+                       item = makeitem(VARDATA(key_datums[i]),
+                                                       VARSIZE(key_datums[i]) - VARHDRSZ, KEYFLAG);
+                       entries[j++] = PointerGetDatum(item);
+               }
+
+               *nentries = j;
+               /* ExistsAll with no keys should match everything */
+               if (j == 0 && strategy == HStoreExistsAllStrategyNumber)
+                       *searchMode = GIN_SEARCH_MODE_ALL;
+       }
+       else
+       {
+               elog(ERROR, "unrecognized strategy number: %d", strategy);
+               entries = NULL;                 /* keep compiler quiet */
+       }
+
+       PG_RETURN_POINTER(entries);
+}
+
+PG_FUNCTION_INFO_V1(gin_consistent_hstore);
+Datum          gin_consistent_hstore(PG_FUNCTION_ARGS);
+
+Datum
+gin_consistent_hstore(PG_FUNCTION_ARGS)
+{
+       bool       *check = (bool *) PG_GETARG_POINTER(0);
+       StrategyNumber strategy = PG_GETARG_UINT16(1);
+
+       /* HStore          *query = PG_GETARG_HS(2); */
+       int32           nkeys = PG_GETARG_INT32(3);
+
+       /* Pointer         *extra_data = (Pointer *) PG_GETARG_POINTER(4); */
+       bool       *recheck = (bool *) PG_GETARG_POINTER(5);
+       bool            res = true;
+       int32           i;
+
+       if (strategy == HStoreContainsStrategyNumber)
+       {
+               /*
+                * Index doesn't have information about correspondence of keys and
+                * values, so we need recheck.  However, if not all the keys are
+                * present, we can fail at once.
+                */
+               *recheck = true;
+               for (i = 0; i < nkeys; i++)
+               {
+                       if (!check[i])
+                       {
+                               res = false;
+                               break;
+                       }
+               }
+       }
+       else if (strategy == HStoreExistsStrategyNumber)
+       {
+               /* Existence of key is guaranteed in default search mode */
+               *recheck = false;
+               res = true;
+       }
+       else if (strategy == HStoreExistsAnyStrategyNumber)
+       {
+               /* Existence of key is guaranteed in default search mode */
+               *recheck = false;
+               res = true;
+       }
+       else if (strategy == HStoreExistsAllStrategyNumber)
+       {
+               /* Testing for all the keys being present gives an exact result */
+               *recheck = false;
+               for (i = 0; i < nkeys; i++)
+               {
+                       if (!check[i])
+                       {
+                               res = false;
+                               break;
+                       }
+               }
+       }
+       else
+               elog(ERROR, "unrecognized strategy number: %d", strategy);
+
+       PG_RETURN_BOOL(res);
+}
+
+PG_FUNCTION_INFO_V1(gin_consistent_hstore_hash);
+Datum          gin_consistent_hstore_hash(PG_FUNCTION_ARGS);
+
+Datum
+gin_consistent_hstore_hash(PG_FUNCTION_ARGS)
+{
+       bool       *check = (bool *) PG_GETARG_POINTER(0);
+       StrategyNumber strategy = PG_GETARG_UINT16(1);
+
+       /* HStore          *query = PG_GETARG_HS(2); */
+       int32           nkeys = PG_GETARG_INT32(3);
+
+       /* Pointer         *extra_data = (Pointer *) PG_GETARG_POINTER(4); */
+       bool       *recheck = (bool *) PG_GETARG_POINTER(5);
+       bool            res = true;
+       int32           i;
+
+       if (strategy == HStoreContainsStrategyNumber)
+       {
+               /*
+                * Index doesn't have information about correspondence of keys and
+                * values, so we need recheck.  However, if not all the keys are
+                * present, we can fail at once.
+                */
+               *recheck = true;
+               for (i = 0; i < nkeys; i++)
+               {
+                       if (!check[i])
+                       {
+                               res = false;
+                               break;
+                       }
+               }
+       }
+       else
+               elog(ERROR, "unrecognized strategy number: %d", strategy);
+
+       PG_RETURN_BOOL(res);
+}
+
+PG_FUNCTION_INFO_V1(gin_extract_hstore_hash);
+Datum          gin_extract_hstore_hash(PG_FUNCTION_ARGS);
+
+typedef struct PathHashStack
+{
+       pg_crc32                          hash_state;
+       struct PathHashStack *next;
+} PathHashStack;
+
+#define PATH_SEPARATOR ("\0")
+
+static void
+hash_value(HStoreValue *v, PathHashStack *stack)
+{
+       switch(v->type)
+       {
+               case hsvNull:
+                       COMP_CRC32(stack->hash_state, "NULL", 5 /* include trailing \0 */);
+                       break;
+               case hsvBool:
+                       COMP_CRC32(stack->hash_state, (v->boolean) ? " t" : " f", 2 /* include trailing \0 */);
+                       break;
+               case hsvNumeric:
+                       stack->hash_state ^= DatumGetInt32(DirectFunctionCall1(hash_numeric,
+                                                                                               NumericGetDatum(v->numeric)));
+                       break;
+               case hsvString:
+                       COMP_CRC32(stack->hash_state, v->string.val, v->string.len);
+                       break;
+               default:
+                       elog(ERROR, "Shouldn't take hash of array");
+                       break;
+       }
+}
+
+Datum
+gin_extract_hstore_hash(PG_FUNCTION_ARGS)
+{
+       HStore                  *hs = PG_GETARG_HS(0);
+       int32                   *nentries = (int32 *) PG_GETARG_POINTER(1);
+       Datum                   *entries = NULL;
+       int                             total = 2 * HS_ROOT_COUNT(hs);
+       int                             i = 0, r;
+       HStoreIterator  *it;
+       HStoreValue             v;
+       PathHashStack   tail;
+       PathHashStack   *stack, *tmp;
+       pg_crc32                path_crc32;
+
+       if (total == 0)
+       {
+               *nentries = 0;
+               PG_RETURN_POINTER(NULL);
+       }
+
+       entries = (Datum *) palloc(sizeof(Datum) * total);
+
+       it = HStoreIteratorInit(VARDATA(hs));
+
+       tail.next = NULL;
+       INIT_CRC32(tail.hash_state);
+       stack = &tail;
+
+       /*
+        * Calculate hashes of all key_1.key_2. ... .key_n.value paths as entries.
+        * Order of array elements doesn't matter so array keys are empty in path.
+        * For faster calculation of hashes use stack for precalculated hashes
+        * of prefixes.
+        */
+       while((r = HStoreIteratorGet(&it, &v, false)) != 0)
+       {
+               if (i >= total)
+               {
+                       total *= 2;
+                       entries = (Datum *) repalloc(entries, sizeof(Datum) * total);
+               }
+
+               switch(r)
+               {
+                       case WHS_BEGIN_ARRAY:
+                               tmp = stack;
+                               stack = (PathHashStack *)palloc(sizeof(PathHashStack));
+                               stack->next = tmp;
+                               stack->hash_state = tmp->hash_state;
+                               COMP_CRC32(stack->hash_state, PATH_SEPARATOR, 1);
+                               break;
+                       case WHS_BEGIN_HASH:
+                               /* Preserve stack item for key */
+                               tmp = stack;
+                               stack = (PathHashStack *)palloc(sizeof(PathHashStack));
+                               stack->next = tmp;
+                               break;
+                       case WHS_KEY:
+                               /* Calc hash of key and separated into preserved stack item */
+                               stack->hash_state = stack->next->hash_state;
+                               hash_value(&v, stack);
+                               COMP_CRC32(stack->hash_state, PATH_SEPARATOR, 1);
+                               break;
+                       case WHS_VALUE:
+                       case WHS_ELEM:
+                               path_crc32 = stack->hash_state;
+                               hash_value(&v, stack);
+                               FIN_CRC32(path_crc32);
+                               entries[i++] = path_crc32;
+                               break;
+                       case WHS_END_ARRAY:
+                       case WHS_END_HASH:
+                               /* Pop stack item */
+                               tmp = stack->next;
+                               pfree(stack);
+                               stack = tmp;
+                               break;
+                       default:
+                               break;
+               }
+       }
+
+       *nentries = i;
+
+       PG_RETURN_POINTER(entries);
+}
+
+PG_FUNCTION_INFO_V1(gin_extract_hstore_hash_query);
+Datum          gin_extract_hstore_hash_query(PG_FUNCTION_ARGS);
+
+Datum
+gin_extract_hstore_hash_query(PG_FUNCTION_ARGS)
+{
+       int32      *nentries = (int32 *) PG_GETARG_POINTER(1);
+       StrategyNumber strategy = PG_GETARG_UINT16(2);
+       int32      *searchMode = (int32 *) PG_GETARG_POINTER(6);
+       Datum      *entries;
+
+       if (strategy == HStoreContainsStrategyNumber)
+       {
+               /* Query is an hstore, so just apply gin_extract_hstore... */
+               entries = (Datum *)
+                       DatumGetPointer(DirectFunctionCall2(gin_extract_hstore_hash,
+                                                                                               PG_GETARG_DATUM(0),
+                                                                                               PointerGetDatum(nentries)));
+               /* ... except that "contains {}" requires a full index scan */
+               if (entries == NULL)
+                       *searchMode = GIN_SEARCH_MODE_ALL;
+       }
+       else
+       {
+               elog(ERROR, "unrecognized strategy number: %d", strategy);
+               entries = NULL;                 /* keep compiler quiet */
+       }
+
+       PG_RETURN_POINTER(entries);
+}
diff --git a/hstore_gist.c b/hstore_gist.c
new file mode 100644 (file)
index 0000000..21d90e3
--- /dev/null
@@ -0,0 +1,703 @@
+/*
+ * contrib/hstore/hstore_gist.c
+ */
+#include "postgres.h"
+
+#include "access/gist.h"
+#include "access/skey.h"
+#include "catalog/pg_type.h"
+#include "utils/builtins.h"
+#include "utils/pg_crc.h"
+
+#include "hstore.h"
+
+/* bigint defines */
+#define BITBYTE 8
+#define SIGLENINT  4                   /* >122 => key will toast, so very slow!!! */
+#define SIGLEN ( sizeof(int)*SIGLENINT )
+#define SIGLENBIT (SIGLEN*BITBYTE)
+
+typedef char BITVEC[SIGLEN];
+typedef char *BITVECP;
+
+#define SIGPTR(x)  ( (BITVECP) ARR_DATA_PTR(x) )
+
+
+#define LOOPBYTE \
+                       for(i=0;i<SIGLEN;i++)
+
+#define LOOPBIT \
+                       for(i=0;i<SIGLENBIT;i++)
+
+/* beware of multiple evaluation of arguments to these macros! */
+#define GETBYTE(x,i) ( *( (BITVECP)(x) + (int)( (i) / BITBYTE ) ) )
+#define GETBITBYTE(x,i) ( (*((char*)(x)) >> (i)) & 0x01 )
+#define CLRBIT(x,i)   GETBYTE(x,i) &= ~( 0x01 << ( (i) % BITBYTE ) )
+#define SETBIT(x,i)   GETBYTE(x,i) |=  ( 0x01 << ( (i) % BITBYTE ) )
+#define GETBIT(x,i) ( (GETBYTE(x,i) >> ( (i) % BITBYTE )) & 0x01 )
+#define HASHVAL(val) (((unsigned int)(val)) % SIGLENBIT)
+#define HASH(sign, val) SETBIT((sign), HASHVAL(val))
+
+typedef struct
+{
+       int32           vl_len_;                /* varlena header (do not touch directly!) */
+       int32           flag;
+       char            data[1];
+} GISTTYPE;
+
+#define ALLISTRUE              0x04
+
+#define ISALLTRUE(x)   ( ((GISTTYPE*)x)->flag & ALLISTRUE )
+
+#define GTHDRSIZE              (VARHDRSZ + sizeof(int32))
+#define CALCGTSIZE(flag) ( GTHDRSIZE+(((flag) & ALLISTRUE) ? 0 : SIGLEN) )
+
+#define GETSIGN(x)             ( (BITVECP)( (char*)x+GTHDRSIZE ) )
+
+#define SUMBIT(val) (          \
+       GETBITBYTE((val),0) + \
+       GETBITBYTE((val),1) + \
+       GETBITBYTE((val),2) + \
+       GETBITBYTE((val),3) + \
+       GETBITBYTE((val),4) + \
+       GETBITBYTE((val),5) + \
+       GETBITBYTE((val),6) + \
+       GETBITBYTE((val),7)   \
+)
+
+#define GETENTRY(vec,pos) ((GISTTYPE *) DatumGetPointer((vec)->vector[(pos)].key))
+
+#define WISH_F(a,b,c) (double)( -(double)(((a)-(b))*((a)-(b))*((a)-(b)))*(c) )
+
+PG_FUNCTION_INFO_V1(ghstore_in);
+Datum          ghstore_in(PG_FUNCTION_ARGS);
+
+PG_FUNCTION_INFO_V1(ghstore_out);
+Datum          ghstore_out(PG_FUNCTION_ARGS);
+
+
+Datum
+ghstore_in(PG_FUNCTION_ARGS)
+{
+       elog(ERROR, "Not implemented");
+       PG_RETURN_DATUM(0);
+}
+
+Datum
+ghstore_out(PG_FUNCTION_ARGS)
+{
+       elog(ERROR, "Not implemented");
+       PG_RETURN_DATUM(0);
+}
+
+PG_FUNCTION_INFO_V1(ghstore_consistent);
+PG_FUNCTION_INFO_V1(ghstore_compress);
+PG_FUNCTION_INFO_V1(ghstore_decompress);
+PG_FUNCTION_INFO_V1(ghstore_penalty);
+PG_FUNCTION_INFO_V1(ghstore_picksplit);
+PG_FUNCTION_INFO_V1(ghstore_union);
+PG_FUNCTION_INFO_V1(ghstore_same);
+
+Datum          ghstore_consistent(PG_FUNCTION_ARGS);
+Datum          ghstore_compress(PG_FUNCTION_ARGS);
+Datum          ghstore_decompress(PG_FUNCTION_ARGS);
+Datum          ghstore_penalty(PG_FUNCTION_ARGS);
+Datum          ghstore_picksplit(PG_FUNCTION_ARGS);
+Datum          ghstore_union(PG_FUNCTION_ARGS);
+Datum          ghstore_same(PG_FUNCTION_ARGS);
+
+static int
+crc32_HStoreValue(HStoreValue *v, uint32 r)
+{
+       int             crc;
+       char    flag = '\0';
+
+       INIT_CRC32(crc);
+
+       switch(r)
+       {
+               case WHS_KEY:
+                       flag = KEYFLAG;
+                       break;
+               case WHS_VALUE:
+                       flag = VALFLAG;
+                       break;
+               case WHS_ELEM:
+                       flag = ELEMFLAG;
+                       break;
+               default:
+                       break;
+       }
+
+       COMP_CRC32(crc, &flag, 1);
+
+       switch(v->type)
+       {
+               case hsvString:
+                       COMP_CRC32(crc, v->string.val, v->string.len);
+                       break;
+               case hsvBool:
+                       flag = (v->boolean) ? 't' : 'f';
+                       COMP_CRC32(crc, &flag, 1);
+                       break;
+               case hsvNumeric:
+                       crc = DatumGetInt32(DirectFunctionCall1(hash_numeric,
+                                                               NumericGetDatum(v->numeric)));
+                       break;
+               default:
+                       elog(PANIC, "impossible value %d", v->type);
+       }
+
+       FIN_CRC32(crc);
+       return crc;
+}
+
+static int
+crc32_Key(char *buf, int sz)
+{
+       int     crc;
+       char    flag = KEYFLAG;
+
+       INIT_CRC32(crc);
+
+       COMP_CRC32(crc, &flag, 1);
+       COMP_CRC32(crc, buf, sz);
+
+       FIN_CRC32(crc);
+       return crc;
+}
+
+Datum
+ghstore_compress(PG_FUNCTION_ARGS)
+{
+       GISTENTRY  *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
+       GISTENTRY  *retval = entry;
+
+       if (entry->leafkey)
+       {
+               GISTTYPE                *res = (GISTTYPE *) palloc0(CALCGTSIZE(0));
+               HStore                  *val = DatumGetHStoreP(entry->key);
+
+               SET_VARSIZE(res, CALCGTSIZE(0));
+
+               if (!HS_ISEMPTY(val))
+               {
+                       int                             r;
+                       HStoreIterator  *it = HStoreIteratorInit(VARDATA(val));
+                       HStoreValue             v;
+
+                       while((r = HStoreIteratorGet(&it, &v, false)) != 0)
+                       {
+                               if ((r == WHS_ELEM || r == WHS_KEY || r == WHS_VALUE) &&
+                                       v.type != hsvNull)
+                               {
+                                       int   h = crc32_HStoreValue(&v, r);
+
+                                       HASH(GETSIGN(res), h);
+                               }
+                       }
+               }
+
+               retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
+               gistentryinit(*retval, PointerGetDatum(res),
+                                         entry->rel, entry->page,
+                                         entry->offset,
+                                         FALSE);
+       }
+       else if (!ISALLTRUE(DatumGetPointer(entry->key)))
+       {
+               int32           i;
+               GISTTYPE   *res;
+               BITVECP         sign = GETSIGN(DatumGetPointer(entry->key));
+
+               LOOPBYTE
+               {
+                       if ((sign[i] & 0xff) != 0xff)
+                               PG_RETURN_POINTER(retval);
+               }
+
+               res = (GISTTYPE *) palloc(CALCGTSIZE(ALLISTRUE));
+               SET_VARSIZE(res, CALCGTSIZE(ALLISTRUE));
+               res->flag = ALLISTRUE;
+
+               retval = (GISTENTRY *) palloc(sizeof(GISTENTRY));
+               gistentryinit(*retval, PointerGetDatum(res),
+                                         entry->rel, entry->page,
+                                         entry->offset,
+                                         FALSE);
+       }
+
+       PG_RETURN_POINTER(retval);
+}
+
+/*
+ * Since type ghstore isn't toastable (and doesn't need to be),
+ * this function can be a no-op.
+ */
+Datum
+ghstore_decompress(PG_FUNCTION_ARGS)
+{
+       PG_RETURN_POINTER(PG_GETARG_POINTER(0));
+}
+
+Datum
+ghstore_same(PG_FUNCTION_ARGS)
+{
+       GISTTYPE   *a = (GISTTYPE *) PG_GETARG_POINTER(0);
+       GISTTYPE   *b = (GISTTYPE *) PG_GETARG_POINTER(1);
+       bool       *result = (bool *) PG_GETARG_POINTER(2);
+
+       if (ISALLTRUE(a) && ISALLTRUE(b))
+               *result = true;
+       else if (ISALLTRUE(a))
+               *result = false;
+       else if (ISALLTRUE(b))
+               *result = false;
+       else
+       {
+               int32           i;
+               BITVECP         sa = GETSIGN(a),
+                                       sb = GETSIGN(b);
+
+               *result = true;
+               LOOPBYTE
+               {
+                       if (sa[i] != sb[i])
+                       {
+                               *result = false;
+                               break;
+                       }
+               }
+       }
+       PG_RETURN_POINTER(result);
+}
+
+static int32
+sizebitvec(BITVECP sign)
+{
+       int32           size = 0,
+                               i;
+
+       LOOPBYTE
+       {
+               size += SUMBIT(sign);
+               sign = (BITVECP) (((char *) sign) + 1);
+       }
+       return size;
+}
+
+static int
+hemdistsign(BITVECP a, BITVECP b)
+{
+       int                     i,
+                               dist = 0;
+
+       LOOPBIT
+       {
+               if (GETBIT(a, i) != GETBIT(b, i))
+                       dist++;
+       }
+       return dist;
+}
+
+static int
+hemdist(GISTTYPE *a, GISTTYPE *b)
+{
+       if (ISALLTRUE(a))
+       {
+               if (ISALLTRUE(b))
+                       return 0;
+               else
+                       return SIGLENBIT - sizebitvec(GETSIGN(b));
+       }
+       else if (ISALLTRUE(b))
+               return SIGLENBIT - sizebitvec(GETSIGN(a));
+
+       return hemdistsign(GETSIGN(a), GETSIGN(b));
+}
+
+static int32
+unionkey(BITVECP sbase, GISTTYPE *add)
+{
+       int32           i;
+       BITVECP         sadd = GETSIGN(add);
+
+       if (ISALLTRUE(add))
+               return 1;
+       LOOPBYTE
+               sbase[i] |= sadd[i];
+       return 0;
+}
+
+Datum
+ghstore_union(PG_FUNCTION_ARGS)
+{
+       GistEntryVector *entryvec = (GistEntryVector *) PG_GETARG_POINTER(0);
+       int32           len = entryvec->n;
+
+       int                *size = (int *) PG_GETARG_POINTER(1);
+       BITVEC          base;
+       int32           i;
+       int32           flag = 0;
+       GISTTYPE   *result;
+
+       MemSet((void *) base, 0, sizeof(BITVEC));
+       for (i = 0; i < len; i++)
+       {
+               if (unionkey(base, GETENTRY(entryvec, i)))
+               {
+                       flag = ALLISTRUE;
+                       break;
+               }
+       }
+
+       len = CALCGTSIZE(flag);
+       result = (GISTTYPE *) palloc(len);
+       SET_VARSIZE(result, len);
+       result->flag = flag;
+       if (!ISALLTRUE(result))
+               memcpy((void *) GETSIGN(result), (void *) base, sizeof(BITVEC));
+       *size = len;
+
+       PG_RETURN_POINTER(result);
+}
+
+Datum
+ghstore_penalty(PG_FUNCTION_ARGS)
+{
+       GISTENTRY  *origentry = (GISTENTRY *) PG_GETARG_POINTER(0); /* always ISSIGNKEY */
+       GISTENTRY  *newentry = (GISTENTRY *) PG_GETARG_POINTER(1);
+       float      *penalty = (float *) PG_GETARG_POINTER(2);
+       GISTTYPE   *origval = (GISTTYPE *) DatumGetPointer(origentry->key);
+       GISTTYPE   *newval = (GISTTYPE *) DatumGetPointer(newentry->key);
+
+       *penalty = hemdist(origval, newval);
+       PG_RETURN_POINTER(penalty);
+}
+
+
+typedef struct
+{
+       OffsetNumber pos;
+       int32           cost;
+} SPLITCOST;
+
+static int
+comparecost(const void *a, const void *b)
+{
+       return ((const SPLITCOST *) a)->cost - ((const SPLITCOST *) b)->cost;
+}
+
+
+Datum
+ghstore_picksplit(PG_FUNCTION_ARGS)
+{
+       GistEntryVector *entryvec = (GistEntryVector *) PG_GETARG_POINTER(0);
+       OffsetNumber maxoff = entryvec->n - 2;
+
+       GIST_SPLITVEC *v = (GIST_SPLITVEC *) PG_GETARG_POINTER(1);
+       OffsetNumber k,
+                               j;
+       GISTTYPE   *datum_l,
+                          *datum_r;
+       BITVECP         union_l,
+                               union_r;
+       int32           size_alpha,
+                               size_beta;
+       int32           size_waste,
+                               waste = -1;
+       int32           nbytes;
+       OffsetNumber seed_1 = 0,
+                               seed_2 = 0;
+       OffsetNumber *left,
+                          *right;
+       BITVECP         ptr;
+       int                     i;
+       SPLITCOST  *costvector;
+       GISTTYPE   *_k,
+                          *_j;
+
+       nbytes = (maxoff + 2) * sizeof(OffsetNumber);
+       v->spl_left = (OffsetNumber *) palloc(nbytes);
+       v->spl_right = (OffsetNumber *) palloc(nbytes);
+
+       for (k = FirstOffsetNumber; k < maxoff; k = OffsetNumberNext(k))
+       {
+               _k = GETENTRY(entryvec, k);
+               for (j = OffsetNumberNext(k); j <= maxoff; j = OffsetNumberNext(j))
+               {
+                       size_waste = hemdist(_k, GETENTRY(entryvec, j));
+                       if (size_waste > waste)
+                       {
+                               waste = size_waste;
+                               seed_1 = k;
+                               seed_2 = j;
+                       }
+               }
+       }
+
+       left = v->spl_left;
+       v->spl_nleft = 0;
+       right = v->spl_right;
+       v->spl_nright = 0;
+
+       if (seed_1 == 0 || seed_2 == 0)
+       {
+               seed_1 = 1;
+               seed_2 = 2;
+       }
+
+       /* form initial .. */
+       if (ISALLTRUE(GETENTRY(entryvec, seed_1)))
+       {
+               datum_l = (GISTTYPE *) palloc(GTHDRSIZE);
+               SET_VARSIZE(datum_l, GTHDRSIZE);
+               datum_l->flag = ALLISTRUE;
+       }
+       else
+       {
+               datum_l = (GISTTYPE *) palloc(GTHDRSIZE + SIGLEN);
+               SET_VARSIZE(datum_l, GTHDRSIZE + SIGLEN);
+               datum_l->flag = 0;
+               memcpy((void *) GETSIGN(datum_l),
+                          (void *) GETSIGN(GETENTRY(entryvec, seed_1)), sizeof(BITVEC))
+                       ;
+       }
+       if (ISALLTRUE(GETENTRY(entryvec, seed_2)))
+       {
+               datum_r = (GISTTYPE *) palloc(GTHDRSIZE);
+               SET_VARSIZE(datum_r, GTHDRSIZE);
+               datum_r->flag = ALLISTRUE;
+       }
+       else
+       {
+               datum_r = (GISTTYPE *) palloc(GTHDRSIZE + SIGLEN);
+               SET_VARSIZE(datum_r, GTHDRSIZE + SIGLEN);
+               datum_r->flag = 0;
+               memcpy((void *) GETSIGN(datum_r),
+                          (void *) GETSIGN(GETENTRY(entryvec, seed_2)), sizeof(BITVEC));
+       }
+
+       maxoff = OffsetNumberNext(maxoff);
+       /* sort before ... */
+       costvector = (SPLITCOST *) palloc(sizeof(SPLITCOST) * maxoff);
+       for (j = FirstOffsetNumber; j <= maxoff; j = OffsetNumberNext(j))
+       {
+               costvector[j - 1].pos = j;
+               _j = GETENTRY(entryvec, j);
+               size_alpha = hemdist(datum_l, _j);
+               size_beta = hemdist(datum_r, _j);
+               costvector[j - 1].cost = abs(size_alpha - size_beta);
+       }
+       qsort((void *) costvector, maxoff, sizeof(SPLITCOST), comparecost);
+
+       union_l = GETSIGN(datum_l);
+       union_r = GETSIGN(datum_r);
+
+       for (k = 0; k < maxoff; k++)
+       {
+               j = costvector[k].pos;
+               if (j == seed_1)
+               {
+                       *left++ = j;
+                       v->spl_nleft++;
+                       continue;
+               }
+               else if (j == seed_2)
+               {
+                       *right++ = j;
+                       v->spl_nright++;
+                       continue;
+               }
+               _j = GETENTRY(entryvec, j);
+               size_alpha = hemdist(datum_l, _j);
+               size_beta = hemdist(datum_r, _j);
+
+               if (size_alpha < size_beta + WISH_F(v->spl_nleft, v->spl_nright, 0.0001))
+               {
+                       if (ISALLTRUE(datum_l) || ISALLTRUE(_j))
+                       {
+                               if (!ISALLTRUE(datum_l))
+                                       MemSet((void *) union_l, 0xff, sizeof(BITVEC));
+                       }
+                       else
+                       {
+                               ptr = GETSIGN(_j);
+                               LOOPBYTE
+                                       union_l[i] |= ptr[i];
+                       }
+                       *left++ = j;
+                       v->spl_nleft++;
+               }
+               else
+               {
+                       if (ISALLTRUE(datum_r) || ISALLTRUE(_j))
+                       {
+                               if (!ISALLTRUE(datum_r))
+                                       MemSet((void *) union_r, 0xff, sizeof(BITVEC));
+                       }
+                       else
+                       {
+                               ptr = GETSIGN(_j);
+                               LOOPBYTE
+                                       union_r[i] |= ptr[i];
+                       }
+                       *right++ = j;
+                       v->spl_nright++;
+               }
+       }
+
+       *right = *left = FirstOffsetNumber;
+
+       v->spl_ldatum = PointerGetDatum(datum_l);
+       v->spl_rdatum = PointerGetDatum(datum_r);
+
+       PG_RETURN_POINTER(v);
+}
+
+Datum
+ghstore_consistent(PG_FUNCTION_ARGS)
+{
+       GISTTYPE   *entry = (GISTTYPE *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(0))->key);
+       StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2);
+
+       /* Oid          subtype = PG_GETARG_OID(3); */
+       bool       *recheck = (bool *) PG_GETARG_POINTER(4);
+       bool            res = true;
+       BITVECP         sign;
+
+       /* All cases served by this function are inexact */
+       *recheck = true;
+
+       if (ISALLTRUE(entry))
+               PG_RETURN_BOOL(true);
+
+       sign = GETSIGN(entry);
+
+       if (strategy == HStoreContainsStrategyNumber ||
+               strategy == HStoreOldContainsStrategyNumber)
+       {
+               BITVECP         qe;
+               int                     i;
+
+               qe = fcinfo->flinfo->fn_extra;
+               if (qe == NULL)
+               {
+                       HStore                  *query = PG_GETARG_HS(1);
+
+                       qe = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt, sizeof(BITVEC));
+                       memset(qe, 0, sizeof(BITVEC));
+
+                       if (!HS_ISEMPTY(query))
+                       {
+                               int                             r;
+                               HStoreIterator  *it = HStoreIteratorInit(VARDATA(query));
+                               HStoreValue             v;
+
+                               while((r = HStoreIteratorGet(&it, &v, false)) != 0)
+                               {
+                                       if ((r == WHS_ELEM || r == WHS_KEY || r == WHS_VALUE) && v.type != hsvNull)
+                                       {
+                                               int   crc = crc32_HStoreValue(&v, r);
+
+                                               HASH(qe, crc);
+                                       }
+                               }
+                       }
+
+                       fcinfo->flinfo->fn_extra = qe;
+               }
+
+               LOOPBYTE
+               {
+                       if ((sign[i] & qe[i]) != qe[i])
+                       {
+                               res = false;
+                               break;
+                       }
+               }
+       }
+       else if (strategy == HStoreExistsStrategyNumber)
+       {
+               int     *qval;
+
+               qval = fcinfo->flinfo->fn_extra;
+               if (qval == NULL)
+               {
+                       text       *query = PG_GETARG_TEXT_PP(1);
+                       int                     crc = crc32_Key(VARDATA_ANY(query), VARSIZE_ANY_EXHDR(query));
+
+                       qval = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt, sizeof(*qval));
+                       *qval = HASHVAL(crc);
+
+                       fcinfo->flinfo->fn_extra = qval;
+               }
+
+               res = (GETBIT(sign, *qval)) ? true : false;
+       }
+       else if (strategy == HStoreExistsAllStrategyNumber ||
+                        strategy == HStoreExistsAnyStrategyNumber)
+       {
+               BITVECP arrentry;
+               int             i;
+
+               arrentry = fcinfo->flinfo->fn_extra;
+               if (arrentry == NULL)
+               {
+                       ArrayType  *query = PG_GETARG_ARRAYTYPE_P(1);
+                       Datum      *key_datums;
+                       bool       *key_nulls;
+                       int                     key_count;
+
+                       arrentry = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
+                                                                                 sizeof(BITVEC));
+                       memset(arrentry, 0, sizeof(BITVEC));
+
+                       deconstruct_array(query,
+                                                         TEXTOID, -1, false, 'i',
+                                                         &key_datums, &key_nulls, &key_count);
+
+                       for (i = 0; i < key_count; ++i)
+                       {
+                               int                     crc;
+
+                               if (key_nulls[i])
+                                       continue;
+                               crc = crc32_Key(VARDATA(key_datums[i]),
+                                                               VARSIZE(key_datums[i]) - VARHDRSZ);
+                               HASH(arrentry, crc);
+                       }
+
+                       fcinfo->flinfo->fn_extra = arrentry;
+               }
+
+               if (strategy == HStoreExistsAllStrategyNumber)
+               {
+                       LOOPBYTE
+                       {
+                               if ((sign[i] & arrentry[i]) != arrentry[i])
+                               {
+                                       res = false;
+                                       break;
+                               }
+                       }
+               }
+               else /* HStoreExistsAnyStrategyNumber */
+               {
+                       res = false;
+
+                       LOOPBYTE
+                       {
+                               if (sign[i] & arrentry[i])
+                               {
+                                       res = true;
+                                       break;
+                               }
+                       }
+               }
+       }
+       else
+               elog(ERROR, "Unsupported strategy number: %d", strategy);
+
+       PG_RETURN_BOOL(res);
+}
diff --git a/hstore_gram.y b/hstore_gram.y
new file mode 100644 (file)
index 0000000..8db2f60
--- /dev/null
@@ -0,0 +1,315 @@
+%{
+#define YYPARSE_PARAM result  /* need this to pass a pointer (void *) to yyparse */
+
+#include "postgres.h"
+
+#include "fmgr.h"
+#include "utils/builtins.h"
+#include "hstore.h"
+
+/*
+ * Bison doesn't allocate anything that needs to live across parser calls,
+ * so we can easily have it use palloc instead of malloc.  This prevents
+ * memory leaks if we error out during parsing.  Note this only works with
+ * bison >= 2.0.  However, in bison 1.875 the default is to use alloca()
+ * if possible, so there's not really much problem anyhow, at least if
+ * you're building with gcc.
+ */
+#define YYMALLOC palloc
+#define YYFREE   pfree
+
+/* Avoid exit() on fatal scanner errors (a bit ugly -- see yy_fatal_error) */
+#undef fprintf
+#define fprintf(file, fmt, msg)  fprintf_to_ereport(fmt, msg)
+
+static void
+fprintf_to_ereport(const char *fmt, const char *msg)
+{
+       ereport(ERROR, (errmsg_internal("%s", msg)));
+}
+
+/* struct string is shared between scan and gram */
+typedef struct string {
+       char    *val;
+       int     len;
+       int             total;
+} string;
+#include <hstore_gram.h>
+
+/* flex 2.5.4 doesn't bother with a decl for this */
+int hstore_yylex(YYSTYPE * yylval_param);
+int hstore_yyparse(void *result);
+void hstore_yyerror(const char *message);
+
+static HStoreValue*
+makeHStoreValueString(HStoreValue* v, string *s)
+{
+       if (v == NULL)
+               v = palloc(sizeof(*v));
+
+       if (s == NULL)
+       {
+               v->type = hsvNull;
+               v->size = sizeof(HEntry);
+       }
+       else if (s->len > HENTRY_POSMASK)
+       {
+               elog(ERROR, "string is too long");
+       }
+       else
+       {
+               v->type = hsvString;
+               v->string.val = s->val;
+               v->string.len = s->len;
+               v->size = sizeof(HEntry) + s->len;
+
+       }
+
+       return v;
+}
+
+static HStoreValue*
+makeHStoreValueNumeric(string *s)
+{
+       Numeric                 n = NULL;
+       HStoreValue             *v;
+       MemoryContext   ccxt = CurrentMemoryContext;
+
+       /*
+        * ignore ERRCODE_INVALID_TEXT_REPRESENTATION in parse: our
+        * test stringIsNumber could be not agree with numeric_in
+        */
+
+       PG_TRY();
+       {
+               n = DatumGetNumeric(DirectFunctionCall3(numeric_in, CStringGetDatum(s->val), 0, -1));
+       }
+       PG_CATCH();
+       {
+               ErrorData               *errdata;
+               MemoryContext   ecxt;
+
+               ecxt = MemoryContextSwitchTo(ccxt);
+               errdata = CopyErrorData();
+               if (errdata->sqlerrcode == ERRCODE_INVALID_TEXT_REPRESENTATION)
+               {
+                       FlushErrorState();
+                       n = NULL;
+               }
+               else
+               {
+                       MemoryContextSwitchTo(ecxt);
+                       PG_RE_THROW();
+               }
+       }
+       PG_END_TRY();
+
+       if (n != NULL)
+       {
+               v = palloc(sizeof(*v));
+               v->type = hsvNumeric;
+               v->numeric = n;
+               v->size = 2*sizeof(HEntry) + VARSIZE_ANY(n);
+       }
+       else
+       {
+               v = makeHStoreValueString(NULL, s);
+       }
+
+       return v;
+}
+
+static HStoreValue*
+makeHStoreValueBool(bool val) {
+       HStoreValue *v = palloc(sizeof(*v));
+
+       v->type = hsvBool;
+       v->boolean = val;
+       v->size = sizeof(HEntry);
+
+       return v;
+}
+
+static HStoreValue*
+makeHStoreValueArray(List *list)
+{
+       HStoreValue     *v = palloc(sizeof(*v));
+
+       v->type = hsvArray;
+       v->array.scalar = false;
+       v->array.nelems = list_length(list);
+       v->size = sizeof(uint32) /* header */ + sizeof(HEntry) /* parent's entry */ + sizeof(HEntry) - 1 /*alignment*/;
+
+       if (v->array.nelems > 0)
+       {
+               ListCell        *cell;
+               int                     i = 0;
+
+               v->array.elems = palloc(sizeof(HStoreValue) * v->array.nelems);
+
+               foreach(cell, list)
+               {
+                       HStoreValue     *s = (HStoreValue*)lfirst(cell);
+
+                       v->size += s->size; 
+
+                       v->array.elems[i++] = *s;
+
+                       if (v->size > HENTRY_POSMASK)
+                               elog(ERROR, "array is too long");
+               }
+       }
+       else
+       {
+               v->array.elems = NULL;
+       }
+
+       return v;
+}
+
+static HStoreValue*
+makeHStoreValuePairs(List *list)
+{
+       HStoreValue     *v = palloc(sizeof(*v));
+
+       v->type = hsvHash;
+       v->hash.npairs = list_length(list);
+       v->size = sizeof(uint32) /* header */ + sizeof(HEntry) /* parent's entry */ + sizeof(HEntry) - 1 /*alignment*/;
+
+       if (v->hash.npairs > 0)
+       {
+               ListCell        *cell;
+               int                     i = 0;
+
+               v->hash.pairs = palloc(sizeof(HStorePair) * v->hash.npairs);
+
+               foreach(cell, list)
+               {
+                       HStorePair      *s = (HStorePair*)lfirst(cell);
+
+                       v->size += s->key.size + s->value.size; 
+                       v->hash.pairs[i].order = i;
+                       v->hash.pairs[i++] = *s;
+
+                       if (v->size > HENTRY_POSMASK)
+                               elog(ERROR, "hstore is too long");
+               }
+
+               uniqueHStoreValue(v);
+       }
+       else
+       {
+               v->hash.pairs = NULL;
+       }
+
+       return v;
+}
+
+static HStorePair*
+makeHStorePair(string *key, HStoreValue *value) {
+       HStorePair      *v = palloc(sizeof(*v));
+
+       makeHStoreValueString(&v->key, key);
+       v->value = *value;
+
+       return v;
+}
+
+%}
+
+/* BISON Declarations */
+%pure-parser
+%expect 0
+%name-prefix="hstore_yy"
+%error-verbose
+
+%union {
+       string                  str;
+       Numeric                 numeric;
+       List                    *elems;                 /* list of HStoreValue */
+       List                    *pairs;                 /* list of HStorePair */
+
+       HStoreValue             *hvalue;
+       HStorePair              *pair;
+}
+
+%token <str>                   DELIMITER_P NULL_P STRING_P TRUE_P FALSE_P
+                                               NUMERIC_P
+
+%type  <hvalue>                result hstore value scalar_value 
+%type  <str>                   key
+
+%type  <pair>                  pair
+
+%type  <elems>                 value_list
+%type  <pairs>                 pair_list
+
+/* Grammar follows */
+%%
+
+result: 
+       pair_list                                               { *((HStoreValue**)result) = makeHStoreValuePairs($1); }
+       | hstore                                                {       
+                                                                               if ($1->type == hsvNull)
+                                                                                       *((HStoreValue**)result) = NULL;
+                                                                               else
+                                                                                       *((HStoreValue**)result) = $1;
+                                                                       }
+       | scalar_value                                  { 
+                                                                               *((HStoreValue**)result) = makeHStoreValueArray(lappend(NIL, $1));
+                                                                               (*((HStoreValue**)result))->array.scalar = true;
+                                                                       }
+       | /* EMPTY */                                   { *((HStoreValue**)result) = NULL; }
+       ;
+
+hstore:
+       '{' pair_list '}'                               { $$ = makeHStoreValuePairs($2); }
+       | '{' value_list '}'                    { $$ = makeHStoreValueArray($2); }
+       | '[' value_list ']'                    { $$ = makeHStoreValueArray($2); }
+       | '{' value '}'                                 { $$ = makeHStoreValueArray(lappend(NIL, $2)); }
+       | '[' value ']'                                 { $$ = makeHStoreValueArray(lappend(NIL, $2)); }
+       | '{' '}'                                               { $$ = makeHStoreValueString(NULL, NULL); }
+       | '[' ']'                                               { $$ = makeHStoreValueString(NULL, NULL); }
+       ;
+
+scalar_value:
+       NULL_P                                                  { $$ = makeHStoreValueString(NULL, NULL); }
+       | STRING_P                                              { $$ = makeHStoreValueString(NULL, &$1); }
+       | TRUE_P                                                { $$ = makeHStoreValueBool(true); }
+       | FALSE_P                                               { $$ = makeHStoreValueBool(false); }
+       | NUMERIC_P                                             { $$ = makeHStoreValueNumeric(&$1); }
+       ;
+
+value:
+       scalar_value                                    { $$ = $1; }
+       | hstore                                                { $$ = $1; } 
+       ;
+
+value_list:
+       value ',' value                                 { $$ = lappend(lappend(NIL, $1), $3); } 
+       | value_list ',' value                  { $$ = lappend($1, $3); } 
+       ;
+
+/*
+ * key is always a string, not a bool or numeric
+ */
+key:
+       STRING_P                                                { $$ = $1; }
+       | TRUE_P                                                { $$ = $1; }
+       | FALSE_P                                               { $$ = $1; }
+       | NUMERIC_P                                             { $$ = $1; }
+       | NULL_P                                                { $$ = $1; }
+       ;
+
+pair:
+       key DELIMITER_P value                   { $$ = makeHStorePair(&$1, $3); }
+       ;
+
+pair_list:
+       pair                                                    { $$ = lappend(NIL, $1); }
+       | pair_list ',' pair                    { $$ = lappend($1, $3); }
+       ;
+
+%%
+
+#include "hstore_scan.c"
diff --git a/hstore_io.c b/hstore_io.c
new file mode 100644 (file)
index 0000000..63ffcda
--- /dev/null
@@ -0,0 +1,1906 @@
+/*
+ * contrib/hstore/hstore_io.c
+ */
+#include "postgres.h"
+
+#include <ctype.h>
+
+#include "access/htup_details.h"
+#include "catalog/pg_type.h"
+#include "catalog/pg_cast.h"
+#include "funcapi.h"
+#include "libpq/pqformat.h"
+#include "miscadmin.h"
+#include "parser/parse_coerce.h"
+#include "utils/builtins.h"
+#include "utils/fmgroids.h"
+#include "utils/json.h"
+#include "utils/guc.h"
+#include "utils/lsyscache.h"
+#include "utils/memutils.h"
+#include "utils/syscache.h"
+#include "utils/typcache.h"
+
+#include "hstore.h"
+
+PG_MODULE_MAGIC;
+
+/* old names for C functions */
+HSTORE_POLLUTE(hstore_from_text, tconvert);
+
+/* GUC variables */
+static bool    pretty_print_var = false;
+#define SET_PRETTY_PRINT_VAR(x)                ((pretty_print_var) ? \
+                                                                        ((x) | PrettyPrint) : (x))
+
+static void recvHStore(StringInfo buf, HStoreValue *v, uint32 level,
+                                          uint32 header);
+static Oid searchCast(Oid src, Oid dst, CoercionMethod *method);
+
+static size_t
+hstoreCheckKeyLen(size_t len)
+{
+       if (len > HSTORE_MAX_KEY_LEN)
+               ereport(ERROR,
+                               (errcode(ERRCODE_STRING_DATA_RIGHT_TRUNCATION),
+                                errmsg("string too long for hstore key")));
+       return len;
+}
+
+static size_t
+hstoreCheckValLen(size_t len)
+{
+       if (len > HSTORE_MAX_VALUE_LEN)
+               ereport(ERROR,
+                               (errcode(ERRCODE_STRING_DATA_RIGHT_TRUNCATION),
+                                errmsg("string too long for hstore value")));
+       return len;
+}
+
+
+static HStore*
+hstoreDump(HStoreValue *p)
+{
+       uint32                  buflen;
+       HStore             *out;
+
+       if (p == NULL || (p->type == hsvArray && p->array.nelems == 0) ||
+               (p->type == hsvHash && p->hash.npairs == 0))
+       {
+               buflen = 0;
+               out = palloc(VARHDRSZ);
+       }
+       else
+       {
+               buflen = VARHDRSZ + p->size;
+               out = palloc(buflen);
+               SET_VARSIZE(out, buflen);
+
+               buflen = compressHStore(p, VARDATA(out));
+       }
+       SET_VARSIZE(out, buflen + VARHDRSZ);
+
+       return out;
+}
+
+PG_FUNCTION_INFO_V1(hstore_in);
+Datum          hstore_in(PG_FUNCTION_ARGS);
+Datum
+hstore_in(PG_FUNCTION_ARGS)
+{
+       PG_RETURN_POINTER(hstoreDump(parseHStore(PG_GETARG_CSTRING(0), -1, false)));
+}
+
+static void
+recvHStoreValue(StringInfo buf, HStoreValue *v, uint32 level, int c)
+{
+       uint32  hentry = c & HENTRY_TYPEMASK;
+
+       check_stack_depth();
+
+       if (c == -1 /* compatibility */ || hentry == HENTRY_ISNULL)
+       {
+               v->type = hsvNull;
+               v->size = sizeof(HEntry);
+       }
+       else if (hentry == HENTRY_ISHASH || hentry == HENTRY_ISARRAY ||
+                        hentry == HENTRY_ISSCALAR)
+       {
+               recvHStore(buf, v, level + 1, (uint32)c);
+       }
+       else if (hentry == HENTRY_ISFALSE || hentry == HENTRY_ISTRUE)
+       {
+               v->type = hsvBool;
+               v->size = sizeof(HEntry);
+               v->boolean = (hentry == HENTRY_ISFALSE) ? false : true;
+       }
+       else if (hentry == HENTRY_ISNUMERIC)
+       {
+               v->type = hsvNumeric;
+               v->numeric = DatumGetNumeric(DirectFunctionCall3(numeric_recv,
+                                                                                                                PointerGetDatum(buf),
+                                                                                                                Int32GetDatum(0),
+                                                                                                                Int32GetDatum(-1)));
+               v->size = sizeof(HEntry) * 2 + VARSIZE_ANY(v->numeric);
+       }
+       else if (hentry == HENTRY_ISSTRING)
+       {
+               v->type = hsvString;
+               v->string.val = pq_getmsgtext(buf, c & ~HENTRY_TYPEMASK, &c);
+               v->string.len = hstoreCheckKeyLen(c);
+               v->size = sizeof(HEntry) + v->string.len;
+       }
+       else
+       {
+               ereport(ERROR,
+                               (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
+                                errmsg("unknown hstore value")));
+       }
+}
+
+static void
+recvHStore(StringInfo buf, HStoreValue *v, uint32 level, uint32 header)
+{
+       uint32  hentry;
+       uint32  i;
+
+       hentry = header & HENTRY_TYPEMASK;
+
+       if (level == 0 && hentry == 0)
+               hentry = HENTRY_ISHASH; /* old version */
+
+       check_stack_depth();
+
+       v->size = 3 * sizeof(HEntry);
+       if (hentry == HENTRY_ISHASH)
+       {
+               v->type = hsvHash;
+               v->hash.npairs = header & HS_COUNT_MASK;
+
+               if (v->hash.npairs > (buf->len  - buf->cursor) / (2 * sizeof(uint32)) ||
+                       v->hash.npairs > MaxAllocSize / sizeof(HStorePair))
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
+                                        errmsg("too much elements in hstore hash")));
+
+               if (v->hash.npairs > 0)
+               {
+                       v->hash.pairs = palloc(sizeof(*v->hash.pairs) * v->hash.npairs);
+
+                       for(i=0; i<v->hash.npairs; i++)
+                       {
+                               recvHStoreValue(buf, &v->hash.pairs[i].key, level,
+                                                               pq_getmsgint(buf, 4));
+                               if (v->hash.pairs[i].key.type != hsvString)
+                                       ereport(ERROR,
+                                                       (errcode(ERRCODE_DATATYPE_MISMATCH),
+                                                        errmsg("hstore's key could be only a string")));
+
+                               recvHStoreValue(buf, &v->hash.pairs[i].value, level,
+                                                               pq_getmsgint(buf, 4));
+
+                               v->size += v->hash.pairs[i].key.size +
+                                                       v->hash.pairs[i].value.size;
+                       }
+
+                       uniqueHStoreValue(v);
+               }
+       }
+       else if (hentry == HENTRY_ISARRAY || hentry == HENTRY_ISSCALAR)
+       {
+               v->type = hsvArray;
+               v->array.nelems = header & HS_COUNT_MASK;
+               v->array.scalar = (hentry == HENTRY_ISSCALAR) ? true : false;
+
+               if (v->array.nelems > (buf->len  - buf->cursor) / sizeof(uint32) ||
+                       v->array.nelems > MaxAllocSize / sizeof(HStoreValue))
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
+                                        errmsg("too much elements in hstore array")));
+
+               if (v->array.scalar && v->array.nelems != 1)
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
+                                        errmsg("wrong scalar representation")));
+
+               if (v->array.nelems > 0)
+               {
+                       v->array.elems = palloc(sizeof(*v->array.elems) * v->array.nelems);
+
+                       for(i=0; i<v->array.nelems; i++)
+                       {
+                               recvHStoreValue(buf, v->array.elems + i, level,
+                                                               pq_getmsgint(buf, 4));
+                               v->size += v->array.elems[i].size;
+                       }
+               }
+       }
+       else
+       {
+               ereport(ERROR,
+                               (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
+                                errmsg("unknown hstore element")));
+       }
+}
+
+PG_FUNCTION_INFO_V1(hstore_recv);
+Datum          hstore_recv(PG_FUNCTION_ARGS);
+Datum
+hstore_recv(PG_FUNCTION_ARGS)
+{
+       StringInfo      buf = (StringInfo) PG_GETARG_POINTER(0);
+       HStoreValue     v;
+
+       recvHStore(buf, &v, 0, pq_getmsgint(buf, 4));
+
+       PG_RETURN_POINTER(hstoreDump(&v));
+}
+
+PG_FUNCTION_INFO_V1(hstore_from_text);
+Datum          hstore_from_text(PG_FUNCTION_ARGS);
+Datum
+hstore_from_text(PG_FUNCTION_ARGS)
+{
+       text            *key;
+       HStoreValue     v;
+       HStorePair      pair;
+
+       if (PG_ARGISNULL(0))
+               PG_RETURN_NULL();
+
+       key = PG_GETARG_TEXT_PP(0);
+       pair.key.type = hsvString;
+       pair.key.string.val = VARDATA_ANY(key);
+       pair.key.string.len = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(key));
+       pair.key.size = pair.key.string.len + sizeof(HEntry);
+
+       if (PG_ARGISNULL(1))
+       {
+               pair.value.type = hsvNull;
+               pair.value.size = sizeof(HEntry);
+       }
+       else
+       {
+               text            *val = NULL;
+
+               val = PG_GETARG_TEXT_PP(1);
+               pair.value.type = hsvString;
+               pair.value.string.val = VARDATA_ANY(val);
+               pair.value.string.len = hstoreCheckValLen(VARSIZE_ANY_EXHDR(val));
+               pair.value.size = pair.value.string.len + sizeof(HEntry);
+       }
+
+       v.type = hsvHash;
+       v.size = sizeof(HEntry) + pair.key.size + pair.value.size;
+       v.hash.npairs = 1;
+       v.hash.pairs = &pair;
+
+       PG_RETURN_POINTER(hstoreDump(&v));
+}
+
+PG_FUNCTION_INFO_V1(hstore_from_bool);
+Datum          hstore_from_bool(PG_FUNCTION_ARGS);
+Datum
+hstore_from_bool(PG_FUNCTION_ARGS)
+{
+       text            *key;
+       HStoreValue     v;
+       HStorePair      pair;
+
+       if (PG_ARGISNULL(0))
+               PG_RETURN_NULL();
+
+       key = PG_GETARG_TEXT_PP(0);
+       pair.key.type = hsvString;
+       pair.key.string.val = VARDATA_ANY(key);
+       pair.key.string.len = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(key));
+       pair.key.size = pair.key.string.len + sizeof(HEntry);
+
+       if (PG_ARGISNULL(1))
+       {
+               pair.value.type = hsvNull;
+               pair.value.size = sizeof(HEntry);
+       }
+       else
+       {
+               pair.value.type = hsvBool;
+               pair.value.boolean = PG_GETARG_BOOL(1);
+               pair.value.size = sizeof(HEntry);
+       }
+
+       v.type = hsvHash;
+       v.size = sizeof(HEntry) + pair.key.size + pair.value.size;
+       v.hash.npairs = 1;
+       v.hash.pairs = &pair;
+
+       PG_RETURN_POINTER(hstoreDump(&v));
+}
+
+PG_FUNCTION_INFO_V1(hstore_from_numeric);
+Datum          hstore_from_numeric(PG_FUNCTION_ARGS);
+Datum
+hstore_from_numeric(PG_FUNCTION_ARGS)
+{
+       text            *key;
+       HStoreValue     v;
+       HStorePair      pair;
+
+       if (PG_ARGISNULL(0))
+               PG_RETURN_NULL();
+
+       key = PG_GETARG_TEXT_PP(0);
+       pair.key.type = hsvString;
+       pair.key.string.val = VARDATA_ANY(key);
+       pair.key.string.len = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(key));
+       pair.key.size = pair.key.string.len + sizeof(HEntry);
+
+       if (PG_ARGISNULL(1))
+       {
+               pair.value.type = hsvNull;
+               pair.value.size = sizeof(HEntry);
+       }
+       else
+       {
+               pair.value.type = hsvNumeric;
+               pair.value.numeric = PG_GETARG_NUMERIC(1);
+               pair.value.size = sizeof(HEntry) + sizeof(HEntry) +
+                                                       VARSIZE_ANY(pair.value.numeric);
+       }
+
+       v.type = hsvHash;
+       v.size = sizeof(HEntry) + pair.key.size + pair.value.size;
+       v.hash.npairs = 1;
+       v.hash.pairs = &pair;
+
+       PG_RETURN_POINTER(hstoreDump(&v));
+}
+
+PG_FUNCTION_INFO_V1(hstore_from_th);
+Datum          hstore_from_th(PG_FUNCTION_ARGS);
+Datum
+hstore_from_th(PG_FUNCTION_ARGS)
+{
+       text            *key;
+       HStoreValue     v;
+       HStorePair      pair;
+
+       if (PG_ARGISNULL(0))
+               PG_RETURN_NULL();
+
+       key = PG_GETARG_TEXT_PP(0);
+       pair.key.type = hsvString;
+       pair.key.string.val = VARDATA_ANY(key);
+       pair.key.string.len = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(key));
+       pair.key.size = pair.key.string.len + sizeof(HEntry);
+
+       if (PG_ARGISNULL(1))
+       {
+               pair.value.type = hsvNull;
+               pair.value.size = sizeof(HEntry);
+       }
+       else
+       {
+               HStore          *val = NULL;
+
+               val = PG_GETARG_HS(1);
+               pair.value.type = hsvBinary;
+               pair.value.binary.data = VARDATA_ANY(val);
+               pair.value.binary.len = VARSIZE_ANY_EXHDR(val);
+               pair.value.size = pair.value.binary.len + sizeof(HEntry) * 2;
+       }
+
+       v.type = hsvHash;
+       v.size = sizeof(HEntry) + pair.key.size + pair.value.size;
+       v.hash.npairs = 1;
+       v.hash.pairs = &pair;
+
+       PG_RETURN_POINTER(hstoreDump(&v));
+}
+
+PG_FUNCTION_INFO_V1(hstore_from_arrays);
+PG_FUNCTION_INFO_V1(hstore_scalar_from_text);
+Datum          hstore_scalar_from_text(PG_FUNCTION_ARGS);
+Datum
+hstore_scalar_from_text(PG_FUNCTION_ARGS)
+{
+       HStoreValue     a, v;
+
+       if (PG_ARGISNULL(0))
+       {
+               v.type = hsvNull;
+               v.size = sizeof(HEntry);
+       }
+       else
+       {
+               text    *scalar;
+
+               scalar = PG_GETARG_TEXT_PP(0);
+               v.type = hsvString;
+               v.string.val = VARDATA_ANY(scalar);
+               v.string.len = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(scalar));
+               v.size = v.string.len + sizeof(HEntry);
+       }
+
+       a.type = hsvArray;
+       a.size = sizeof(HEntry) + v.size;
+       a.array.nelems = 1;
+       a.array.elems = &v;
+       a.array.scalar = true;
+
+       PG_RETURN_POINTER(hstoreDump(&a));
+}
+
+PG_FUNCTION_INFO_V1(hstore_scalar_from_bool);
+Datum          hstore_scalar_from_bool(PG_FUNCTION_ARGS);
+Datum
+hstore_scalar_from_bool(PG_FUNCTION_ARGS)
+{
+       HStoreValue     a, v;
+
+       if (PG_ARGISNULL(0))
+       {
+               v.type = hsvNull;
+               v.size = sizeof(HEntry);
+       }
+       else
+       {
+               v.type = hsvBool;
+               v.boolean = PG_GETARG_BOOL(0);
+               v.size = sizeof(HEntry);
+       }
+
+       a.type = hsvArray;
+       a.size = sizeof(HEntry) + v.size;
+       a.array.nelems = 1;
+       a.array.elems = &v;
+       a.array.scalar = true;
+
+       PG_RETURN_POINTER(hstoreDump(&a));
+}
+
+PG_FUNCTION_INFO_V1(hstore_scalar_from_numeric);
+Datum          hstore_scalar_from_numeric(PG_FUNCTION_ARGS);
+Datum
+hstore_scalar_from_numeric(PG_FUNCTION_ARGS)
+{
+       HStoreValue     a, v;
+
+       if (PG_ARGISNULL(0))
+       {
+               v.type = hsvNull;
+               v.size = sizeof(HEntry);
+       }
+       else
+       {
+               v.type = hsvNumeric;
+               v.numeric = PG_GETARG_NUMERIC(0);
+               v.size = VARSIZE_ANY(v.numeric) + 2*sizeof(HEntry);
+       }
+
+       a.type = hsvArray;
+       a.size = sizeof(HEntry) + v.size;
+       a.array.nelems = 1;
+       a.array.elems = &v;
+       a.array.scalar = true;
+
+       PG_RETURN_POINTER(hstoreDump(&a));
+}
+
+Datum          hstore_from_arrays(PG_FUNCTION_ARGS);
+Datum
+hstore_from_arrays(PG_FUNCTION_ARGS)
+{
+       HStoreValue v;
+       Datum      *key_datums;
+       bool       *key_nulls;
+       int                     key_count;
+       Datum      *value_datums;
+       bool       *value_nulls;
+       int                     value_count;
+       ArrayType  *key_array;
+       ArrayType  *value_array;
+       int                     i;
+
+       if (PG_ARGISNULL(0))
+               PG_RETURN_NULL();
+
+       key_array = PG_GETARG_ARRAYTYPE_P(0);
+
+       Assert(ARR_ELEMTYPE(key_array) == TEXTOID);
+
+       /*
+        * must check >1 rather than != 1 because empty arrays have 0 dimensions,
+        * not 1
+        */
+
+       if (ARR_NDIM(key_array) > 1)
+               ereport(ERROR,
+                               (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+                                errmsg("wrong number of array subscripts")));
+
+       deconstruct_array(key_array,
+                                         TEXTOID, -1, false, 'i',
+                                         &key_datums, &key_nulls, &key_count);
+
+       /* see discussion in arrayToHStoreSortedArray() */
+       if (key_count > MaxAllocSize / sizeof(HStorePair))
+               ereport(ERROR,
+                               (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+                         errmsg("number of pairs (%d) exceeds the maximum allowed (%d)",
+                                        key_count, (int) (MaxAllocSize / sizeof(HStorePair)))));
+
+       /* value_array might be NULL */
+
+       if (PG_ARGISNULL(1))
+       {
+               value_array = NULL;
+               value_count = key_count;
+               value_datums = NULL;
+               value_nulls = NULL;
+       }
+       else
+       {
+               value_array = PG_GETARG_ARRAYTYPE_P(1);
+
+               Assert(ARR_ELEMTYPE(value_array) == TEXTOID);
+
+               if (ARR_NDIM(value_array) > 1)
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+                                        errmsg("wrong number of array subscripts")));
+
+               if ((ARR_NDIM(key_array) > 0 || ARR_NDIM(value_array) > 0) &&
+                       (ARR_NDIM(key_array) != ARR_NDIM(value_array) ||
+                        ARR_DIMS(key_array)[0] != ARR_DIMS(value_array)[0] ||
+                        ARR_LBOUND(key_array)[0] != ARR_LBOUND(value_array)[0]))
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+                                        errmsg("arrays must have same bounds")));
+
+               deconstruct_array(value_array,
+                                                 TEXTOID, -1, false, 'i',
+                                                 &value_datums, &value_nulls, &value_count);
+
+               Assert(key_count == value_count);
+       }
+
+       v.type = hsvHash;
+       v.size = 2 * sizeof(HEntry);
+       v.hash.pairs = palloc(key_count * sizeof(*v.hash.pairs));
+       v.hash.npairs = key_count;
+
+       for (i = 0; i < key_count; ++i)
+       {
+               if (key_nulls[i])
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+                                        errmsg("null value not allowed for hstore key")));
+
+               v.hash.pairs[i].key.type = hsvString;
+               v.hash.pairs[i].key.string.val = VARDATA_ANY(key_datums[i]);
+               v.hash.pairs[i].key.string.len = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(key_datums[i]));
+               v.hash.pairs[i].key.size = sizeof(HEntry) +
+                                                                       v.hash.pairs[i].key.string.len;
+
+               if (!value_nulls || value_nulls[i])
+               {
+                       v.hash.pairs[i].value.type = hsvNull;
+                       v.hash.pairs[i].value.size = sizeof(HEntry);
+               }
+               else
+               {
+                       v.hash.pairs[i].value.type = hsvString;
+                       v.hash.pairs[i].value.size = sizeof(HEntry);
+                       v.hash.pairs[i].value.string.val = VARDATA_ANY(value_datums[i]);
+                       v.hash.pairs[i].value.string.len = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(value_datums[i]));
+                       v.hash.pairs[i].value.size = sizeof(HEntry) +
+                                                                                       v.hash.pairs[i].value.string.len;
+               }
+
+               v.size += v.hash.pairs[i].key.size + v.hash.pairs[i].value.size;
+       }
+
+       uniqueHStoreValue(&v);
+
+
+       PG_RETURN_POINTER(hstoreDump(&v));
+}
+
+
+PG_FUNCTION_INFO_V1(hstore_from_array);
+Datum          hstore_from_array(PG_FUNCTION_ARGS);
+Datum
+hstore_from_array(PG_FUNCTION_ARGS)
+{
+       ArrayType  *in_array = PG_GETARG_ARRAYTYPE_P(0);
+       int                     ndims = ARR_NDIM(in_array);
+       int                     count;
+       HStoreValue     v;
+       Datum      *in_datums;
+       bool       *in_nulls;
+       int                     in_count;
+       int                     i;
+
+       Assert(ARR_ELEMTYPE(in_array) == TEXTOID);
+
+       switch (ndims)
+       {
+               case 0:
+                       PG_RETURN_POINTER(hstoreDump(NULL));
+
+               case 1:
+                       if ((ARR_DIMS(in_array)[0]) % 2)
+                               ereport(ERROR,
+                                               (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+                                                errmsg("array must have even number of elements")));
+                       break;
+
+               case 2:
+                       if ((ARR_DIMS(in_array)[1]) != 2)
+                               ereport(ERROR,
+                                               (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+                                                errmsg("array must have two columns")));
+                       break;
+
+               default:
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+                                        errmsg("wrong number of array subscripts")));
+       }
+
+       deconstruct_array(in_array,
+                                         TEXTOID, -1, false, 'i',
+                                         &in_datums, &in_nulls, &in_count);
+
+       count = in_count / 2;
+
+       /* see discussion in arrayToHStoreSortedArray() */
+       if (count > MaxAllocSize / sizeof(HStorePair))
+               ereport(ERROR,
+                               (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+                         errmsg("number of pairs (%d) exceeds the maximum allowed (%d)",
+                                        count, (int) (MaxAllocSize / sizeof(HStorePair)))));
+
+       v.type = hsvHash;
+       v.size = 2*sizeof(HEntry);
+       v.hash.npairs = count;
+       v.hash.pairs = palloc(count * sizeof(HStorePair));
+
+       for (i = 0; i < count; ++i)
+       {
+               if (in_nulls[i * 2])
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+                                        errmsg("null value not allowed for hstore key")));
+
+               v.hash.pairs[i].key.type = hsvString;
+               v.hash.pairs[i].key.string.val = VARDATA_ANY(in_datums[i * 2]);
+               v.hash.pairs[i].key.string.len = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(in_datums[i * 2]));
+               v.hash.pairs[i].key.size = sizeof(HEntry) +
+                                                                       v.hash.pairs[i].key.string.len;
+
+               if (in_nulls[i * 2 + 1])
+               {
+                       v.hash.pairs[i].value.type = hsvNull;
+                       v.hash.pairs[i].value.size = sizeof(HEntry);
+               }
+               else
+               {
+                       v.hash.pairs[i].value.type = hsvString;
+                       v.hash.pairs[i].value.size = sizeof(HEntry);
+                       v.hash.pairs[i].value.string.val = VARDATA_ANY(in_datums[i * 2 + 1]);
+                       v.hash.pairs[i].value.string.len = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(in_datums[i * 2 + 1]));
+                       v.hash.pairs[i].value.size = sizeof(HEntry) +
+                                                                                       v.hash.pairs[i].value.string.len;
+               }
+
+               v.size += v.hash.pairs[i].key.size + v.hash.pairs[i].value.size;
+       }
+
+       uniqueHStoreValue(&v);
+
+       PG_RETURN_POINTER(hstoreDump(&v));
+}
+
+/* most of hstore_from_record is shamelessly swiped from record_out */
+
+/*
+ * structure to cache metadata needed for record I/O
+ */
+typedef struct ColumnIOData
+{
+       Oid                     column_type;
+       Oid                     typiofunc;
+       Oid                     typioparam;
+       FmgrInfo        proc;
+} ColumnIOData;
+
+typedef struct RecordIOData
+{
+       Oid                     record_type;
+       int32           record_typmod;
+       int                     ncolumns;
+       ColumnIOData columns[1];        /* VARIABLE LENGTH ARRAY */
+} RecordIOData;
+
+PG_FUNCTION_INFO_V1(hstore_from_record);
+Datum          hstore_from_record(PG_FUNCTION_ARGS);
+Datum
+hstore_from_record(PG_FUNCTION_ARGS)
+{
+       HeapTupleHeader rec;
+       HStore             *out;
+       HStoreValue        v;
+       Oid                             tupType;
+       int32                   tupTypmod;
+       TupleDesc               tupdesc;
+       HeapTupleData   tuple;
+       RecordIOData   *my_extra;
+       int                             ncolumns;
+       int                             i;
+       Datum              *values;
+       bool               *nulls;
+
+       if (PG_ARGISNULL(0))
+       {
+               Oid                     argtype = get_fn_expr_argtype(fcinfo->flinfo, 0);
+
+               /*
+                * have no tuple to look at, so the only source of type info is the
+                * argtype. The lookup_rowtype_tupdesc call below will error out if we
+                * don't have a known composite type oid here.
+                */
+               tupType = argtype;
+               tupTypmod = -1;
+
+               rec = NULL;
+       }
+       else
+       {
+               rec = PG_GETARG_HEAPTUPLEHEADER(0);
+
+               /* Extract type info from the tuple itself */
+               tupType = HeapTupleHeaderGetTypeId(rec);
+               tupTypmod = HeapTupleHeaderGetTypMod(rec);
+       }
+
+       tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
+       ncolumns = tupdesc->natts;
+
+       /*
+        * We arrange to look up the needed I/O info just once per series of
+        * calls, assuming the record type doesn't change underneath us.
+        */
+       my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
+       if (my_extra == NULL ||
+               my_extra->ncolumns != ncolumns)
+       {
+               fcinfo->flinfo->fn_extra =
+                       MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
+                                                          sizeof(RecordIOData) - sizeof(ColumnIOData)
+                                                          + ncolumns * sizeof(ColumnIOData));
+               my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
+               my_extra->record_type = InvalidOid;
+               my_extra->record_typmod = 0;
+       }
+
+       if (my_extra->record_type != tupType ||
+               my_extra->record_typmod != tupTypmod)
+       {
+               MemSet(my_extra, 0,
+                          sizeof(RecordIOData) - sizeof(ColumnIOData)
+                          + ncolumns * sizeof(ColumnIOData));
+               my_extra->record_type = tupType;
+               my_extra->record_typmod = tupTypmod;
+               my_extra->ncolumns = ncolumns;
+       }
+
+       v.type = hsvHash;
+       v.size = 2*sizeof(HEntry);
+       v.hash.npairs = ncolumns;
+       Assert(ncolumns <= MaxTupleAttributeNumber);            /* thus, no overflow */
+       v.hash.pairs = palloc(ncolumns * sizeof(HStorePair));
+
+       if (rec)
+       {
+               /* Build a temporary HeapTuple control structure */
+               tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+               ItemPointerSetInvalid(&(tuple.t_self));
+               tuple.t_tableOid = InvalidOid;
+               tuple.t_data = rec;
+
+               values = (Datum *) palloc(ncolumns * sizeof(Datum));
+               nulls = (bool *) palloc(ncolumns * sizeof(bool));
+
+               /* Break down the tuple into fields */
+               heap_deform_tuple(&tuple, tupdesc, values, nulls);
+       }
+       else
+       {
+               values = NULL;
+               nulls = NULL;
+       }
+
+       for (i = 0; i < ncolumns; ++i)
+       {
+               ColumnIOData *column_info = &my_extra->columns[i];
+               Oid                     column_type = tupdesc->attrs[i]->atttypid;
+               char       *value;
+
+               /* Ignore dropped columns in datatype */
+               if (tupdesc->attrs[i]->attisdropped)
+                       continue;
+
+               v.hash.pairs[i].key.type = hsvString;
+               v.hash.pairs[i].key.string.val = NameStr(tupdesc->attrs[i]->attname);
+               v.hash.pairs[i].key.string.len = hstoreCheckKeyLen(strlen(v.hash.pairs[i].key.string.val));
+               v.hash.pairs[i].key.size = sizeof(HEntry) +
+                                                                       v.hash.pairs[i].key.string.len;
+
+               if (!nulls || nulls[i])
+               {
+                       v.hash.pairs[i].value.type = hsvNull;
+                       v.hash.pairs[i].value.size = sizeof(HEntry);
+               }
+               else
+               {
+                       /*
+                        * Convert the column value to hstore's values
+                        */
+                       if (column_type == BOOLOID)
+                       {
+                               v.hash.pairs[i].value.type = hsvBool;
+                               v.hash.pairs[i].value.boolean = DatumGetBool(values[i]);
+                               v.hash.pairs[i].value.size = sizeof(HEntry);
+                       }
+                       else if (TypeCategory(column_type) == TYPCATEGORY_NUMERIC)
+                       {
+                               Oid                             castOid = InvalidOid;
+                               CoercionMethod  method;
+
+                               v.hash.pairs[i].value.type = hsvNumeric;
+
+                               castOid = searchCast(column_type, NUMERICOID, &method);
+                               if (castOid == InvalidOid)
+                               {
+                                       if (method != COERCION_METHOD_BINARY)
+                                               elog(ERROR, "Could not cast numeric category type to numeric '%c'", (char)method);
+
+                                       v.hash.pairs[i].value.numeric = DatumGetNumeric(values[i]);
+                               }
+                               else
+                               {
+                                       v.hash.pairs[i].value.numeric = 
+                                               DatumGetNumeric(OidFunctionCall1(castOid, values[i]));
+
+                               }
+                               v.hash.pairs[i].value.size = 2*sizeof(HEntry) +
+                                                               VARSIZE_ANY(v.hash.pairs[i].value.numeric);
+                       }
+                       else
+                       {
+                               if (column_info->column_type != column_type)
+                               {
+                                       bool            typIsVarlena;
+
+                                       getTypeOutputInfo(column_type,
+                                                                         &column_info->typiofunc,
+                                                                         &typIsVarlena);
+                                       fmgr_info_cxt(column_info->typiofunc, &column_info->proc,
+                                                                 fcinfo->flinfo->fn_mcxt);
+                                       column_info->column_type = column_type;
+                               }
+
+                               value = OutputFunctionCall(&column_info->proc, values[i]);
+
+                               v.hash.pairs[i].value.type = hsvString;
+                               v.hash.pairs[i].value.string.val = value;
+                               v.hash.pairs[i].value.string.len = hstoreCheckValLen(strlen(value));
+                               v.hash.pairs[i].value.size = sizeof(HEntry) +
+                                                                               v.hash.pairs[i].value.string.len;
+                       }
+               }
+
+               v.size += v.hash.pairs[i].key.size + v.hash.pairs[i].value.size;
+       }
+
+       uniqueHStoreValue(&v);
+
+       out = hstoreDump(&v);
+
+       ReleaseTupleDesc(tupdesc);
+
+       PG_RETURN_POINTER(out);
+}
+
+
+PG_FUNCTION_INFO_V1(hstore_populate_record);
+Datum          hstore_populate_record(PG_FUNCTION_ARGS);
+Datum
+hstore_populate_record(PG_FUNCTION_ARGS)
+{
+       Oid                     argtype = get_fn_expr_argtype(fcinfo->flinfo, 0);
+       HStore     *hs;
+       HeapTupleHeader rec;
+       Oid                     tupType;
+       int32           tupTypmod;
+       TupleDesc       tupdesc;
+       HeapTupleData tuple;
+       HeapTuple       rettuple;
+       RecordIOData *my_extra;
+       int                     ncolumns;
+       int                     i;
+       Datum      *values;
+       bool       *nulls;
+
+       if (!type_is_rowtype(argtype))
+               ereport(ERROR,
+                               (errcode(ERRCODE_DATATYPE_MISMATCH),
+                                errmsg("first argument must be a rowtype")));
+
+       if (PG_ARGISNULL(0))
+       {
+               if (PG_ARGISNULL(1))
+                       PG_RETURN_NULL();
+
+               rec = NULL;
+
+               /*
+                * have no tuple to look at, so the only source of type info is the
+                * argtype. The lookup_rowtype_tupdesc call below will error out if we
+                * don't have a known composite type oid here.
+                */
+               tupType = argtype;
+               tupTypmod = -1;
+       }
+       else
+       {
+               rec = PG_GETARG_HEAPTUPLEHEADER(0);
+
+               if (PG_ARGISNULL(1))
+                       PG_RETURN_POINTER(rec);
+
+               /* Extract type info from the tuple itself */
+               tupType = HeapTupleHeaderGetTypeId(rec);
+               tupTypmod = HeapTupleHeaderGetTypMod(rec);
+       }
+
+       hs = PG_GETARG_HS(1);
+
+       /*
+        * if the input hstore is empty, we can only skip the rest if we were
+        * passed in a non-null record, since otherwise there may be issues with
+        * domain nulls.
+        */
+
+       if (HS_ISEMPTY(hs) && rec)
+               PG_RETURN_POINTER(rec);
+
+       tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
+       ncolumns = tupdesc->natts;
+
+       if (rec)
+       {
+               /* Build a temporary HeapTuple control structure */
+               tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+               ItemPointerSetInvalid(&(tuple.t_self));
+               tuple.t_tableOid = InvalidOid;
+               tuple.t_data = rec;
+       }
+
+       /*
+        * We arrange to look up the needed I/O info just once per series of
+        * calls, assuming the record type doesn't change underneath us.
+        */
+       my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
+       if (my_extra == NULL ||
+               my_extra->ncolumns != ncolumns)
+       {
+               fcinfo->flinfo->fn_extra =
+                       MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
+                                                          sizeof(RecordIOData) - sizeof(ColumnIOData)
+                                                          + ncolumns * sizeof(ColumnIOData));
+               my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
+               my_extra->record_type = InvalidOid;
+               my_extra->record_typmod = 0;
+       }
+
+       if (my_extra->record_type != tupType ||
+               my_extra->record_typmod != tupTypmod)
+       {
+               MemSet(my_extra, 0,
+                          sizeof(RecordIOData) - sizeof(ColumnIOData)
+                          + ncolumns * sizeof(ColumnIOData));
+               my_extra->record_type = tupType;
+               my_extra->record_typmod = tupTypmod;
+               my_extra->ncolumns = ncolumns;
+       }
+
+       values = (Datum *) palloc(ncolumns * sizeof(Datum));
+       nulls = (bool *) palloc(ncolumns * sizeof(bool));
+
+       if (rec)
+       {
+               /* Break down the tuple into fields */
+               heap_deform_tuple(&tuple, tupdesc, values, nulls);
+       }
+       else
+       {
+               for (i = 0; i < ncolumns; ++i)
+               {
+                       values[i] = (Datum) 0;
+                       nulls[i] = true;
+               }
+       }
+
+       for (i = 0; i < ncolumns; ++i)
+       {
+               ColumnIOData *column_info = &my_extra->columns[i];
+               Oid                     column_type = tupdesc->attrs[i]->atttypid;
+               HStoreValue     *v = NULL;
+
+               /* Ignore dropped columns in datatype */
+               if (tupdesc->attrs[i]->attisdropped)
+               {
+                       nulls[i] = true;
+                       continue;
+               }
+
+               if (!HS_ISEMPTY(hs))
+               {
+                       char *key = NameStr(tupdesc->attrs[i]->attname);
+
+                       v = findUncompressedHStoreValue(VARDATA(hs), HS_FLAG_HSTORE, NULL, key, strlen(key));
+               }
+
+               /*
+                * we can't just skip here if the key wasn't found since we might have
+                * a domain to deal with. If we were passed in a non-null record
+                * datum, we assume that the existing values are valid (if they're
+                * not, then it's not our fault), but if we were passed in a null,
+                * then every field which we don't populate needs to be run through
+                * the input function just in case it's a domain type.
+                */
+               if (v == NULL && rec)
+                       continue;
+
+               /*
+                * Prepare to convert the column value from text
+                */
+               if (column_info->column_type != column_type)
+               {
+                       getTypeInputInfo(column_type,
+                                                        &column_info->typiofunc,
+                                                        &column_info->typioparam);
+                       fmgr_info_cxt(column_info->typiofunc, &column_info->proc,
+                                                 fcinfo->flinfo->fn_mcxt);
+                       column_info->column_type = column_type;
+               }
+
+               if (v == NULL || v->type == hsvNull)
+               {
+                       /*
+                        * need InputFunctionCall to happen even for nulls, so that domain
+                        * checks are done
+                        */
+                       values[i] = InputFunctionCall(&column_info->proc, NULL,
+                                                                                 column_info->typioparam,
+                                                                                 tupdesc->attrs[i]->atttypmod);
+                       nulls[i] = true;
+               }
+               else
+               {
+                       char *s = NULL;
+
+                       if (v->type == hsvString)
+                               s = pnstrdup(v->string.val, v->string.len);
+                       else if (v->type == hsvBool)
+                               s = pnstrdup((v->boolean) ? "t" : "f", 1);
+                       else if (v->type == hsvNumeric)
+                               s = DatumGetCString(DirectFunctionCall1(numeric_out,
+                                                                                                               PointerGetDatum(v->numeric)));
+                       else if (v->type == hsvBinary && column_type == JSONOID)
+                               s = hstoreToCString(NULL, v->binary.data, v->binary.len,
+                                                                       SET_PRETTY_PRINT_VAR(JsonOutput | RootHashDecorated));
+                       else if (v->type == hsvBinary && type_is_array(column_type))
+                               s = hstoreToCString(NULL, v->binary.data, v->binary.len,
+                                                                       SET_PRETTY_PRINT_VAR(ArrayCurlyBraces));
+                       else if (v->type == hsvBinary)
+                               s = hstoreToCString(NULL, v->binary.data, v->binary.len,
+                                                                       SET_PRETTY_PRINT_VAR(0));
+                       else
+                               elog(PANIC, "Wrong hstore");
+
+                       values[i] = InputFunctionCall(&column_info->proc, s,
+                                                                                 column_info->typioparam,
+                                                                                 tupdesc->attrs[i]->atttypmod);
+                       nulls[i] = false;
+               }
+       }
+
+       rettuple = heap_form_tuple(tupdesc, values, nulls);
+
+       ReleaseTupleDesc(tupdesc);
+
+       PG_RETURN_DATUM(HeapTupleGetDatum(rettuple));
+}
+
+bool
+stringIsNumber(char *string, int len, bool jsonNumber) {
+       enum {
+               SIN_FIRSTINT,
+               SIN_ZEROINT,
+               SIN_INT,
+               SIN_SCALE,
+               SIN_MSIGN,
+               SIN_MANTISSA
+       } sinState;
+       char    *c;
+       bool    r;
+
+       if (*string == '-' || *string == '+')
+       {
+               string++;
+               len--;
+       }
+
+       c = string;
+       r = true;
+       sinState = SIN_FIRSTINT;
+
+       while(r && c - string < len)
+       {
+               switch(sinState)
+               {
+                       case SIN_FIRSTINT:
+                               if (*c == '0' && jsonNumber)
+                                       sinState = SIN_ZEROINT;
+                               else if (*c == '.')
+                                       sinState = SIN_SCALE;
+                               else if (isdigit(*c))
+                                       sinState = SIN_INT;
+                               else
+                                       r = false;
+                               break;
+                       case SIN_ZEROINT:
+                               if (*c == '.')
+                                       sinState = SIN_SCALE;
+                               else
+                                       r = false;
+                               break;
+                       case SIN_INT:
+                               if (*c == '.')
+                                       sinState = SIN_SCALE;
+                               else if (*c == 'e' || *c == 'E')
+                                       sinState = SIN_MSIGN;
+                               else if (!isdigit(*c))
+                                       r = false;
+                               break;
+                       case SIN_SCALE:
+                               if (*c == 'e' || *c == 'E')
+                                       sinState = SIN_MSIGN;
+                               else if (!isdigit(*c))
+                                       r = false;
+                               break;
+                       case SIN_MSIGN:
+                               if (*c == '-' || *c == '+' || isdigit(*c))
+                                       sinState = SIN_MANTISSA;
+                               else
+                                       r = false;
+                               break;
+                       case SIN_MANTISSA:
+                               if (!isdigit(*c))
+                                       r = false;
+                               break;
+                       default:
+                               abort();
+               }
+
+               c++;
+       }
+
+       if (sinState == SIN_MSIGN)
+               r = false;
+
+       return r;
+}
+
+static void
+printIndent(StringInfo out, bool isRootHash, HStoreOutputKind kind, int level)
+{
+       if (kind & PrettyPrint)
+       {
+               int i;
+
+               if (isRootHash && (kind & RootHashDecorated) == 0)
+                       level--;
+               for(i=0; i<4*level; i++)
+                       appendStringInfoCharMacro(out, ' ');
+       }
+}
+
+static void
+printCR(StringInfo out, HStoreOutputKind kind)
+{
+       if (kind & PrettyPrint)
+               appendStringInfoCharMacro(out, '\n');
+}
+
+static void
+escape_hstore(StringInfo out, char *string, uint32 len)
+{
+       char       *ptr = string;
+
+       appendStringInfoCharMacro(out, '"');
+       while (ptr - string < len)
+       {
+               if (*ptr == '"' || *ptr == '\\')
+                       appendStringInfoCharMacro(out, '\\');
+               appendStringInfoCharMacro(out, *ptr);
+               ptr++;
+       }
+       appendStringInfoCharMacro(out, '"');
+}
+
+static void
+putEscapedString(StringInfo out, HStoreOutputKind kind,
+                                char *string, uint32 len)
+{
+       if (kind & LooseOutput)
+       {
+               if (len == 1 && *string == 't')
+                       appendStringInfoString(out, (kind & JsonOutput) ? "true" : "t" );
+               else if (len == 1 && *string == 'f')
+                       appendStringInfoString(out, (kind & JsonOutput) ? "false" : "f");
+               else if (len > 0 && stringIsNumber(string, len, true))
+                       appendBinaryStringInfo(out, string, len);
+               else if (kind & JsonOutput)
+                       escape_json(out, pnstrdup(string, len));
+               else
+                       escape_hstore(out, string, len);
+       }
+       else
+       {
+               if (kind & JsonOutput)
+                       escape_json(out, pnstrdup(string, len));
+               else
+                       escape_hstore(out, string, len);
+       }
+}
+
+static void
+putEscapedValue(StringInfo out, HStoreOutputKind kind, HStoreValue *v)
+{
+       switch(v->type)
+       {
+               case hsvNull:
+                       appendBinaryStringInfo(out,
+                                                                  (kind & JsonOutput) ? "null" : "NULL", 4);
+                       break;
+               case hsvString:
+                       putEscapedString(out, kind, v->string.val, v->string.len);
+                       break;
+               case hsvBool:
+                       if ((kind & JsonOutput) == 0)
+                               appendBinaryStringInfo(out, (v->boolean) ? "t" : "f", 1);
+                       else if (v->boolean)
+                               appendBinaryStringInfo(out, "true", 4);
+                       else
+                               appendBinaryStringInfo(out, "false", 5);
+                       break;
+               case hsvNumeric:
+                       appendStringInfoString(out, DatumGetCString(DirectFunctionCall1(numeric_out, PointerGetDatum(v->numeric))));
+                       break;
+               default:
+                       elog(PANIC, "Unknown type");
+       }
+}
+
+static bool
+needBrackets(int level, bool isArray, HStoreOutputKind kind, bool isScalar)
+{
+       bool res;
+
+       if (isArray && isScalar)
+               res = false;
+       else if (level == 0)
+               res = (isArray || (kind & RootHashDecorated)) ? true : false;
+       else
+               res = true;
+
+       return res;
+}
+
+static bool
+isArrayBrackets(HStoreOutputKind kind)
+{
+       return ((kind & ArrayCurlyBraces) == 0) ? true : false;
+}
+
+
+char*
+hstoreToCString(StringInfo out, char *in, int len /* just estimation */,
+                 HStoreOutputKind kind)
+{
+       bool                    first = true;
+       HStoreIterator  *it;
+       int                             type;
+       HStoreValue             v;
+       int                             level = 0;
+       bool                    isRootHash = false;
+
+       if (out == NULL)
+               out = makeStringInfo();
+
+       if (in == NULL)
+       {
+               appendStringInfoString(out, "");
+               return out->data;
+       }
+
+       enlargeStringInfo(out, (len >= 0) ? len : 64);
+
+       it = HStoreIteratorInit(in);
+
+       while((type = HStoreIteratorGet(&it, &v, false)) != 0)
+       {
+reout:
+               switch(type)
+               {
+                       case WHS_BEGIN_ARRAY:
+                               if (first == false)
+                               {
+                                       appendBinaryStringInfo(out, ", ", 2);
+                                       printCR(out, kind);
+                               }
+                               first = true;
+
+                               if (needBrackets(level, true, kind, v.array.scalar))
+                               {
+                                       printIndent(out, isRootHash, kind, level);
+                                       appendStringInfoChar(out, isArrayBrackets(kind) ? '[' : '{');
+                                       printCR(out, kind);
+                               }
+                               level++;
+                               break;
+                       case WHS_BEGIN_HASH:
+                               if (first == false)
+                               {
+                                       appendBinaryStringInfo(out, ", ", 2);
+                                       printCR(out, kind);
+                               }
+                               first = true;
+
+                               if (level == 0)
+                                       isRootHash = true;
+
+                               if (needBrackets(level, false, kind, false))
+                               {
+                                       printIndent(out, isRootHash, kind, level);
+                                       appendStringInfoCharMacro(out, '{');
+                                       printCR(out, kind);
+                               }
+
+                               level++;
+                               break;
+                       case WHS_KEY:
+                               if (first == false)
+                               {
+                                       appendBinaryStringInfo(out, ", ", 2);
+                                       printCR(out, kind);
+                               }
+                               first = true;
+
+                               printIndent(out, isRootHash, kind, level);
+                               /* key should not be loose */
+                               putEscapedValue(out, kind & ~LooseOutput, &v);
+                               appendBinaryStringInfo(out,
+                                                                          (kind & JsonOutput) ? ": " : "=>", 2);
+
+                               type = HStoreIteratorGet(&it, &v, false);
+                               if (type == WHS_VALUE)
+                               {
+                                       first = false;
+                                       putEscapedValue(out, kind, &v);
+                               }
+                               else
+                               {
+                                       Assert(type == WHS_BEGIN_HASH || type == WHS_BEGIN_ARRAY);
+                                       printCR(out, kind);
+                                       /*
+                                        * We need to rerun current switch() due to put
+                                        * in current place object which we just got
+                                        * from iterator.
+                                        */
+                                       goto reout;
+                               }
+                               break;
+                       case WHS_ELEM:
+                               if (first == false)
+                               {
+                                       appendBinaryStringInfo(out, ", ", 2);
+                                       printCR(out, kind);
+                               }
+                               else
+                               {
+                                       first = false;
+                               }
+
+                               printIndent(out, isRootHash, kind, level);
+                               putEscapedValue(out, kind, &v);
+                               break;
+                       case WHS_END_ARRAY:
+                               level--;
+                               if (needBrackets(level, true, kind, v.array.scalar))
+                               {
+                                       printCR(out, kind);
+                                       printIndent(out, isRootHash, kind, level);
+                                       appendStringInfoChar(out, isArrayBrackets(kind) ? ']' : '}');
+                               }
+                               first = false;
+                               break;
+                       case WHS_END_HASH:
+                               level--;
+                               if (needBrackets(level, false, kind, false))
+                               {
+                                       printCR(out, kind);
+                                       printIndent(out, isRootHash, kind, level);
+                                       appendStringInfoCharMacro(out, '}');
+                               }
+                               first = false;
+                               break;
+                       default:
+                               elog(PANIC, "Wrong flags");
+               }
+       }
+
+       Assert(level == 0);
+
+       return out->data;
+}
+
+text*
+HStoreValueToText(HStoreValue *v)
+{
+       text            *out;
+
+       if (v == NULL || v->type == hsvNull)
+       {
+               out = NULL;
+       }
+       else if (v->type == hsvString)
+       {
+               out = cstring_to_text_with_len(v->string.val, v->string.len);
+       }
+       else if (v->type == hsvBool)
+       {
+               out = cstring_to_text_with_len((v->boolean) ? "t" : "f", 1);
+       }
+       else if (v->type == hsvNumeric)
+       {
+               out = cstring_to_text(DatumGetCString(
+                               DirectFunctionCall1(numeric_out, PointerGetDatum(v->numeric))
+               ));
+       }
+       else
+       {
+               StringInfo      str;
+
+               str = makeStringInfo();
+               appendBinaryStringInfo(str, "    ", 4); /* VARHDRSZ */
+
+               hstoreToCString(str, v->binary.data, v->binary.len,
+                                               SET_PRETTY_PRINT_VAR(0));
+
+               out = (text*)str->data;
+               SET_VARSIZE(out, str->len);
+       }
+
+       return out;
+}
+
+PG_FUNCTION_INFO_V1(hstore_out);
+Datum          hstore_out(PG_FUNCTION_ARGS);
+Datum
+hstore_out(PG_FUNCTION_ARGS)
+{
+       HStore  *hs = PG_GETARG_HS(0);
+       char    *out;
+
+       out = hstoreToCString(NULL, (HS_ISEMPTY(hs)) ? NULL : VARDATA(hs),
+                                                 VARSIZE(hs), SET_PRETTY_PRINT_VAR(0));
+
+       PG_RETURN_CSTRING(out);
+}
+
+PG_FUNCTION_INFO_V1(hstore_send);
+Datum          hstore_send(PG_FUNCTION_ARGS);
+Datum
+hstore_send(PG_FUNCTION_ARGS)
+{
+       HStore                  *in = PG_GETARG_HS(0);
+       StringInfoData  buf;
+
+       pq_begintypsend(&buf);
+
+       if (HS_ISEMPTY(in))
+       {
+               pq_sendint(&buf, 0, 4);
+       }
+       else
+       {
+               HStoreIterator  *it;
+               int                             type;
+               HStoreValue             v;
+               uint32                  flag;
+               bytea                   *nbuf;
+
+               enlargeStringInfo(&buf, VARSIZE_ANY(in) /* just estimation */);
+
+               it = HStoreIteratorInit(VARDATA_ANY(in));
+
+               while((type = HStoreIteratorGet(&it, &v, false)) != 0)
+               {
+                       switch(type)
+                       {
+                               case WHS_BEGIN_ARRAY:
+                                       flag = (v.array.scalar) ? HENTRY_ISSCALAR : HENTRY_ISARRAY;
+                                       pq_sendint(&buf, v.array.nelems | flag, 4);
+                                       break;
+                               case WHS_BEGIN_HASH:
+                                       pq_sendint(&buf, v.hash.npairs | HENTRY_ISHASH, 4);
+                                       break;
+                               case WHS_KEY:
+                                       pq_sendint(&buf, v.string.len | HENTRY_ISSTRING, 4);
+                                       pq_sendtext(&buf, v.string.val, v.string.len);
+                                       break;
+                               case WHS_ELEM:
+                               case WHS_VALUE:
+                                       switch(v.type)
+                                       {
+                                               case hsvNull:
+                                                       pq_sendint(&buf, HENTRY_ISNULL, 4);
+                                                       break;
+                                               case hsvString:
+                                                       pq_sendint(&buf, v.string.len | HENTRY_ISSTRING, 4);
+                                                       pq_sendtext(&buf, v.string.val, v.string.len);
+                                                       break;
+                                               case hsvBool:
+                                                       pq_sendint(&buf, (v.boolean) ? HENTRY_ISTRUE : HENTRY_ISFALSE, 4);
+                                                       break;
+                                               case hsvNumeric:
+                                                       nbuf = DatumGetByteaP(DirectFunctionCall1(numeric_send, NumericGetDatum(v.numeric)));
+                                                       pq_sendint(&buf, ((int)VARSIZE_ANY_EXHDR(nbuf)) | HENTRY_ISNUMERIC, 4);
+                                                       pq_sendbytes(&buf, VARDATA(nbuf), (int)VARSIZE_ANY_EXHDR(nbuf));
+                                                       break;
+                                               default:
+                                                       elog(PANIC, "Wrong type: %u", v.type);
+                                       }
+                                       break;
+                               case WHS_END_ARRAY:
+                               case WHS_END_HASH:
+                                       break;
+                               default:
+                                       elog(PANIC, "Wrong flags");
+                       }
+               }
+       }
+
+       PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
+}
+
+
+/*
+ * hstore_to_json_loose
+ *
+ * This is a heuristic conversion to json which treats
+ * 't' and 'f' as booleans and strings that look like numbers as numbers,
+ * as long as they don't start with a leading zero followed by another digit
+ * (think zip codes or phone numbers starting with 0).
+ */
+PG_FUNCTION_INFO_V1(hstore_to_json_loose);
+Datum          hstore_to_json_loose(PG_FUNCTION_ARGS);
+Datum
+hstore_to_json_loose(PG_FUNCTION_ARGS)
+{
+       HStore     *in = PG_GETARG_HS(0);
+       text       *out;
+
+       if (HS_ISEMPTY(in))
+       {
+               out = cstring_to_text_with_len("{}",2);
+       }
+       else
+       {
+               StringInfo      str;
+
+               str = makeStringInfo();
+               appendBinaryStringInfo(str, "    ", 4); /* VARHDRSZ */
+
+               hstoreToCString(str, VARDATA_ANY(in), VARSIZE_ANY(in),
+                                               SET_PRETTY_PRINT_VAR(JsonOutput | RootHashDecorated | LooseOutput));
+
+               out = (text*)str->data;
+
+               SET_VARSIZE(out, str->len);
+       }
+
+       PG_RETURN_TEXT_P(out);
+}
+
+PG_FUNCTION_INFO_V1(hstore_to_json);
+Datum          hstore_to_json(PG_FUNCTION_ARGS);
+Datum
+hstore_to_json(PG_FUNCTION_ARGS)
+{
+       HStore     *in = PG_GETARG_HS(0);
+       text       *out;
+
+       if (HS_ISEMPTY(in))
+       {
+               out = cstring_to_text_with_len("{}",2);
+       }
+       else
+       {
+               StringInfo      str;
+
+               str = makeStringInfo();
+               appendBinaryStringInfo(str, "    ", 4); /* VARHDRSZ */
+
+               hstoreToCString(str,
+                                               HS_ISEMPTY(in) ? NULL : VARDATA_ANY(in),
+                                               VARSIZE_ANY(in),
+                                               SET_PRETTY_PRINT_VAR(JsonOutput | RootHashDecorated));
+
+               out = (text*)str->data;
+
+               SET_VARSIZE(out, str->len);
+       }
+
+       PG_RETURN_TEXT_P(out);
+}
+
+PG_FUNCTION_INFO_V1(json_to_hstore);
+Datum          json_to_hstore(PG_FUNCTION_ARGS);
+Datum
+json_to_hstore(PG_FUNCTION_ARGS)
+{
+       text    *json = PG_GETARG_TEXT_PP(0);
+
+       PG_RETURN_POINTER(hstoreDump(parseHStore(VARDATA_ANY(json),
+                                                                                        VARSIZE_ANY_EXHDR(json), true)));
+}
+
+static Oid
+searchCast(Oid src, Oid dst, CoercionMethod *method)
+{
+       Oid                             funcOid = InvalidOid,
+                                       baseSrc;
+       HeapTuple       tuple;
+
+       if (src == dst)
+       {
+               *method = COERCION_METHOD_BINARY;
+               return InvalidOid;
+       }
+
+       tuple = SearchSysCache2(CASTSOURCETARGET,
+                                                       ObjectIdGetDatum(src),
+                                                       ObjectIdGetDatum(dst));
+
+       *method = 0;
+
+       if (HeapTupleIsValid(tuple))
+       {
+               Form_pg_cast    castForm = (Form_pg_cast) GETSTRUCT(tuple);
+
+               if (castForm->castmethod == COERCION_METHOD_FUNCTION)
+                       funcOid = castForm->castfunc;
+
+               *method = castForm->castmethod;
+
+               ReleaseSysCache(tuple);
+       }
+       else if ((baseSrc = getBaseType(src)) != src && OidIsValid(baseSrc))
+       {       
+               /* domain type */
+               funcOid = searchCast(baseSrc, dst, method);
+       }
+
+       return funcOid;
+}
+
+PG_FUNCTION_INFO_V1(array_to_hstore);
+Datum          array_to_hstore(PG_FUNCTION_ARGS);
+Datum
+array_to_hstore(PG_FUNCTION_ARGS)
+{
+       ArrayType               *array = PG_GETARG_ARRAYTYPE_P(0);
+       ArrayIterator   iterator;
+       int                             i = 0;
+       Datum                   datum;
+       bool                    isnull;
+       int                             ncounters = ARR_NDIM(array),
+                                       *counters = palloc0(sizeof(*counters) * ncounters),
+                                       *dims = ARR_DIMS(array);
+       ToHStoreState   *state = NULL;
+       HStoreValue             value, *result;
+       Oid                             castOid = InvalidOid;
+       int                             valueType = hsvString;
+       FmgrInfo                castInfo;
+       CoercionMethod  method;
+
+       if (ArrayGetNItems(ARR_NDIM(array), ARR_DIMS(array)) == 0)
+               PG_RETURN_POINTER(hstoreDump(NULL));
+
+       switch(ARR_ELEMTYPE(array))
+       {
+               case BOOLOID:
+                       valueType = hsvBool;
+                       break;
+               case NUMERICOID:
+                       valueType = hsvNumeric;
+                       break;
+               case TEXTOID:
+                       valueType = hsvString;
+                       break;
+               default:
+                       if (TypeCategory(ARR_ELEMTYPE(array)) == TYPCATEGORY_NUMERIC)
+                       {
+                               castOid = searchCast(ARR_ELEMTYPE(array), NUMERICOID, &method);
+
+                               if (castOid == InvalidOid && method != COERCION_METHOD_BINARY)
+                                       elog(ERROR, "Could not cast array's element type to numeric");
+
+                               valueType = hsvNumeric;
+                               break;
+                       }
+                       else
+                       {
+                               castOid = searchCast(ARR_ELEMTYPE(array), TEXTOID, &method);
+
+                               if (castOid == InvalidOid && method != COERCION_METHOD_BINARY)
+                                       elog(ERROR, "Could not cast array's element type to text");
+
+                               valueType = hsvString;
+                               break;
+                       }
+       }
+
+       if (castOid != InvalidOid)
+               fmgr_info(castOid, &castInfo);
+
+       iterator = array_create_iterator(array, 0);
+
+       value.type = hsvArray;
+       value.array.scalar = false;
+       for(i=0; i<ncounters; i++)
+       {
+               value.array.nelems = dims[i];
+               result = pushHStoreValue(&state, WHS_BEGIN_ARRAY, &value);
+       }
+
+       while(array_iterate(iterator, &datum, &isnull))
+       {
+               i = ncounters - 1;
+
+               if (counters[i] >= dims[i])
+               {
+                       while(i>=0 && counters[i] >= dims[i])
+                       {
+                               counters[i] = 0;
+                               result = pushHStoreValue(&state, WHS_END_ARRAY, NULL);
+                               i--;
+                       }
+
+                       Assert(i>=0);
+
+                       counters[i]++;
+
+                       value.type = hsvArray;
+                       value.array.scalar = false;
+                       for(i = i + 1; i<ncounters; i++)
+                       {
+                               counters[i] = 1;
+                               value.array.nelems = dims[i];
+                               result = pushHStoreValue(&state, WHS_BEGIN_ARRAY, &value);
+                       }
+               }
+               else
+               {
+                       counters[i]++;
+               }
+
+               if (isnull)
+               {
+                       value.type = hsvNull;
+                       value.size = sizeof(HEntry);
+               }
+               else
+               {
+                       value.type = valueType;
+                       switch(valueType)
+                       {
+                               case hsvBool:
+                                       value.boolean = DatumGetBool(datum);
+                                       value.size = sizeof(HEntry);
+                                       break;
+                               case hsvString:
+                                       if (castOid != InvalidOid)
+                                               datum = FunctionCall1(&castInfo, datum);
+                                       value.string.val = VARDATA_ANY(datum);
+                                       value.string.len = VARSIZE_ANY_EXHDR(datum);
+                                       value.size = sizeof(HEntry) + value.string.len;
+                                       break;
+                               case hsvNumeric:
+                                       if (castOid != InvalidOid)
+                                               datum = FunctionCall1(&castInfo, datum);
+                                       value.numeric = DatumGetNumeric(datum);
+                                       value.size = sizeof(HEntry)*2 + VARSIZE_ANY(value.numeric);
+                                       break;
+                               default:
+                                       elog(ERROR, "Impossible state: %d", valueType);
+                       }
+               }
+
+               result = pushHStoreValue(&state, WHS_ELEM, &value);
+       }
+
+       for(i=0; i<ncounters; i++)
+               result = pushHStoreValue(&state, WHS_END_ARRAY, NULL);
+
+       PG_RETURN_POINTER(hstoreDump(result));
+}
+
+PG_FUNCTION_INFO_V1(hstore_print);
+Datum          hstore_print(PG_FUNCTION_ARGS);
+Datum
+hstore_print(PG_FUNCTION_ARGS)
+{
+       HStore          *hs = PG_GETARG_HS(0);
+       int             flags = 0;
+       text            *out;
+       StringInfo      str;
+
+       if (PG_GETARG_BOOL(1))
+               flags |= PrettyPrint;
+       if (PG_GETARG_BOOL(2))
+               flags |= ArrayCurlyBraces;
+       if (PG_GETARG_BOOL(3))
+               flags |= RootHashDecorated;
+       if (PG_GETARG_BOOL(4))
+               flags |= JsonOutput;
+       if (PG_GETARG_BOOL(5))
+               flags |= LooseOutput;
+
+       str = makeStringInfo();
+       appendBinaryStringInfo(str, "    ", 4); /* VARHDRSZ */
+
+       hstoreToCString(str, (HS_ISEMPTY(hs)) ? NULL : VARDATA(hs),
+                                       VARSIZE(hs), flags);
+
+       out = (text*)str->data;
+       SET_VARSIZE(out, str->len);
+
+       PG_RETURN_TEXT_P(out);
+}
+
+void _PG_init(void);
+void
+_PG_init(void)
+{
+       DefineCustomBoolVariable(
+               "hstore.pretty_print",
+               "Enable pretty print",
+               "Enable pretty print of hstore type",
+               &pretty_print_var,
+               pretty_print_var,
+               PGC_USERSET,
+               GUC_NOT_IN_SAMPLE,
+               NULL,
+               NULL,
+               NULL
+       );
+
+       EmitWarningsOnPlaceholders("hstore");
+}
diff --git a/hstore_op.c b/hstore_op.c
new file mode 100644 (file)
index 0000000..ef210cb
--- /dev/null
@@ -0,0 +1,3154 @@
+/*
+ * contrib/hstore/hstore_op.c
+ */
+#include "postgres.h"
+
+#include "access/hash.h"
+#include "access/htup_details.h"
+#include "catalog/pg_type.h"
+#include "funcapi.h"
+#include "utils/builtins.h"
+#include "utils/memutils.h"
+#include "utils/pg_crc.h"
+
+#include "hstore.h"
+
+#ifndef SRF_RETURN_NEXT_NULL
+#define SRF_RETURN_NEXT_NULL(_funcctx) \
+       do { \
+               ReturnSetInfo      *rsi; \
+               (_funcctx)->call_cntr++; \
+               rsi = (ReturnSetInfo *) fcinfo->resultinfo; \
+               rsi->isDone = ExprMultipleResult; \
+               PG_RETURN_NULL(); \
+       } while (0)
+#endif
+
+/* old names for C functions */
+HSTORE_POLLUTE(hstore_fetchval, fetchval);
+HSTORE_POLLUTE(hstore_exists, exists);
+HSTORE_POLLUTE(hstore_defined, defined);
+HSTORE_POLLUTE(hstore_delete, delete);
+HSTORE_POLLUTE(hstore_concat, hs_concat);
+HSTORE_POLLUTE(hstore_contains, hs_contains);
+HSTORE_POLLUTE(hstore_contained, hs_contained);
+HSTORE_POLLUTE(hstore_akeys, akeys);
+HSTORE_POLLUTE(hstore_avals, avals);
+HSTORE_POLLUTE(hstore_skeys, skeys);
+HSTORE_POLLUTE(hstore_svals, svals);
+HSTORE_POLLUTE(hstore_each, each);
+
+static HStoreValue*
+arrayToHStoreSortedArray(ArrayType *a)
+{
+       Datum                   *key_datums;
+       bool                    *key_nulls;
+       int                             key_count;
+       HStoreValue             *v;
+       int                             i,
+                                       j;
+       bool                    hasNonUniq = false;
+
+       deconstruct_array(a,
+                                         TEXTOID, -1, false, 'i',
+                                         &key_datums, &key_nulls, &key_count);
+
+       if (key_count == 0)
+               return NULL;
+
+       /*
+        * A text array uses at least eight bytes per element, so any overflow in
+        * "key_count * sizeof(Pairs)" is small enough for palloc() to catch.
+        * However, credible improvements to the array format could invalidate
+        * that assumption.  Therefore, use an explicit check rather than relying
+        * on palloc() to complain.
+        */
+       if (key_count > MaxAllocSize / sizeof(HStorePair))
+               ereport(ERROR,
+                               (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+                         errmsg("number of pairs (%d) exceeds the maximum allowed (%d)",
+                                        key_count, (int) (MaxAllocSize / sizeof(HStorePair)))));
+
+       v = palloc(sizeof(*v));
+       v->type = hsvArray;
+       v->array.scalar = false;
+
+       v->array.elems = palloc(sizeof(*v->hash.pairs) * key_count);
+
+       for (i = 0, j = 0; i < key_count; i++)
+       {
+               if (!key_nulls[i])
+               {
+                       v->array.elems[j].type = hsvString;
+                       v->array.elems[j].string.val = VARDATA(key_datums[i]);
+                       v->array.elems[j].string.len = VARSIZE(key_datums[i]) - VARHDRSZ;
+                       j++;
+               }
+       }
+       v->array.nelems = j;
+
+       if (v->array.nelems > 1)
+               qsort_arg(v->array.elems, v->array.nelems, sizeof(*v->array.elems),
+                                 compareHStoreStringValue, &hasNonUniq);
+
+       if (hasNonUniq)
+       {
+               HStoreValue     *ptr = v->array.elems + 1,
+                                       *res = v->array.elems;
+
+               while (ptr - v->array.elems < v->array.nelems)
+               {
+                       if (!(ptr->string.len == res->string.len &&
+                                 memcmp(ptr->string.val, res->string.val, ptr->string.len) == 0))
+                       {
+                               res++;
+                               *res = *ptr;
+                       }
+
+                       ptr++;
+               }
+
+               v->array.nelems = res + 1 - v->array.elems;
+       }
+
+       return v;
+}
+
+static HStoreValue*
+findInHStoreSortedArray(HStoreValue *a, uint32 *lowbound,
+                                               char *key, uint32 keylen)
+{
+       HStoreValue             *stopLow = a->array.elems + ((lowbound) ? *lowbound : 0),
+                                       *stopHigh = a->array.elems + a->array.nelems,
+                                       *stopMiddle;
+
+       while (stopLow < stopHigh)
+       {
+               int diff;
+
+               stopMiddle = stopLow + (stopHigh - stopLow) / 2;
+
+               if (keylen == stopMiddle->string.len)
+                       diff = memcmp(stopMiddle->string.val, key, keylen);
+               else
+                       diff = (stopMiddle->string.len > keylen) ? 1 : -1;
+
+               if (diff == 0)
+               {
+                       if (lowbound)
+                               *lowbound = (stopMiddle - a->array.elems) + 1;
+                       return stopMiddle;
+               }
+               else if (diff < 0)
+               {
+                       stopLow = stopMiddle + 1;
+               }
+               else
+               {
+                       stopHigh = stopMiddle;
+               }
+       }
+
+       if (lowbound)
+               *lowbound = (stopLow - a->array.elems) + 1;
+
+       return NULL;
+}
+
+PG_FUNCTION_INFO_V1(hstore_fetchval);
+Datum          hstore_fetchval(PG_FUNCTION_ARGS);
+Datum
+hstore_fetchval(PG_FUNCTION_ARGS)
+{
+       HStore          *hs = PG_GETARG_HS(0);
+       text            *key = PG_GETARG_TEXT_PP(1);
+       HStoreValue     *v = NULL;
+       text            *out;
+
+       if (!HS_ISEMPTY(hs))
+               v = findUncompressedHStoreValue(VARDATA(hs),
+                                                                               HS_FLAG_HSTORE | HS_FLAG_ARRAY,
+                                                                               NULL,
+                                                                               VARDATA_ANY(key),
+                                                                               VARSIZE_ANY_EXHDR(key));
+
+       if ((out = HStoreValueToText(v)) == NULL)
+               PG_RETURN_NULL();
+       else
+               PG_RETURN_TEXT_P(out);
+}
+
+PG_FUNCTION_INFO_V1(hstore_fetchval_numeric);
+Datum          hstore_fetchval_numeric(PG_FUNCTION_ARGS);
+Datum
+hstore_fetchval_numeric(PG_FUNCTION_ARGS)
+{
+       HStore          *hs = PG_GETARG_HS(0);
+       text            *key = PG_GETARG_TEXT_PP(1);
+       HStoreValue     *v = NULL;
+
+       if (!HS_ISEMPTY(hs))
+               v = findUncompressedHStoreValue(VARDATA(hs),
+                                                                               HS_FLAG_HSTORE | HS_FLAG_ARRAY,
+                                                                               NULL,
+                                                                               VARDATA_ANY(key),
+                                                                               VARSIZE_ANY_EXHDR(key));
+
+       if (v && v->type == hsvNumeric)
+       {
+               Numeric         out = palloc(VARSIZE_ANY(v->numeric));
+
+               memcpy(out, v->numeric, VARSIZE_ANY(v->numeric));
+               PG_RETURN_NUMERIC(out);
+       }
+
+       PG_RETURN_NULL();
+}
+
+PG_FUNCTION_INFO_V1(hstore_fetchval_boolean);
+Datum          hstore_fetchval_boolean(PG_FUNCTION_ARGS);
+Datum
+hstore_fetchval_boolean(PG_FUNCTION_ARGS)
+{
+       HStore          *hs = PG_GETARG_HS(0);
+       text            *key = PG_GETARG_TEXT_PP(1);
+       HStoreValue     *v = NULL;
+
+       if (!HS_ISEMPTY(hs))
+               v = findUncompressedHStoreValue(VARDATA(hs),
+                                                                               HS_FLAG_HSTORE | HS_FLAG_ARRAY,
+                                                                               NULL,
+                                                                               VARDATA_ANY(key),
+                                                                               VARSIZE_ANY_EXHDR(key));
+
+       if (v && v->type == hsvBool)
+               PG_RETURN_BOOL(v->boolean);
+
+       PG_RETURN_NULL();
+}
+
+PG_FUNCTION_INFO_V1(hstore_fetchval_n);
+Datum          hstore_fetchval_n(PG_FUNCTION_ARGS);
+Datum
+hstore_fetchval_n(PG_FUNCTION_ARGS)
+{
+       HStore          *hs = PG_GETARG_HS(0);
+       int                     i = PG_GETARG_INT32(1);
+       HStoreValue     *v = NULL;
+       text            *out;
+
+       if (!HS_ISEMPTY(hs))
+               v = getHStoreValue(VARDATA(hs), HS_FLAG_HSTORE | HS_FLAG_ARRAY, i);
+
+       if ((out = HStoreValueToText(v)) == NULL)
+               PG_RETURN_NULL();
+       else
+               PG_RETURN_TEXT_P(out);
+}
+
+PG_FUNCTION_INFO_V1(hstore_fetchval_n_numeric);
+Datum          hstore_fetchval_n_numeric(PG_FUNCTION_ARGS);
+Datum
+hstore_fetchval_n_numeric(PG_FUNCTION_ARGS)
+{
+       HStore          *hs = PG_GETARG_HS(0);
+       int                     i = PG_GETARG_INT32(1);
+       HStoreValue     *v = NULL;
+
+       if (!HS_ISEMPTY(hs))
+               v = getHStoreValue(VARDATA(hs), HS_FLAG_HSTORE | HS_FLAG_ARRAY, i);
+
+       if (v && v->type == hsvNumeric)
+       {
+               Numeric         out = palloc(VARSIZE_ANY(v->numeric));
+
+               memcpy(out, v->numeric, VARSIZE_ANY(v->numeric));
+               PG_RETURN_NUMERIC(out);
+       }
+
+       PG_RETURN_NULL();
+}
+
+PG_FUNCTION_INFO_V1(hstore_fetchval_n_boolean);
+Datum          hstore_fetchval_n_boolean(PG_FUNCTION_ARGS);
+Datum
+hstore_fetchval_n_boolean(PG_FUNCTION_ARGS)
+{
+       HStore          *hs = PG_GETARG_HS(0);
+       int                     i = PG_GETARG_INT32(1);
+       HStoreValue     *v = NULL;
+
+       if (!HS_ISEMPTY(hs))
+               v = getHStoreValue(VARDATA(hs), HS_FLAG_HSTORE | HS_FLAG_ARRAY, i);
+
+       if (v && v->type == hsvBool)
+               PG_RETURN_BOOL(v->boolean);
+
+       PG_RETURN_NULL();
+}
+
+static bool
+h_atoi(char *c, int l, int *acc)
+{
+       bool    negative = false;
+       char    *p = c;
+
+       *acc = 0;
+
+       while(isspace(*p) && p - c < l)
+               p++;
+
+       if (p - c >= l)
+               return false;
+
+       if (*p == '-')
+       {
+               negative = true;
+               p++;
+       }
+       else if (*p == '+')
+       {
+               p++;
+       }
+
+       if (p - c >= l)
+               return false;
+
+
+       while(p - c < l)
+       {
+               if (!isdigit(*p))
+                       return false;
+
+               *acc *= 10;
+               *acc += (*p - '0');
+               p++;
+       }
+
+       if (negative)
+               *acc = - *acc;
+
+       return true;
+}
+
+static HStoreValue*
+hstoreDeepFetch(HStore *in, ArrayType *path)
+{
+       HStoreValue                     *v = NULL;
+       static HStoreValue      init /* could be returned */;
+       Datum                           *path_elems;
+       bool                            *path_nulls;
+       int                                     path_len, i;
+
+       Assert(ARR_ELEMTYPE(path) == TEXTOID);
+
+       if (ARR_NDIM(path) > 1)
+               ereport(ERROR,
+                               (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+                                errmsg("wrong number of array subscripts")));
+
+       if (HS_ROOT_COUNT(in) == 0)
+               return NULL;
+
+       deconstruct_array(path, TEXTOID, -1, false, 'i',
+                                         &path_elems, &path_nulls, &path_len);
+
+       init.type = hsvBinary;
+       init.size = VARSIZE(in);
+       init.binary.data = VARDATA(in);
+       init.binary.len = VARSIZE_ANY_EXHDR(in);
+
+       v = &init;
+
+       if (path_len == 0)
+               return v;
+
+       for(i=0; v != NULL && i<path_len; i++)
+       {
+               uint32  header;
+
+               if (v->type != hsvBinary || path_nulls[i])
+                       return NULL;
+
+               header = *(uint32*)v->binary.data;
+
+               if (header & HS_FLAG_HSTORE)
+               {
+                       v = findUncompressedHStoreValue(v->binary.data, HS_FLAG_HSTORE,
+                                                                                       NULL,
+                                                                                       VARDATA_ANY(path_elems[i]),
+                                                                                       VARSIZE_ANY_EXHDR(path_elems[i]));
+               }
+               else if (header & HS_FLAG_ARRAY)
+               {
+                       int ith;
+
+                       if (h_atoi(VARDATA_ANY(path_elems[i]),
+                                          VARSIZE_ANY_EXHDR(path_elems[i]), &ith) == false)
+                               return NULL;
+
+                       if (ith < 0)
+                       {
+                               if (-ith > (int)(header & HS_COUNT_MASK))
+                                       return NULL;
+                               else
+                                       ith = ((int)(header & HS_COUNT_MASK)) + ith;
+                       }
+                       else
+                       {
+                               if (ith >= (int)(header & HS_COUNT_MASK))
+                                       return NULL;
+                       }
+
+                       v = getHStoreValue(v->binary.data, HS_FLAG_ARRAY, ith);
+               }
+               else
+               {
+                       elog(PANIC,"wrong header type: %08x", header);
+               }
+       }
+
+       return v;
+}
+
+PG_FUNCTION_INFO_V1(hstore_fetchval_path);
+Datum          hstore_fetchval_path(PG_FUNCTION_ARGS);
+Datum
+hstore_fetchval_path(PG_FUNCTION_ARGS)
+{
+       HStore          *hs = PG_GETARG_HS(0);
+       ArrayType       *path = PG_GETARG_ARRAYTYPE_P(1);
+       text            *out;
+
+       if ((out = HStoreValueToText(hstoreDeepFetch(hs, path))) == NULL)
+               PG_RETURN_NULL();
+       else
+               PG_RETURN_TEXT_P(out);
+}
+
+PG_FUNCTION_INFO_V1(hstore_fetchval_path_numeric);
+Datum          hstore_fetchval_path_numeric(PG_FUNCTION_ARGS);
+Datum
+hstore_fetchval_path_numeric(PG_FUNCTION_ARGS)
+{
+       HStore          *hs = PG_GETARG_HS(0);
+       ArrayType       *path = PG_GETARG_ARRAYTYPE_P(1);
+       HStoreValue     *v = NULL;
+
+       if (!HS_ISEMPTY(hs))
+               v = hstoreDeepFetch(hs, path);
+
+       if (v && v->type == hsvNumeric)
+       {
+               Numeric         out = palloc(VARSIZE_ANY(v->numeric));
+
+               memcpy(out, v->numeric, VARSIZE_ANY(v->numeric));
+               PG_RETURN_NUMERIC(out);
+       }
+
+       PG_RETURN_NULL();
+}
+
+PG_FUNCTION_INFO_V1(hstore_fetchval_path_boolean);
+Datum          hstore_fetchval_path_boolean(PG_FUNCTION_ARGS);
+Datum
+hstore_fetchval_path_boolean(PG_FUNCTION_ARGS)
+{
+       HStore          *hs = PG_GETARG_HS(0);
+       ArrayType       *path = PG_GETARG_ARRAYTYPE_P(1);
+       HStoreValue     *v = NULL;
+
+       if (!HS_ISEMPTY(hs))
+               v = hstoreDeepFetch(hs, path);
+
+       if (v && v->type == hsvBool)
+               PG_RETURN_BOOL(v->boolean);
+
+       PG_RETURN_NULL();
+}
+
+static HStore *
+HStoreValueToHStore(HStoreValue *v)
+{
+       HStore                  *out;
+
+       if (v == NULL || v->type == hsvNull)
+       {
+               out = NULL;
+       }
+       else if (v->type == hsvString || v->type == hsvBool ||
+                        v->type == hsvNumeric)
+       {
+               ToHStoreState   *state = NULL;
+               HStoreValue             *res;
+               int                             r;
+               HStoreValue             scalarArray;
+
+               scalarArray.type = hsvArray;
+               scalarArray.array.scalar = true;
+               scalarArray.array.nelems = 1;
+
+               pushHStoreValue(&state, WHS_BEGIN_ARRAY, &scalarArray);
+               pushHStoreValue(&state, WHS_ELEM, v);
+               res = pushHStoreValue(&state, WHS_END_ARRAY, NULL);
+
+               out = palloc(VARHDRSZ + res->size);
+               SET_VARSIZE(out, VARHDRSZ + res->size);
+               r = compressHStore(res, VARDATA(out));
+               Assert(r <= res->size);
+               SET_VARSIZE(out, r + VARHDRSZ);
+       }
+       else
+       {
+               out = palloc(VARHDRSZ + v->size);
+
+               Assert(v->type == hsvBinary);
+               SET_VARSIZE(out, VARHDRSZ + v->binary.len);
+               memcpy(VARDATA(out), v->binary.data, v->binary.len);
+       }
+
+       return out;
+}
+
+PG_FUNCTION_INFO_V1(hstore_fetchval_hstore);
+Datum          hstore_fetchval_hstore(PG_FUNCTION_ARGS);
+Datum
+hstore_fetchval_hstore(PG_FUNCTION_ARGS)
+{
+       HStore          *hs = PG_GETARG_HS(0);
+       text            *key = PG_GETARG_TEXT_PP(1);
+       HStoreValue     *v = NULL;
+       HStore          *out;
+
+       if (!HS_ISEMPTY(hs))
+               v = findUncompressedHStoreValue(VARDATA(hs),
+                                                                               HS_FLAG_HSTORE | HS_FLAG_ARRAY,
+                                                                               NULL,
+                                                                               VARDATA_ANY(key),
+                                                                               VARSIZE_ANY_EXHDR(key));
+
+
+       if ((out = HStoreValueToHStore(v)) == NULL)
+               PG_RETURN_NULL();
+       else
+               PG_RETURN_POINTER(out);
+}
+
+PG_FUNCTION_INFO_V1(hstore_fetchval_n_hstore);
+Datum          hstore_fetchval_n_hstore(PG_FUNCTION_ARGS);
+Datum
+hstore_fetchval_n_hstore(PG_FUNCTION_ARGS)
+{
+       HStore          *hs = PG_GETARG_HS(0);
+       int                     i = PG_GETARG_INT32(1);
+       HStoreValue     *v = NULL;
+       HStore          *out;
+
+       if (!HS_ISEMPTY(hs))
+               v = getHStoreValue(VARDATA(hs), HS_FLAG_HSTORE | HS_FLAG_ARRAY, i);
+
+       if ((out = HStoreValueToHStore(v)) == NULL)
+               PG_RETURN_NULL();
+       else
+               PG_RETURN_POINTER(out);
+}
+
+PG_FUNCTION_INFO_V1(hstore_fetchval_path_hstore);
+Datum          hstore_fetchval_path_hstore(PG_FUNCTION_ARGS);
+Datum
+hstore_fetchval_path_hstore(PG_FUNCTION_ARGS)
+{
+       HStore          *hs = PG_GETARG_HS(0);
+       ArrayType       *path = PG_GETARG_ARRAYTYPE_P(1);
+       HStore          *out;
+
+       if ((out = HStoreValueToHStore(hstoreDeepFetch(hs, path))) == NULL)
+               PG_RETURN_NULL();
+       else
+               PG_RETURN_POINTER(out);
+}
+
+PG_FUNCTION_INFO_V1(hstore_exists);
+Datum          hstore_exists(PG_FUNCTION_ARGS);
+Datum
+hstore_exists(PG_FUNCTION_ARGS)
+{
+       HStore          *hs = PG_GETARG_HS(0);
+       text            *key = PG_GETARG_TEXT_PP(1);
+       HStoreValue     *v = NULL;
+
+       if (!HS_ISEMPTY(hs))
+               v = findUncompressedHStoreValue(VARDATA(hs),
+                                                                               HS_FLAG_HSTORE | HS_FLAG_ARRAY,
+                                                                               NULL,
+                                                                               VARDATA_ANY(key),
+                                                                               VARSIZE_ANY_EXHDR(key));
+
+       PG_RETURN_BOOL(v != NULL);
+}
+
+
+PG_FUNCTION_INFO_V1(hstore_exists_idx);
+Datum          hstore_exists_idx(PG_FUNCTION_ARGS);
+Datum
+hstore_exists_idx(PG_FUNCTION_ARGS)
+{
+       HStore          *hs = PG_GETARG_HS(0);
+       int                     ith = PG_GETARG_INT32(1);
+       HStoreValue     *v = NULL;
+
+       if (!HS_ISEMPTY(hs))
+               v = getHStoreValue(VARDATA(hs), HS_FLAG_HSTORE | HS_FLAG_ARRAY, ith);
+
+       PG_RETURN_BOOL(v != NULL);
+}
+
+PG_FUNCTION_INFO_V1(hstore_exists_path);
+Datum          hstore_exists_path(PG_FUNCTION_ARGS);
+Datum
+hstore_exists_path(PG_FUNCTION_ARGS)
+{
+       HStore          *hs = PG_GETARG_HS(0);
+       ArrayType       *path = PG_GETARG_ARRAYTYPE_P(1);
+
+       PG_RETURN_BOOL(hstoreDeepFetch(hs, path) != NULL);
+}
+
+
+
+PG_FUNCTION_INFO_V1(hstore_exists_any);
+Datum          hstore_exists_any(PG_FUNCTION_ARGS);
+Datum
+hstore_exists_any(PG_FUNCTION_ARGS)
+{
+       HStore                  *hs = PG_GETARG_HS(0);
+       ArrayType               *keys = PG_GETARG_ARRAYTYPE_P(1);
+       HStoreValue             *v = arrayToHStoreSortedArray(keys);
+       int                             i;
+       uint32                  *plowbound = NULL, lowbound = 0;
+       bool                    res = false;
+
+       if (HS_ISEMPTY(hs) || v == NULL || v->hash.npairs == 0)
+               PG_RETURN_BOOL(false);
+
+       if (HS_ROOT_IS_HASH(hs))
+               plowbound = &lowbound;
+       /*
+        * we exploit the fact that the pairs list is already sorted into strictly
+        * increasing order to narrow the findUncompressedHStoreValue search; each search can
+        * start one entry past the previous "found" entry, or at the lower bound
+        * of the last search.
+        */
+       for (i = 0; i < v->array.nelems; i++)
+       {
+               if (findUncompressedHStoreValueByValue(VARDATA(hs), HS_FLAG_HSTORE | HS_FLAG_ARRAY, plowbound,
+                                                                                          v->array.elems + i) != NULL)
+               {
+                       res = true;
+                       break;
+               }
+       }
+
+       PG_RETURN_BOOL(res);
+}
+
+
+PG_FUNCTION_INFO_V1(hstore_exists_all);
+Datum          hstore_exists_all(PG_FUNCTION_ARGS);
+Datum
+hstore_exists_all(PG_FUNCTION_ARGS)
+{
+       HStore                  *hs = PG_GETARG_HS(0);
+       ArrayType               *keys = PG_GETARG_ARRAYTYPE_P(1);
+       HStoreValue             *v = arrayToHStoreSortedArray(keys);
+       int                             i;
+       uint32                  *plowbound = NULL, lowbound = 0;
+       bool                    res = true;
+
+       if (HS_ISEMPTY(hs) || v == NULL || v->array.nelems == 0)
+       {
+
+               if (v == NULL || v->array.nelems == 0)
+                       PG_RETURN_BOOL(true); /* compatibility */
+               else
+                       PG_RETURN_BOOL(false);
+       }
+
+       if (HS_ROOT_IS_HASH(hs))
+               plowbound = &lowbound;
+       /*
+        * we exploit the fact that the pairs list is already sorted into strictly
+        * increasing order to narrow the findUncompressedHStoreValue search;
+        * each search can start one entry past the previous "found" entry,
+        * or at the lower bound of the last search.
+        */
+       for (i = 0; i < v->array.nelems; i++)
+       {
+               if (findUncompressedHStoreValueByValue(VARDATA(hs),
+                                                                                          HS_FLAG_HSTORE | HS_FLAG_ARRAY,
+                                                                                          plowbound,
+                                                                                          v->array.elems + i) == NULL)
+               {
+                       res = false;
+                       break;
+               }
+       }
+
+       PG_RETURN_BOOL(res);
+}
+
+
+PG_FUNCTION_INFO_V1(hstore_defined);
+Datum          hstore_defined(PG_FUNCTION_ARGS);
+Datum
+hstore_defined(PG_FUNCTION_ARGS)
+{
+       HStore          *hs = PG_GETARG_HS(0);
+       text            *key = PG_GETARG_TEXT_PP(1);
+       HStoreValue     *v = NULL;
+
+       if (!HS_ISEMPTY(hs))
+               v = findUncompressedHStoreValue(VARDATA(hs),
+                                                                               HS_FLAG_HSTORE | HS_FLAG_ARRAY,
+                                                                               NULL,
+                                                                               VARDATA_ANY(key),
+                                                                               VARSIZE_ANY_EXHDR(key));
+
+       PG_RETURN_BOOL(!(v == NULL || v->type == hsvNull));
+}
+
+
+PG_FUNCTION_INFO_V1(hstore_delete);
+Datum          hstore_delete(PG_FUNCTION_ARGS);
+Datum
+hstore_delete(PG_FUNCTION_ARGS)
+{
+       HStore                  *in = PG_GETARG_HS(0);
+       text                    *key = PG_GETARG_TEXT_PP(1);
+       char                    *keyptr = VARDATA_ANY(key);
+       int                             keylen = VARSIZE_ANY_EXHDR(key);
+       HStore                  *out = palloc(VARSIZE(in));
+       ToHStoreState   *toState = NULL;
+       HStoreIterator  *it;
+       uint32                  r;
+       HStoreValue             v, *res = NULL;
+       bool                    skipNested = false;
+
+       SET_VARSIZE(out, VARSIZE(in));
+
+       if (HS_ISEMPTY(in))
+               PG_RETURN_POINTER(out);
+
+       it = HStoreIteratorInit(VARDATA(in));
+
+       while((r = HStoreIteratorGet(&it, &v, skipNested)) != 0)
+       {
+               skipNested = true;
+
+               if ((r == WHS_ELEM || r == WHS_KEY) &&
+                       (v.type == hsvString && keylen == v.string.len &&
+                        memcmp(keyptr, v.string.val, keylen) == 0))
+               {
+                       if (r == WHS_KEY)
+                               /* skip corresponding value */
+                               HStoreIteratorGet(&it, &v, true);
+
+                       continue;
+               }
+
+               res = pushHStoreValue(&toState, r, &v);
+       }
+
+       if (res == NULL || (res->type == hsvArray && res->array.nelems == 0) ||
+                                          (res->type == hsvHash && res->hash.npairs == 0) )
+       {
+               SET_VARSIZE(out, VARHDRSZ);
+       }
+       else
+       {
+               r = compressHStore(res, VARDATA(out));
+               SET_VARSIZE(out, r + VARHDRSZ);
+       }
+
+       PG_RETURN_POINTER(out);
+}
+
+PG_FUNCTION_INFO_V1(hstore_delete_array);
+Datum          hstore_delete_array(PG_FUNCTION_ARGS);
+Datum
+hstore_delete_array(PG_FUNCTION_ARGS)
+{
+       HStore                  *in = PG_GETARG_HS(0);
+       HStore                  *out = palloc(VARSIZE(in));
+       HStoreValue     *a = arrayToHStoreSortedArray(PG_GETARG_ARRAYTYPE_P(1));
+       HStoreIterator  *it;
+       ToHStoreState   *toState = NULL;
+       uint32                  r, i = 0;
+       HStoreValue             v, *res = NULL;
+       bool                    skipNested = false;
+       bool                    isHash = false;
+
+
+       if (HS_ISEMPTY(in) || a == NULL || a->array.nelems == 0)
+       {
+               memcpy(out, in, VARSIZE(in));
+               PG_RETURN_POINTER(out);
+       }
+
+       it = HStoreIteratorInit(VARDATA(in));
+
+       while((r = HStoreIteratorGet(&it, &v, skipNested)) != 0)
+       {
+
+               if (skipNested == false)
+               {
+                       Assert(v.type == hsvArray || v.type == hsvHash);
+                       isHash = (v.type == hsvArray) ? false : true;
+                       skipNested = true;
+               }
+
+               if ((r == WHS_ELEM || r == WHS_KEY) && v.type == hsvString &&
+                       i < a->array.nelems)
+               {
+                       int diff;
+
+                       if (isHash)
+                       {
+                               do {
+                                       diff = compareHStoreStringValue(&v, a->array.elems + i,
+                                                                                                       NULL);
+
+                                       if (diff >= 0)
+                                               i++;
+                               } while(diff > 0 && i < a->array.nelems);
+                       }
+                       else
+                       {
+                               diff = (findInHStoreSortedArray(a, NULL,
+                                                                                               v.string.val,
+                                                                                               v.string.len) == NULL) ? 1 : 0;
+                       }
+
+                       if (diff == 0)
+                       {
+                               if (r == WHS_KEY)
+                                       /* skip corresponding value */
+                                       HStoreIteratorGet(&it, &v, true);
+
+                               continue;
+                       }
+               }
+
+               res = pushHStoreValue(&toState, r, &v);
+       }
+
+       if (res == NULL || (res->type == hsvArray && res->array.nelems == 0) ||
+                                          (res->type == hsvHash && res->hash.npairs == 0) )
+       {
+               SET_VARSIZE(out, VARHDRSZ);
+       }
+       else
+       {
+               r = compressHStore(res, VARDATA(out));
+               SET_VARSIZE(out, r + VARHDRSZ);
+       }
+
+       PG_RETURN_POINTER(out);
+}
+
+
+PG_FUNCTION_INFO_V1(hstore_delete_hstore);
+Datum          hstore_delete_hstore(PG_FUNCTION_ARGS);
+Datum
+hstore_delete_hstore(PG_FUNCTION_ARGS)
+{
+       HStore                  *hs1 = PG_GETARG_HS(0);
+       HStore                  *hs2 = PG_GETARG_HS(1);
+       HStore                  *out = palloc(VARSIZE(hs1));
+       HStoreIterator  *it1, *it2;
+       ToHStoreState   *toState = NULL;
+       uint32                  r1, r2;
+       HStoreValue             v1, v2, *res = NULL;
+       bool                    isHash1, isHash2;
+
+       if (HS_ISEMPTY(hs1) || HS_ISEMPTY(hs2))
+       {
+               memcpy(out, hs1, VARSIZE(hs1));
+               PG_RETURN_POINTER(out);
+       }
+
+       it1 = HStoreIteratorInit(VARDATA(hs1));
+       r1 = HStoreIteratorGet(&it1, &v1, false);
+       isHash1 = (v1.type == hsvArray) ? false : true;
+
+       it2 = HStoreIteratorInit(VARDATA(hs2));
+       r2 = HStoreIteratorGet(&it2, &v2, false);
+       isHash2 = (v2.type == hsvArray) ? false : true;
+
+       res = pushHStoreValue(&toState, r1, &v1);
+
+       if (isHash1 == true && isHash2 == true)
+       {
+               bool                    fin2 = false,
+                                               keyIsDef = false;
+
+               while((r1 = HStoreIteratorGet(&it1, &v1, true)) != 0)
+               {
+                       if (r1 == WHS_KEY && fin2 == false)
+                       {
+                               int diff  = 1;
+
+                               if (keyIsDef)
+                                       r2 = WHS_KEY;
+
+                               while(keyIsDef ||
+                                         (r2 = HStoreIteratorGet(&it2, &v2, true)) != 0)
+                               {
+                                       if (r2 != WHS_KEY)
+                                               continue;
+
+                                       diff = compareHStoreStringValue(&v1, &v2, NULL);
+
+                                       if (diff > 0 && keyIsDef)
+                                               keyIsDef = false;
+                                       if (diff <= 0)
+                                               break;
+                               }
+
+                               if (r2 == 0)
+                               {
+                                       fin2 = true;
+                               }
+                               else if (diff == 0)
+                               {
+                                       HStoreValue             vk;
+
+                                       keyIsDef = false;
+
+                                       r1 = HStoreIteratorGet(&it1, &vk, true);
+                                       r2 = HStoreIteratorGet(&it2, &v2, true);
+
+                                       Assert(r1 == WHS_VALUE && r2 == WHS_VALUE);
+
+                                       if (compareHStoreValue(&vk, &v2) != 0)
+                                       {
+                                               res = pushHStoreValue(&toState, WHS_KEY, &v1);
+                                               res = pushHStoreValue(&toState, WHS_VALUE, &vk);
+                                       }
+
+                                       continue;
+                               }
+                               else
+                               {
+                                       keyIsDef = true;
+                               }
+                       }
+
+                       res = pushHStoreValue(&toState, r1, &v1);
+               }
+       }
+       else
+       {
+               while((r1 = HStoreIteratorGet(&it1, &v1, true)) != 0)
+               {
+
+                       if (r1 == WHS_ELEM || r1 == WHS_KEY)
+                       {
+                               int diff = 1;
+
+                               it2 = HStoreIteratorInit(VARDATA(hs2));
+
+                               r2 = HStoreIteratorGet(&it2, &v2, false);
+
+                               while(diff && (r2 = HStoreIteratorGet(&it2, &v2, true)) != 0)
+                               {
+                                       if (r2 == WHS_KEY || r2 == WHS_VALUE || r2 == WHS_ELEM)
+                                               diff = compareHStoreValue(&v1, &v2);
+                               }
+
+                               if (diff == 0)
+                               {
+                                       if (r1 == WHS_KEY)
+                                               HStoreIteratorGet(&it1, &v1, true);
+                                       continue;
+                               }
+                       }
+
+                       res = pushHStoreValue(&toState, r1, &v1);
+               }
+       }
+
+       if (res == NULL || (res->type == hsvArray && res->array.nelems == 0) ||
+                                          (res->type == hsvHash && res->hash.npairs == 0) )
+       {
+               SET_VARSIZE(out, VARHDRSZ);
+       }
+       else
+       {
+               int r = compressHStore(res, VARDATA(out));
+               SET_VARSIZE(out, r + VARHDRSZ);
+       }
+
+       PG_RETURN_POINTER(out);
+}
+
+static HStoreValue*
+deletePathDo(HStoreIterator **it, Datum        *path_elems,
+                        bool *path_nulls, int path_len,
+                        ToHStoreState  **st, int level)
+{
+       HStoreValue     v, *res = NULL;
+       int                     r;
+
+       r = HStoreIteratorGet(it, &v, false);
+
+       if (r == WHS_BEGIN_ARRAY)
+       {
+               int     skipIdx, i;
+               uint32  n = v.array.nelems;
+
+               skipIdx = n;
+               if (level >= path_len || path_nulls[level] ||
+                       h_atoi(VARDATA_ANY(path_elems[level]),
+                                  VARSIZE_ANY_EXHDR(path_elems[level]), &skipIdx) == false)
+               {
+                       skipIdx = n;
+               }
+               else if (skipIdx < 0)
+               {
+                       if (-skipIdx > n)
+                               skipIdx = n;
+                       else
+                               skipIdx = n + skipIdx;
+               }
+
+               if (skipIdx > n)
+                       skipIdx = n;
+
+               if (skipIdx == 0 && n == 1)
+               {
+                       r = HStoreIteratorGet(it, &v, true);
+                       Assert(r == WHS_ELEM);
+                       r = HStoreIteratorGet(it, &v, true);
+                       Assert(r == WHS_END_ARRAY);
+                       return NULL;
+               }
+
+               pushHStoreValue(st, r, &v);
+
+               for(i=0; i<skipIdx; i++) {
+                       r = HStoreIteratorGet(it, &v, true);
+                       Assert(r == WHS_ELEM);
+                       res = pushHStoreValue(st, r, &v);
+               }
+
+               if (level >= path_len || skipIdx == n) {
+                       r = HStoreIteratorGet(it, &v, true);
+                       Assert(r == WHS_END_ARRAY);
+                       res = pushHStoreValue(st, r, &v);
+                       return res;
+               }
+
+               if (level == path_len - 1)
+               {
+                       /* last level in path, skip all elem */
+                       r = HStoreIteratorGet(it, &v, true);
+                       Assert(r == WHS_ELEM);
+               }
+               else
+               {
+                       res = deletePathDo(it, path_elems, path_nulls, path_len, st,
+                                                          level + 1);
+               }
+
+               for(i = skipIdx + 1; i<n; i++) {
+                       r = HStoreIteratorGet(it, &v, true);
+                       Assert(r == WHS_ELEM);
+                       res = pushHStoreValue(st, r, &v);
+               }
+
+               r = HStoreIteratorGet(it, &v, true);
+               Assert(r == WHS_END_ARRAY);
+               res = pushHStoreValue(st, r, &v);
+       }
+       else if (r == WHS_BEGIN_HASH)
+       {
+               int                     i;
+               uint32          n = v.hash.npairs;
+               HStoreValue     k;
+               bool            done = false;
+
+               if (n == 1 && level == path_len - 1)
+               {
+                       r = HStoreIteratorGet(it, &k, false);
+                       Assert(r == WHS_KEY);
+
+                       if ( path_nulls[level] == false &&
+                                k.string.len == VARSIZE_ANY_EXHDR(path_elems[level]) &&
+                                memcmp(k.string.val, VARDATA_ANY(path_elems[level]),
+                                               k.string.len) == 0)
+                       {
+                               r = HStoreIteratorGet(it, &v, true);
+                               Assert(r == WHS_VALUE);
+                               r = HStoreIteratorGet(it, &v, true);
+                               Assert(r == WHS_END_HASH);
+                               return NULL;
+                       }
+
+                       pushHStoreValue(st, WHS_BEGIN_HASH, &v);
+                       pushHStoreValue(st, WHS_KEY, &k);
+                       r = HStoreIteratorGet(it, &v, true);
+                       Assert(r == WHS_VALUE);
+                       pushHStoreValue(st, r, &v);
+                       r = HStoreIteratorGet(it, &v, true);
+                       Assert(r == WHS_END_HASH);
+                       return pushHStoreValue(st, r, &v);
+               }
+
+               pushHStoreValue(st, WHS_BEGIN_HASH, &v);
+
+               if (level >= path_len || path_nulls[level])
+                       done = true;
+
+               for(i=0; i<n; i++)
+               {
+                       r = HStoreIteratorGet(it, &k, false);
+                       Assert(r == WHS_KEY);
+
+                       if (done == false &&
+                               k.string.len == VARSIZE_ANY_EXHDR(path_elems[level]) &&
+                               memcmp(k.string.val, VARDATA_ANY(path_elems[level]),
+                                          k.string.len) == 0)
+                       {
+                               done = true;
+
+                               if (level == path_len - 1)
+                               {
+                                       r = HStoreIteratorGet(it, &v, true);
+                                       Assert(r == WHS_VALUE);
+                               }
+                               else
+                               {
+                                       pushHStoreValue(st, r, &k);
+                                       res = deletePathDo(it, path_elems, path_nulls, path_len,
+                                                                          st, level + 1);
+                                       if (res == NULL)
+                                       {
+                                               v.type = hsvNull;
+                                               pushHStoreValue(st, WHS_VALUE, &v);
+                                       }
+                               }
+
+                               continue;
+                       }
+
+                       pushHStoreValue(st, r, &k);
+                       r = HStoreIteratorGet(it, &v, true);
+                       Assert(r == WHS_VALUE);
+                       pushHStoreValue(st, r, &v);
+               }
+
+               r = HStoreIteratorGet(it, &v, true);
+               Assert(r == WHS_END_HASH);
+               res = pushHStoreValue(st, r, &v);
+       }
+       else if (r == WHS_ELEM || r == WHS_VALUE) /* just a string or null */
+       {
+               pushHStoreValue(st, r, &v);
+               res = (void*)0x01; /* dummy value */
+       }
+       else
+       {
+               elog(PANIC, "impossible state");
+       }
+
+       return res;
+}
+
+
+PG_FUNCTION_INFO_V1(hstore_delete_path);
+Datum          hstore_delete_path(PG_FUNCTION_ARGS);
+Datum
+hstore_delete_path(PG_FUNCTION_ARGS)
+{
+       HStore                  *in = PG_GETARG_HS(0);
+       HStore                  *out = palloc(VARSIZE(in));
+       ArrayType               *path = PG_GETARG_ARRAYTYPE_P(1);
+       HStoreValue             *res = NULL;
+       Datum                   *path_elems;
+       bool                    *path_nulls;
+       int                             path_len;
+       HStoreIterator  *it;
+       ToHStoreState   *st = NULL;
+
+       Assert(ARR_ELEMTYPE(path) == TEXTOID);
+
+       if (ARR_NDIM(path) > 1)
+               ereport(ERROR,
+                               (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+                                errmsg("wrong number of array subscripts")));
+
+       if (HS_ROOT_COUNT(in) == 0)
+       {
+               memcpy(out, in, VARSIZE(in));
+               PG_RETURN_POINTER(out);
+       }
+
+       deconstruct_array(path, TEXTOID, -1, false, 'i',
+                                         &path_elems, &path_nulls, &path_len);
+
+       if (path_len == 0)
+       {
+               memcpy(out, in, VARSIZE(in));
+               PG_RETURN_POINTER(out);
+       }
+
+       it = HStoreIteratorInit(VARDATA(in));
+
+       res = deletePathDo(&it, path_elems, path_nulls, path_len, &st, 0);
+
+       if (res == NULL)
+       {
+               SET_VARSIZE(out, VARHDRSZ);
+       }
+       else
+       {
+               int                             sz;
+
+               sz = compressHStore(res, VARDATA(out));
+               SET_VARSIZE(out, sz + VARHDRSZ);
+       }
+
+       PG_RETURN_POINTER(out);
+}
+
+PG_FUNCTION_INFO_V1(hstore_delete_idx);
+Datum          hstore_delete_idx(PG_FUNCTION_ARGS);
+Datum
+hstore_delete_idx(PG_FUNCTION_ARGS)
+{
+       HStore                  *in = PG_GETARG_HS(0);
+       int                             idx = PG_GETARG_INT32(1);
+       HStore                  *out = palloc(VARSIZE(in));
+       ToHStoreState   *toState = NULL;
+       HStoreIterator  *it;
+       uint32                  r, i = 0, n;
+       HStoreValue             v, *res = NULL;
+
+       if (HS_ISEMPTY(in))
+       {
+               memcpy(out, in, VARSIZE(in));
+               PG_RETURN_POINTER(out);
+       }
+
+       it = HStoreIteratorInit(VARDATA(in));
+
+       r = HStoreIteratorGet(&it, &v, false);
+       if (r == WHS_BEGIN_ARRAY)
+               n = v.array.nelems;
+       else
+               n = v.hash.npairs;
+
+       if (idx < 0)
+       {
+               if (-idx > n)
+                       idx = n;
+               else
+                       idx = n + idx;
+       }
+
+       if (idx >= n)
+       {
+               memcpy(out, in, VARSIZE(in));
+               PG_RETURN_POINTER(out);
+       }
+
+       pushHStoreValue(&toState, r, &v);
+
+       while((r = HStoreIteratorGet(&it, &v, true)) != 0)
+       {
+               if (r == WHS_ELEM || r == WHS_KEY)
+               {
+                       if (i++ == idx)
+                       {
+                               if (r == WHS_KEY)
+                                       HStoreIteratorGet(&it, &v, true); /* skip value */
+                               continue;
+                       }
+               }
+
+               res = pushHStoreValue(&toState, r, &v);
+       }
+
+       if (res == NULL || (res->type == hsvArray && res->array.nelems == 0) ||
+                                          (res->type == hsvHash && res->hash.npairs == 0) )
+       {
+               SET_VARSIZE(out, VARHDRSZ);
+       }
+       else
+       {
+               r = compressHStore(res, VARDATA(out));
+               SET_VARSIZE(out, r + VARHDRSZ);
+       }
+
+       PG_RETURN_POINTER(out);
+}
+
+static void
+convertScalarToString(HStoreValue *v)
+{
+       switch(v->type) {
+               case hsvNull:
+                       elog(ERROR, "key in hstore type could not be a NULL");
+                       break;
+               case hsvBool:
+                       v->type = hsvString;
+                       v->string.val = pnstrdup((v->boolean) ? "t" : "f", 1);
+                       v->string.len = 1;
+                       v->size = sizeof(HEntry) + v->string.len;
+                       break;
+               case hsvNumeric:
+                       v->type = hsvString;
+                       v->string.val = DatumGetCString(
+                                                       DirectFunctionCall1(numeric_out,
+                                                                                               PointerGetDatum(v->numeric)));
+                       v->string.len = strlen(v->string.val);
+                       v->size = sizeof(HEntry) + v->string.len;
+                       break;
+               case hsvString:
+                       break;
+               default:
+                       elog(PANIC,"Could not convert to string");
+       }
+}
+
+static HStoreValue *
+IteratorConcat(HStoreIterator **it1, HStoreIterator **it2,
+                          ToHStoreState **toState)
+{
+       uint32                  r1, r2, rk1, rk2;
+       HStoreValue             v1, v2, *res = NULL;
+
+       r1 = rk1 = HStoreIteratorGet(it1, &v1, false);
+       r2 = rk2 = HStoreIteratorGet(it2, &v2, false);
+
+       if (rk1 == WHS_BEGIN_HASH && rk2 == WHS_BEGIN_HASH)
+       {
+               bool                    fin2 = false,
+                                               keyIsDef = false;
+
+               res = pushHStoreValue(toState, r1, &v1);
+
+               for(;;)
+               {
+                       r1 = HStoreIteratorGet(it1, &v1, true);
+
+                       Assert(r1 == WHS_KEY || r1 == WHS_VALUE || r1 == WHS_END_HASH);
+
+                       if (r1 == WHS_KEY && fin2 == false)
+                       {
+                               int diff  = 1;
+
+                               if (keyIsDef)
+                                       r2 = WHS_KEY;
+
+                               while(keyIsDef || (r2 = HStoreIteratorGet(it2, &v2, true)) != 0)
+                               {
+                                       if (r2 != WHS_KEY)
+                                               continue;
+
+                                       diff = compareHStoreStringValue(&v1, &v2, NULL);
+
+                                       if (diff > 0)
+                                       {
+                                               if (keyIsDef)
+                                                       keyIsDef = false;
+
+                                               pushHStoreValue(toState, r2, &v2);
+                                               r2 = HStoreIteratorGet(it2, &v2, true);
+                                               Assert(r2 == WHS_VALUE);
+                                               pushHStoreValue(toState, r2, &v2);
+                                       }
+                                       else if (diff <= 0)
+                                       {
+                                               break;
+                                       }
+                               }
+
+                               if (r2 == 0)
+                               {
+                                       fin2 = true;
+                               }
+                               else if (diff == 0)
+                               {
+                                       keyIsDef = false;
+
+                                       pushHStoreValue(toState, r1, &v1);
+
+                                       r1 = HStoreIteratorGet(it1, &v1, true); /* ignore */
+                                       r2 = HStoreIteratorGet(it2, &v2, true); /* new val */
+
+                                       Assert(r1 == WHS_VALUE && r2 == WHS_VALUE);
+                                       pushHStoreValue(toState, r2, &v2);
+
+                                       continue;
+                               }
+                               else
+                               {
+                                       keyIsDef = true;
+                               }
+                       }
+                       else if (r1 == WHS_END_HASH)
+                       {
+                               if (r2 != 0)
+                               {
+                                       if (keyIsDef)
+                                               r2 = WHS_KEY;
+
+                                       while(keyIsDef ||
+                                                 (r2 = HStoreIteratorGet(it2, &v2, true)) != 0)
+                                       {
+                                               if (r2 != WHS_KEY)
+                                                       continue;
+
+                                               pushHStoreValue(toState, r2, &v2);
+                                               r2 = HStoreIteratorGet(it2, &v2, true);
+                                               Assert(r2 == WHS_VALUE);
+                                               pushHStoreValue(toState, r2, &v2);
+                                               keyIsDef = false;
+                                       }
+                               }
+
+                               res = pushHStoreValue(toState, r1, &v1);
+                               break;
+                       }
+
+                       res = pushHStoreValue(toState, r1, &v1);
+               }
+       }
+       else if ((rk1 == WHS_BEGIN_HASH || rk1 == WHS_BEGIN_ARRAY) &&
+                        (rk2 == WHS_BEGIN_HASH || rk2 == WHS_BEGIN_ARRAY))
+       {
+               if (rk1 == WHS_BEGIN_HASH && rk2 == WHS_BEGIN_ARRAY &&
+                       v2.array.nelems % 2 != 0)
+                       elog(ERROR, "hstore's array must have even number of elements");
+
+               res = pushHStoreValue(toState, r1, &v1);
+
+               for(;;)
+               {
+                       r1 = HStoreIteratorGet(it1, &v1, true);
+                       if (r1 == WHS_END_HASH || r1 == WHS_END_ARRAY)
+                               break;
+                       Assert(r1 == WHS_KEY || r1 == WHS_VALUE || r1 == WHS_ELEM);
+                       pushHStoreValue(toState, r1, &v1);
+               }
+
+               while((r2 = HStoreIteratorGet(it2, &v2, true)) != 0)
+               {
+                       if (!(r2 == WHS_END_HASH || r2 == WHS_END_ARRAY))
+                       {
+                               if (rk1 == WHS_BEGIN_HASH)
+                               {
+                                       convertScalarToString(&v2);
+                                       pushHStoreValue(toState, WHS_KEY, &v2);
+                                       r2 = HStoreIteratorGet(it2, &v2, true);
+                                       Assert(r2 == WHS_ELEM);
+                                       pushHStoreValue(toState, WHS_VALUE, &v2);
+                               }
+                               else
+                               {
+                                       pushHStoreValue(toState, WHS_ELEM, &v2);
+                               }
+                       }
+               }
+
+               res = pushHStoreValue(toState,
+                                                         (rk1 == WHS_BEGIN_HASH) ? WHS_END_HASH : WHS_END_ARRAY,
+                                                         NULL/* signal to sort */);
+       }
+       else if ((rk1 & (WHS_VALUE | WHS_ELEM)) != 0)
+       {
+               if (v2.type == hsvArray && v2.array.scalar)
+               {
+                       Assert(v2.array.nelems == 1);
+                       r2 = HStoreIteratorGet(it2, &v2, false);
+                       pushHStoreValue(toState, r1, &v2);
+               }
+               else
+               {
+                       res = pushHStoreValue(toState, r2, &v2);
+                       while((r2 = HStoreIteratorGet(it2, &v2, true)) != 0)
+                               res = pushHStoreValue(toState, r2, &v2);
+               }
+       }
+       else
+       {
+               elog(ERROR, "invalid concatnation of hstores");
+       }
+
+       return res;
+}
+
+PG_FUNCTION_INFO_V1(hstore_concat);
+Datum          hstore_concat(PG_FUNCTION_ARGS);
+Datum
+hstore_concat(PG_FUNCTION_ARGS)
+{
+       HStore                  *hs1 = PG_GETARG_HS(0);
+       HStore                  *hs2 = PG_GETARG_HS(1);
+       HStore                  *out = palloc(VARSIZE(hs1) + VARSIZE(hs2));
+       ToHStoreState   *toState = NULL;
+       HStoreValue             *res;
+       HStoreIterator  *it1, *it2;
+
+       if (HS_ISEMPTY(hs1))
+       {
+               memcpy(out, hs2, VARSIZE(hs2));
+               PG_RETURN_POINTER(out);
+       }
+       else if (HS_ISEMPTY(hs2))
+       {
+               memcpy(out, hs1, VARSIZE(hs1));
+               PG_RETURN_POINTER(out);
+       }
+
+       it1 = HStoreIteratorInit(VARDATA(hs1));
+       it2 = HStoreIteratorInit(VARDATA(hs2));
+
+       res = IteratorConcat(&it1, &it2, &toState);
+
+       if (res == NULL || (res->type == hsvArray && res->array.nelems == 0) ||
+                                          (res->type == hsvHash && res->hash.npairs == 0) )
+       {
+               SET_VARSIZE(out, VARHDRSZ);
+       }
+       else
+       {
+               uint32 r;
+
+               if (res->type == hsvArray && res->array.nelems > 1)
+                       res->array.scalar = false;
+
+               r = compressHStore(res, VARDATA(out));
+               SET_VARSIZE(out, r + VARHDRSZ);
+       }
+
+       PG_RETURN_POINTER(out);
+}
+
+
+PG_FUNCTION_INFO_V1(hstore_slice_to_array);
+Datum          hstore_slice_to_array(PG_FUNCTION_ARGS);
+Datum
+hstore_slice_to_array(PG_FUNCTION_ARGS)
+{
+       HStore     *hs = PG_GETARG_HS(0);
+       ArrayType  *key_array = PG_GETARG_ARRAYTYPE_P(1);
+       ArrayType  *aout;
+       Datum      *key_datums;
+       bool       *key_nulls;
+       Datum      *out_datums;
+       bool       *out_nulls;
+       int                     key_count;
+       int                     i;
+
+       deconstruct_array(key_array,
+                                         TEXTOID, -1, false, 'i',
+                                         &key_datums, &key_nulls, &key_count);
+
+       if (key_count == 0 || HS_ISEMPTY(hs))
+       {
+               aout = construct_empty_array(TEXTOID);
+               PG_RETURN_POINTER(aout);
+       }
+
+       out_datums = palloc(sizeof(Datum) * key_count);
+       out_nulls = palloc(sizeof(bool) * key_count);
+
+       for (i = 0; i < key_count; ++i)
+       {
+               text       *key = (text *) DatumGetPointer(key_datums[i]);
+               HStoreValue     *v = NULL;
+
+               if (key_nulls[i] == false)
+                       v = findUncompressedHStoreValue(VARDATA(hs),
+                                                                                       HS_FLAG_HSTORE | HS_FLAG_ARRAY,
+                                                                                       NULL,
+                                                                                       VARDATA(key),
+                                                                                       VARSIZE(key) - VARHDRSZ);
+
+               out_datums[i] = PointerGetDatum(HStoreValueToText(v));
+               out_nulls[i] = (DatumGetPointer(out_datums[i]) == NULL) ? true : false;
+       }
+
+       aout = construct_md_array(out_datums, out_nulls,
+                                                         ARR_NDIM(key_array),
+                                                         ARR_DIMS(key_array),
+                                                         ARR_LBOUND(key_array),
+                                                         TEXTOID, -1, false, 'i');
+
+       PG_RETURN_POINTER(aout);
+}
+
+
+PG_FUNCTION_INFO_V1(hstore_slice_to_hstore);
+Datum          hstore_slice_to_hstore(PG_FUNCTION_ARGS);
+Datum
+hstore_slice_to_hstore(PG_FUNCTION_ARGS)
+{
+       HStore             *hs = PG_GETARG_HS(0);
+       HStoreValue        *a = arrayToHStoreSortedArray(PG_GETARG_ARRAYTYPE_P(1));
+       uint32                  lowbound = 0,
+                                  *plowbound;
+       HStoreValue             *res = NULL;
+       ToHStoreState   *state = NULL;
+       text                    *out;
+       uint32                  i;
+
+       out = palloc(VARSIZE(hs));
+
+       if (a == NULL || a->array.nelems == 0 || HS_ISEMPTY(hs))
+       {
+               memcpy(out, hs, VARSIZE(hs));
+               PG_RETURN_POINTER(out);
+       }
+
+       if (HS_ROOT_IS_HASH(hs))
+       {
+               plowbound = &lowbound;
+               pushHStoreValue(&state, WHS_BEGIN_HASH, NULL);
+       }
+       else
+       {
+               plowbound = NULL;
+               pushHStoreValue(&state, WHS_BEGIN_ARRAY, NULL);
+       }
+
+       for (i = 0; i < a->array.nelems; ++i)
+       {
+               HStoreValue     *v = findUncompressedHStoreValueByValue(VARDATA(hs),
+                                                                                                                       HS_FLAG_HSTORE | HS_FLAG_ARRAY,
+                                                                                                                       plowbound,
+                                                                                                                       a->array.elems + i);
+
+               if (v)
+               {
+                       if (plowbound)
+                       {
+                               pushHStoreValue(&state, WHS_KEY, a->array.elems + i);
+                               pushHStoreValue(&state, WHS_VALUE, v);
+                       }
+                       else
+                       {
+                               pushHStoreValue(&state, WHS_ELEM, v);
+                       }
+               }
+       }
+
+       if (plowbound)
+               res = pushHStoreValue(&state, WHS_END_HASH, a /* any non-null value */);
+       else
+               res = pushHStoreValue(&state, WHS_END_ARRAY, NULL);
+
+
+       if (res == NULL || (res->type == hsvArray && res->array.nelems == 0) ||
+                                               (res->type == hsvHash && res->hash.npairs == 0) )
+       {
+               SET_VARSIZE(out, VARHDRSZ);
+       }
+       else
+       {
+               int r = compressHStore(res, VARDATA(out));
+               SET_VARSIZE(out, r + VARHDRSZ);
+       }
+
+       PG_RETURN_POINTER(out);
+}
+
+static HStoreValue*
+replacePathDo(HStoreIterator **it, Datum *path_elems,
+                         bool *path_nulls, int path_len,
+                         ToHStoreState  **st, int level, HStoreValue *newval)
+{
+       HStoreValue v, *res = NULL;
+       int                     r;
+
+       r = HStoreIteratorGet(it, &v, false);
+
+       if (r == WHS_BEGIN_ARRAY)
+       {
+               int             idx, i;
+               uint32  n = v.array.nelems;
+
+               idx = n;
+               if (level >= path_len || path_nulls[level] ||
+                       h_atoi(VARDATA_ANY(path_elems[level]),
+                                  VARSIZE_ANY_EXHDR(path_elems[level]), &idx) == false)
+               {
+                       idx = n;
+               }
+               else if (idx < 0)
+               {
+                       if (-idx > n)
+                               idx = n;
+                       else
+                               idx = n + idx;
+               }
+
+               if (idx > n)
+                       idx = n;
+
+               pushHStoreValue(st, r, &v);
+
+               for(i=0; i<n; i++)
+               {
+                       if (i == idx && level < path_len)
+                       {
+                               if (level == path_len - 1)
+                               {
+                                       r = HStoreIteratorGet(it, &v, true); /* skip */
+                                       Assert(r == WHS_ELEM);
+                                       res = pushHStoreValue(st, r, newval);
+                               }
+                               else
+                               {
+                                       res = replacePathDo(it, path_elems, path_nulls, path_len,
+                                                                               st, level + 1, newval);
+                               }
+                       }
+                       else
+                       {
+                               r = HStoreIteratorGet(it, &v, true);
+                               Assert(r == WHS_ELEM);
+                               res = pushHStoreValue(st, r, &v);
+                       }
+               }
+
+               r = HStoreIteratorGet(it, &v, true);
+               Assert(r == WHS_END_ARRAY);
+               res = pushHStoreValue(st, r, &v);
+       }
+       else if (r == WHS_BEGIN_HASH)
+       {
+               int                     i;
+               uint32          n = v.hash.npairs;
+               HStoreValue     k;
+               bool            done = false;
+
+               pushHStoreValue(st, WHS_BEGIN_HASH, &v);
+
+               if (level >= path_len || path_nulls[level])
+                       done = true;
+
+               for(i=0; i<n; i++)
+               {
+                       r = HStoreIteratorGet(it, &k, false);
+                       Assert(r == WHS_KEY);
+                       res = pushHStoreValue(st, r, &k);
+
+                       if (done == false &&
+                               k.string.len == VARSIZE_ANY_EXHDR(path_elems[level]) &&
+                               memcmp(k.string.val, VARDATA_ANY(path_elems[level]),
+                                          k.string.len) == 0)
+                       {
+                               if (level == path_len - 1)
+                               {
+                                       r = HStoreIteratorGet(it, &v, true); /* skip */
+                                       Assert(r == WHS_VALUE);
+                                       res = pushHStoreValue(st, r, newval);
+                               }
+                               else
+                               {
+                                       res = replacePathDo(it, path_elems, path_nulls, path_len,
+                                                                               st, level + 1, newval);
+                               }
+                       }
+                       else
+                       {
+                               r = HStoreIteratorGet(it, &v, true);
+                               Assert(r == WHS_VALUE);
+                               res = pushHStoreValue(st, r, &v);
+                       }
+               }
+
+               r = HStoreIteratorGet(it, &v, true);
+               Assert(r == WHS_END_HASH);
+               res = pushHStoreValue(st, r, &v);
+       }
+       else if (r == WHS_ELEM || r == WHS_VALUE)
+       {
+               pushHStoreValue(st, r, &v);
+               res = (void*)0x01; /* dummy value */
+       }
+       else
+       {
+               elog(PANIC, "impossible state");
+       }
+
+       return res;
+}
+
+PG_FUNCTION_INFO_V1(hstore_replace);
+Datum          hstore_replace(PG_FUNCTION_ARGS);
+Datum
+hstore_replace(PG_FUNCTION_ARGS)
+{
+       HStore                  *in = PG_GETARG_HS(0);
+       ArrayType               *path = PG_GETARG_ARRAYTYPE_P(1);
+       HStore                  *newval = PG_GETARG_HS(2);
+       HStore                  *out = palloc(VARSIZE(in) + VARSIZE(newval));
+       HStoreValue             *res = NULL;
+       HStoreValue             value;
+       Datum                   *path_elems;
+       bool                    *path_nulls;
+       int                             path_len;
+       HStoreIterator  *it;
+       ToHStoreState   *st = NULL;
+
+       Assert(ARR_ELEMTYPE(path) == TEXTOID);
+
+       if (ARR_NDIM(path) > 1)
+               ereport(ERROR,
+                               (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+                                errmsg("wrong number of array subscripts")));
+
+       if (HS_ROOT_COUNT(in) == 0)
+       {
+               memcpy(out, in, VARSIZE(in));
+               PG_RETURN_POINTER(out);
+       }
+
+       deconstruct_array(path, TEXTOID, -1, false, 'i',
+                                         &path_elems, &path_nulls, &path_len);
+
+       if (path_len == 0)
+       {
+               memcpy(out, in, VARSIZE(in));
+               PG_RETURN_POINTER(out);
+       }
+
+       if (HS_ROOT_COUNT(newval) == 0)
+       {
+               value.type = hsvNull;
+               value.size = sizeof(HEntry);
+       }
+       else
+       {
+               value.type = hsvBinary;
+               value.binary.data = VARDATA(newval);
+               value.binary.len = VARSIZE_ANY_EXHDR(newval);
+               value.size = value.binary.len + sizeof(HEntry);
+       }
+
+       it = HStoreIteratorInit(VARDATA(in));
+
+       res = replacePathDo(&it, path_elems, path_nulls, path_len, &st, 0, &value);
+
+       if (res == NULL)
+       {
+               SET_VARSIZE(out, VARHDRSZ);
+       }
+       else
+       {
+               int                             sz;
+
+               sz = compressHStore(res, VARDATA(out));
+               SET_VARSIZE(out, sz + VARHDRSZ);
+       }
+
+       PG_RETURN_POINTER(out);
+}
+
+static HStoreValue*
+concatPathDo(HStoreIterator **it, Datum *path_elems,
+                        bool *path_nulls, int path_len,
+                        ToHStoreState  **st, int level, HStoreIterator *toConcat)
+{
+       HStoreValue v, *res = NULL;
+       int                     r;
+
+       r = HStoreIteratorGet(it, &v, false);
+
+       if (r == WHS_BEGIN_ARRAY)
+       {
+               int             idx, i;
+               uint32  n = v.array.nelems;
+
+               idx = n;
+               if (level >= path_len || path_nulls[level] ||
+                       h_atoi(VARDATA_ANY(path_elems[level]),
+                                  VARSIZE_ANY_EXHDR(path_elems[level]), &idx) == false)
+               {
+                       idx = n;
+               }
+               else if (idx < 0)
+               {
+                       if (-idx > n)
+                               idx = n;
+                       else
+                               idx = n + idx;
+               }
+
+               if (idx > n)
+                       idx = n;
+
+               pushHStoreValue(st, r, &v);
+
+               for(i=0; i<n; i++)
+               {
+                       if (i == idx && level < path_len)
+                       {
+                               if (level == path_len - 1)
+                                       res = IteratorConcat(it, &toConcat, st);
+                               else
+                                       res = concatPathDo(it, path_elems, path_nulls, path_len,
+                                                                          st, level + 1, toConcat);
+                       }
+                       else
+                       {
+                               r = HStoreIteratorGet(it, &v, true);
+                               Assert(r == WHS_ELEM);
+                               res = pushHStoreValue(st, r, &v);
+                       }
+               }
+
+               r = HStoreIteratorGet(it, &v, true);
+               Assert(r == WHS_END_ARRAY);
+               res = pushHStoreValue(st, r, &v);
+       }
+       else if (r == WHS_BEGIN_HASH)
+       {
+               int                     i;
+               uint32          n = v.hash.npairs;
+               HStoreValue     k;
+               bool            done = false;
+
+               pushHStoreValue(st, WHS_BEGIN_HASH, &v);
+
+               if (level >= path_len || path_nulls[level])
+                       done = true;
+
+               for(i=0; i<n; i++)
+               {
+                       r = HStoreIteratorGet(it, &k, false);
+                       Assert(r == WHS_KEY);
+                       res = pushHStoreValue(st, r, &k);
+
+                       if (done == false && level < path_len &&
+                               k.string.len == VARSIZE_ANY_EXHDR(path_elems[level]) &&
+                               memcmp(k.string.val, VARDATA_ANY(path_elems[level]),
+                                          k.string.len) == 0)
+                       {
+                               if (level == path_len - 1)
+                                       res = IteratorConcat(it, &toConcat, st);
+                               else
+                                       res = concatPathDo(it, path_elems, path_nulls, path_len,
+                                                                          st, level + 1, toConcat);
+                       }
+                       else
+                       {
+                               r = HStoreIteratorGet(it, &v, true);
+                               Assert(r == WHS_VALUE);
+                               res = pushHStoreValue(st, r, &v);
+                       }
+               }
+
+               r = HStoreIteratorGet(it, &v, true);
+               Assert(r == WHS_END_HASH);
+               res = pushHStoreValue(st, r, &v);
+       }
+       else if (r == WHS_ELEM || r == WHS_VALUE)
+       {
+               pushHStoreValue(st, r, &v);
+               res = (void*)0x01; /* dummy value */
+       }
+       else
+       {
+               elog(PANIC, "impossible state");
+       }
+
+       return res;
+}
+
+PG_FUNCTION_INFO_V1(hstore_deep_concat);
+Datum          hstore_deep_concat(PG_FUNCTION_ARGS);
+Datum
+hstore_deep_concat(PG_FUNCTION_ARGS)
+{
+       HStore                  *in = PG_GETARG_HS(0);
+       ArrayType               *path = PG_GETARG_ARRAYTYPE_P(1);
+       HStore                  *newval = PG_GETARG_HS(2);
+       HStore                  *out = palloc(VARSIZE(in) + VARSIZE(newval));
+       HStoreValue             *res = NULL;
+       Datum                   *path_elems;
+       bool                    *path_nulls;
+       int                             path_len;
+       HStoreIterator  *it1, *it2;
+       ToHStoreState   *st = NULL;
+
+       Assert(ARR_ELEMTYPE(path) == TEXTOID);
+
+       if (ARR_NDIM(path) > 1)
+               ereport(ERROR,
+                               (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+                                errmsg("wrong number of array subscripts")));
+
+       if (HS_ROOT_COUNT(in) == 0 || HS_ROOT_COUNT(newval) == 0)
+       {
+               memcpy(out, in, VARSIZE(in));
+               PG_RETURN_POINTER(out);
+       }
+
+       deconstruct_array(path, TEXTOID, -1, false, 'i',
+                                         &path_elems, &path_nulls, &path_len);
+
+       it1 = HStoreIteratorInit(VARDATA(in));
+       it2 = HStoreIteratorInit(VARDATA(newval));
+
+       if (path_len == 0)
+               res = IteratorConcat(&it1, &it2, &st);
+       else
+               res = concatPathDo(&it1, path_elems, path_nulls, path_len, &st, 0, it2);
+
+       if (res == NULL)
+       {
+               SET_VARSIZE(out, VARHDRSZ);
+       }
+       else
+       {
+               int                             sz;
+
+               if (res->type == hsvArray && res->array.nelems > 1)
+                       res->array.scalar = false;
+
+               sz = compressHStore(res, VARDATA(out));
+               SET_VARSIZE(out, sz + VARHDRSZ);
+       }
+
+       PG_RETURN_POINTER(out);
+}
+
+PG_FUNCTION_INFO_V1(hstore_akeys);
+Datum          hstore_akeys(PG_FUNCTION_ARGS);
+Datum
+hstore_akeys(PG_FUNCTION_ARGS)
+{
+       HStore                  *hs = PG_GETARG_HS(0);
+       Datum                   *d;
+       ArrayType               *a;
+       int                             i = 0, r = 0;
+       HStoreIterator  *it;
+       HStoreValue             v;
+       bool                    skipNested = false;
+
+       if (HS_ISEMPTY(hs))
+       {
+               a = construct_empty_array(TEXTOID);
+               PG_RETURN_POINTER(a);
+       }
+
+       d = (Datum *) palloc(sizeof(Datum) * HS_ROOT_COUNT(hs));
+
+       it = HStoreIteratorInit(VARDATA(hs));
+
+       while((r = HStoreIteratorGet(&it, &v, skipNested)) != 0)
+       {
+               skipNested = true;
+
+               if ((r == WHS_ELEM && v.type != hsvNull) || r == WHS_KEY)
+                       d[i++] = PointerGetDatum(HStoreValueToText(&v));
+       }
+
+       a = construct_array(d, i,
+                                               TEXTOID, -1, false, 'i');
+
+       PG_RETURN_POINTER(a);
+}
+
+
+PG_FUNCTION_INFO_V1(hstore_avals);
+Datum          hstore_avals(PG_FUNCTION_ARGS);
+Datum
+hstore_avals(PG_FUNCTION_ARGS)
+{
+       HStore                  *hs = PG_GETARG_HS(0);
+       Datum                   *d;
+       ArrayType               *a;
+       int                             i = 0, r = 0;
+       HStoreIterator  *it;
+       HStoreValue             v;
+       bool                    skipNested = false;
+       bool               *nulls;
+       int                             lb = 1;
+
+       if (HS_ISEMPTY(hs))
+       {
+               a = construct_empty_array(TEXTOID);
+               PG_RETURN_POINTER(a);
+       }
+
+       d = (Datum *) palloc(sizeof(Datum) * HS_ROOT_COUNT(hs));
+       nulls = (bool *) palloc(sizeof(bool) * HS_ROOT_COUNT(hs));
+
+       it = HStoreIteratorInit(VARDATA(hs));
+
+       while((r = HStoreIteratorGet(&it, &v, skipNested)) != 0)
+       {
+               skipNested = true;
+
+               if (r == WHS_ELEM || r == WHS_VALUE)
+               {
+                       d[i] = PointerGetDatum(HStoreValueToText(&v));
+                       nulls[i] = (DatumGetPointer(d[i]) == NULL) ? true : false;
+                       i++;
+               }
+       }
+
+       a = construct_md_array(d, nulls, 1, &i, &lb,
+                                                  TEXTOID, -1, false, 'i');
+
+       PG_RETURN_POINTER(a);
+}
+
+
+static ArrayType *
+hstore_to_array_internal(HStore *hs, int ndims)
+{
+       int                             count = HS_ROOT_COUNT(hs);
+       int                             out_size[2] = {0, 2};
+       int                             lb[2] = {1, 1};
+       Datum              *out_datums;
+       bool                    *out_nulls;
+       bool                    isHash = HS_ROOT_IS_HASH(hs) ? true : false;
+       int                             i = 0, r = 0;
+       HStoreIterator  *it;
+       HStoreValue             v;
+       bool                    skipNested = false;
+
+       Assert(ndims < 3);
+
+       if (count == 0 || ndims == 0)
+               return construct_empty_array(TEXTOID);
+
+       if (isHash == false && ndims == 2 && count % 2 != 0)
+               elog(ERROR, "hstore's array should have even number of elements");
+
+       out_size[0] = count * (isHash ? 2 : 1) / ndims;
+       out_datums = palloc(sizeof(Datum) * count * 2);
+       out_nulls = palloc(sizeof(bool) * count * 2);
+
+       it = HStoreIteratorInit(VARDATA(hs));
+
+       while((r = HStoreIteratorGet(&it, &v, skipNested)) != 0)
+       {
+               skipNested = true;
+
+               switch(r)
+               {
+                       case WHS_ELEM:
+                               out_datums[i] = PointerGetDatum(HStoreValueToText(&v));
+                               out_nulls[i] = (DatumGetPointer(out_datums[i]) == NULL) ? true : false;
+                               i++;
+                               break;
+                       case WHS_KEY:
+                               out_datums[i * 2] = PointerGetDatum(HStoreValueToText(&v));
+                               out_nulls[i * 2] = (DatumGetPointer(out_datums[i * 2]) == NULL) ? true : false;
+                               break;
+                       case WHS_VALUE:
+                               out_datums[i * 2 + 1] = PointerGetDatum(HStoreValueToText(&v));
+                               out_nulls[i * 2 + 1] = (DatumGetPointer(out_datums[i * 2 + 1]) == NULL) ? true : false;
+                               i++;
+                               break;
+                       default:
+                               break;
+               }
+       }
+
+       return construct_md_array(out_datums, out_nulls,
+                                                         ndims, out_size, lb,
+                                                         TEXTOID, -1, false, 'i');
+}
+
+PG_FUNCTION_INFO_V1(hstore_to_array);
+Datum          hstore_to_array(PG_FUNCTION_ARGS);
+Datum
+hstore_to_array(PG_FUNCTION_ARGS)
+{
+       HStore     *hs = PG_GETARG_HS(0);
+       ArrayType  *out = hstore_to_array_internal(hs, 1);
+
+       PG_RETURN_POINTER(out);
+}
+
+PG_FUNCTION_INFO_V1(hstore_to_matrix);
+Datum          hstore_to_matrix(PG_FUNCTION_ARGS);
+Datum
+hstore_to_matrix(PG_FUNCTION_ARGS)
+{
+       HStore     *hs = PG_GETARG_HS(0);
+       ArrayType  *out = hstore_to_array_internal(hs, 2);
+
+       PG_RETURN_POINTER(out);
+}
+
+/*
+ * Common initialization function for the various set-returning
+ * funcs. fcinfo is only passed if the function is to return a
+ * composite; it will be used to look up the return tupledesc.
+ * we stash a copy of the hstore in the multi-call context in
+ * case it was originally toasted. (At least I assume that's why;
+ * there was no explanatory comment in the original code. --AG)
+ */
+
+typedef struct SetReturningState
+{
+       HStore                  *hs;
+       HStoreIterator  *it;
+       MemoryContext   ctx;
+
+       HStoreValue             init;
+       int                             path_len;
+       int                             level;
+       struct {
+               HStoreValue             v;
+               Datum           varStr;
+               int                             varInt;
+               enum {
+                       pathStr,
+                       pathInt,
+                       pathAny
+               }                               varKind;
+               int                             i;
+       }                               *path;
+} SetReturningState;
+
+static SetReturningState*
+setup_firstcall(FuncCallContext *funcctx, HStore *hs, ArrayType *path,
+                               FunctionCallInfoData *fcinfo)
+{
+       MemoryContext                   oldcontext;
+       SetReturningState          *st;
+
+       oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
+
+       st = palloc(sizeof(*st));
+
+       st->ctx = funcctx->multi_call_memory_ctx;
+
+       st->hs = (HStore *) palloc(VARSIZE(hs));
+       memcpy(st->hs, hs, VARSIZE(hs));
+       if (HS_ISEMPTY(hs) || path)
+               st->it = NULL;
+       else
+               st->it = HStoreIteratorInit(VARDATA(st->hs));
+
+       funcctx->user_fctx = (void *) st;
+
+       if (fcinfo)
+       {
+               TupleDesc       tupdesc;
+
+               /* Build a tuple descriptor for our result type */
+               if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
+                       elog(ERROR, "return type must be a row type");
+
+               funcctx->tuple_desc = BlessTupleDesc(tupdesc);
+       }
+
+       st->path_len = st->level = 0;
+       if (path)
+       {
+               Datum           *path_elems;
+               bool            *path_nulls;
+               int                     i;
+
+               Assert(ARR_ELEMTYPE(path) == TEXTOID);
+               if (ARR_NDIM(path) > 1)
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+                                        errmsg("wrong number of array subscripts")));
+
+               deconstruct_array(path, TEXTOID, -1, false, 'i',
+                                                 &path_elems, &path_nulls, &st->path_len);
+
+               st->init.type = hsvBinary;
+               st->init.size = VARSIZE(st->hs);
+               st->init.binary.data = VARDATA(st->hs);
+               st->init.binary.len = VARSIZE_ANY_EXHDR(st->hs);
+
+               if (st->path_len > 0)
+               {
+                       st->path = palloc(sizeof(*st->path) * st->path_len);
+                       st->path[0].v = st->init;
+               }
+
+               for(i=0; i<st->path_len; i++)
+               {
+                       st->path[i].varStr = path_elems[i];
+                       st->path[i].i = 0;
+
+                       if (path_nulls[i])
+                               st->path[i].varKind = pathAny;
+                       else if (h_atoi(VARDATA_ANY(path_elems[i]),
+                                                       VARSIZE_ANY_EXHDR(path_elems[i]),
+                                                       &st->path[i].varInt))
+                               st->path[i].varKind = pathInt;
+                       else
+                               st->path[i].varKind = pathStr;
+               }
+       }
+
+       MemoryContextSwitchTo(oldcontext);
+
+       return st;
+}
+
+static uint32
+HStoreIteratorGetCtx(SetReturningState *st, HStoreValue *v, bool skipNested)
+{
+       int                     r;
+       MemoryContext   oldctx;
+
+       oldctx = MemoryContextSwitchTo(st->ctx);
+       r = HStoreIteratorGet(&st->it, v, skipNested);
+       MemoryContextSwitchTo(oldctx);
+
+       return r;
+}
+
+PG_FUNCTION_INFO_V1(hstore_skeys);
+Datum          hstore_skeys(PG_FUNCTION_ARGS);
+Datum
+hstore_skeys(PG_FUNCTION_ARGS)
+{
+       FuncCallContext         *funcctx;
+       SetReturningState       *st;
+       int                                     r;
+       HStoreValue                     v;
+
+       if (SRF_IS_FIRSTCALL())
+       {
+               funcctx = SRF_FIRSTCALL_INIT();
+               st = setup_firstcall(funcctx, PG_GETARG_HS(0), NULL, NULL);
+       }
+
+       funcctx = SRF_PERCALL_SETUP();
+       st = (SetReturningState *) funcctx->user_fctx;
+
+       while(st->it && (r = HStoreIteratorGetCtx(st, &v, true)) != 0)
+       {
+               if (r == WHS_KEY || r == WHS_ELEM)
+               {
+                       text       *item = HStoreValueToText(&v);
+
+                       if (item == NULL)
+                               SRF_RETURN_NEXT_NULL(funcctx);
+                       else
+                               SRF_RETURN_NEXT(funcctx, PointerGetDatum(item));
+               }
+       }
+
+       SRF_RETURN_DONE(funcctx);
+}
+
+PG_FUNCTION_INFO_V1(hstore_svals);
+Datum          hstore_svals(PG_FUNCTION_ARGS);
+Datum
+hstore_svals(PG_FUNCTION_ARGS)
+{
+       FuncCallContext         *funcctx;
+       SetReturningState       *st;
+       int                                     r;
+       HStoreValue                     v;
+
+       if (SRF_IS_FIRSTCALL())
+       {
+               funcctx = SRF_FIRSTCALL_INIT();
+               st = setup_firstcall(funcctx, PG_GETARG_HS(0), NULL, NULL);
+       }
+
+       funcctx = SRF_PERCALL_SETUP();
+       st = (SetReturningState *) funcctx->user_fctx;
+
+       while(st->it && (r = HStoreIteratorGetCtx(st, &v, true)) != 0)
+       {
+               if (r == WHS_VALUE || r == WHS_ELEM)
+               {
+                       text       *item = HStoreValueToText(&v);
+
+                       if (item == NULL)
+                               SRF_RETURN_NEXT_NULL(funcctx);
+                       else
+                               SRF_RETURN_NEXT(funcctx, PointerGetDatum(item));
+               }
+       }
+
+       SRF_RETURN_DONE(funcctx);
+}
+
+PG_FUNCTION_INFO_V1(hstore_hvals);
+Datum          hstore_hvals(PG_FUNCTION_ARGS);
+Datum
+hstore_hvals(PG_FUNCTION_ARGS)
+{
+       FuncCallContext         *funcctx;
+       SetReturningState       *st;
+       int                                     r;
+       HStoreValue                     v;
+
+       if (SRF_IS_FIRSTCALL())
+       {
+               funcctx = SRF_FIRSTCALL_INIT();
+               st = setup_firstcall(funcctx, PG_GETARG_HS(0), NULL, NULL);
+       }
+
+       funcctx = SRF_PERCALL_SETUP();
+       st = (SetReturningState *) funcctx->user_fctx;
+
+       while(st->it && (r = HStoreIteratorGetCtx(st, &v, true)) != 0)
+       {
+               if (r == WHS_VALUE || r == WHS_ELEM)
+               {
+                       HStore     *item = HStoreValueToHStore(&v);
+
+                       if (item == NULL)
+                               SRF_RETURN_NEXT_NULL(funcctx);
+                       else
+                               SRF_RETURN_NEXT(funcctx, PointerGetDatum(item));
+               }
+       }
+
+       SRF_RETURN_DONE(funcctx);
+}
+
+static HStoreValue*
+getNextValsPath(SetReturningState *st)
+{
+       HStoreValue             *v = NULL;
+
+       if (st->path_len == 0)
+       {
+               /* empty path */
+               if (st->level == 0)
+               {
+                       v = &st->init;
+                       st->level ++;
+               }
+
+               return v;
+       }
+
+       while(st->level >= 0)
+       {
+               uint32  header;
+
+               v = NULL;
+               if (st->path[st->level].v.type != hsvBinary)
+               {
+                       st->level--;
+                       continue;
+               }
+
+               header = *(uint32*)st->path[st->level].v.binary.data;
+
+               if (header & HS_FLAG_HSTORE)
+               {
+                       if (st->path[st->level].varKind == pathAny)
+                       {
+                               v = getHStoreValue(st->path[st->level].v.binary.data,
+                                                                  HS_FLAG_HSTORE,
+                                                                  st->path[st->level].i++);
+                       }
+                       else
+                       {
+                               v = findUncompressedHStoreValue(st->path[st->level].v.binary.data,
+                                                                                               HS_FLAG_HSTORE, NULL,
+                                                                                               VARDATA_ANY(st->path[st->level].varStr),
+                                                                                               VARSIZE_ANY_EXHDR(st->path[st->level].varStr));
+                       }
+               }
+               else if (header & HS_FLAG_ARRAY)
+               {
+                       if (st->path[st->level].varKind == pathAny)
+                       {
+                               v = getHStoreValue(st->path[st->level].v.binary.data,
+                                                                  HS_FLAG_ARRAY, st->path[st->level].i++);
+                       }
+                       else if (st->path[st->level].varKind == pathInt)
+                       {
+                               int     ith = st->path[st->level].varInt;
+
+                               if (ith < 0)
+                               {
+                                       if (-ith > (int)(header & HS_COUNT_MASK))
+                                       {
+                                               st->level--;
+                                               continue;
+                                       }
+                                       else
+                                       {
+                                               ith = ((int)(header & HS_COUNT_MASK)) + ith;
+                                       }
+                               }
+                               else
+                               {
+                                       if (ith >= (int)(header & HS_COUNT_MASK))
+                                       {
+                                               st->level--;
+                                               continue;
+                                       }
+                               }
+
+                               v = getHStoreValue(st->path[st->level].v.binary.data,
+                                                                  HS_FLAG_ARRAY, ith);
+                       }
+                       else
+                       {
+                               st->level--;
+                               continue;
+                       }
+               }
+               else
+               {
+                       elog(PANIC, "impossible state");
+               }
+
+               if (v == NULL)
+               {
+                       st->level--;
+               }
+               else if (st->level == st->path_len - 1)
+               {
+                       if (st->path[st->level].varKind != pathAny)
+                       {
+                               st->path[st->level].v.type = hsvNull;
+                               st->level--;
+                       }
+                       break;
+               }
+               else
+               {
+                       if (st->path[st->level].varKind != pathAny)
+                               st->path[st->level].v.type = hsvNull;
+                       st->level++;
+                       st->path[st->level].v = *v;
+                       st->path[st->level].i = 0;
+               }
+       }
+
+       return v;
+}
+
+PG_FUNCTION_INFO_V1(hstore_svals_path);
+Datum          hstore_svals_path(PG_FUNCTION_ARGS);
+Datum
+hstore_svals_path(PG_FUNCTION_ARGS)
+{
+       FuncCallContext         *funcctx;
+       SetReturningState       *st;
+       HStoreValue                     *v;
+
+       if (SRF_IS_FIRSTCALL())
+       {
+               funcctx = SRF_FIRSTCALL_INIT();
+               st = setup_firstcall(funcctx, PG_GETARG_HS(0), PG_GETARG_ARRAYTYPE_P(1), NULL);
+       }
+
+       funcctx = SRF_PERCALL_SETUP();
+       st = (SetReturningState *) funcctx->user_fctx;
+
+       if ((v = getNextValsPath(st)) != NULL)
+       {
+               text    *item = HStoreValueToText(v);
+
+               if (item == NULL)
+                       SRF_RETURN_NEXT_NULL(funcctx);
+               else
+                       SRF_RETURN_NEXT(funcctx, PointerGetDatum(item));
+       }
+
+       SRF_RETURN_DONE(funcctx);
+}
+
+PG_FUNCTION_INFO_V1(hstore_hvals_path);
+Datum          hstore_hvals_path(PG_FUNCTION_ARGS);
+Datum
+hstore_hvals_path(PG_FUNCTION_ARGS)
+{
+       FuncCallContext         *funcctx;
+       SetReturningState       *st;
+       HStoreValue             *v;
+
+       if (SRF_IS_FIRSTCALL())
+       {
+               funcctx = SRF_FIRSTCALL_INIT();
+               st = setup_firstcall(funcctx, PG_GETARG_HS(0),
+                                                        PG_GETARG_ARRAYTYPE_P(1), NULL);
+       }
+
+       funcctx = SRF_PERCALL_SETUP();
+       st = (SetReturningState *) funcctx->user_fctx;
+
+       if ((v = getNextValsPath(st)) != NULL)
+       {
+               HStore     *item = HStoreValueToHStore(v);
+
+               if (item == NULL)
+                       SRF_RETURN_NEXT_NULL(funcctx);
+               else
+                       SRF_RETURN_NEXT(funcctx, PointerGetDatum(item));
+       }
+
+       SRF_RETURN_DONE(funcctx);
+}
+
+PG_FUNCTION_INFO_V1(hstore_each);
+Datum          hstore_each(PG_FUNCTION_ARGS);
+Datum
+hstore_each(PG_FUNCTION_ARGS)
+{
+       FuncCallContext         *funcctx;
+       SetReturningState       *st;
+       int                                     r;
+       HStoreValue                     v;
+
+       if (SRF_IS_FIRSTCALL())
+       {
+               funcctx = SRF_FIRSTCALL_INIT();
+               st = setup_firstcall(funcctx, PG_GETARG_HS(0), NULL, fcinfo);
+       }
+
+       funcctx = SRF_PERCALL_SETUP();
+       st = (SetReturningState *) funcctx->user_fctx;
+
+       while(st->it && (r = HStoreIteratorGetCtx(st, &v, true)) != 0)
+       {
+               Datum           res,
+                                       dvalues[2] = {0, 0};
+               bool            nulls[2] = {false, false};
+               text       *item;
+               HeapTuple       tuple;
+
+               if (r == WHS_ELEM)
+               {
+                       nulls[0] = true;
+
+                       item = HStoreValueToText(&v);
+                       if (item == NULL)
+                               nulls[1] = true;
+                       else
+                               dvalues[1] = PointerGetDatum(item);
+               }
+               else if (r == WHS_KEY)
+               {
+                       item = HStoreValueToText(&v);
+                       dvalues[0] = PointerGetDatum(item);
+
+                       r = HStoreIteratorGetCtx(st, &v, true);
+                       Assert(r == WHS_VALUE);
+                       item = HStoreValueToText(&v);
+                       if (item == NULL)
+                               nulls[1] = true;
+                       else
+                               dvalues[1] = PointerGetDatum(item);
+               }
+               else
+               {
+                       continue;
+               }
+
+               tuple = heap_form_tuple(funcctx->tuple_desc, dvalues, nulls);
+               res = HeapTupleGetDatum(tuple);
+
+               SRF_RETURN_NEXT(funcctx, PointerGetDatum(res));
+       }
+
+       SRF_RETURN_DONE(funcctx);
+}
+
+PG_FUNCTION_INFO_V1(hstore_each_hstore);
+Datum          hstore_each_hstore(PG_FUNCTION_ARGS);
+Datum
+hstore_each_hstore(PG_FUNCTION_ARGS)
+{
+       FuncCallContext         *funcctx;
+       SetReturningState       *st;
+       int                                     r;
+       HStoreValue                     v;
+
+       if (SRF_IS_FIRSTCALL())
+       {
+               funcctx = SRF_FIRSTCALL_INIT();
+               st = setup_firstcall(funcctx, PG_GETARG_HS(0), NULL, fcinfo);
+       }
+
+       funcctx = SRF_PERCALL_SETUP();
+       st = (SetReturningState *) funcctx->user_fctx;
+
+       while(st->it && (r = HStoreIteratorGetCtx(st, &v, true)) != 0)
+       {
+               Datum           res,
+                                       dvalues[2] = {0, 0};
+               bool            nulls[2] = {false, false};
+               text       *item;
+               HStore          *hitem;
+               HeapTuple       tuple;
+
+               if (r == WHS_ELEM)
+               {
+                       nulls[0] = true;
+
+                       hitem = HStoreValueToHStore(&v);
+                       if (hitem == NULL)
+                               nulls[1] = true;
+                       else
+                               dvalues[1] = PointerGetDatum(hitem);
+               }
+               else if (r == WHS_KEY)
+               {
+                       item = HStoreValueToText(&v);
+                       dvalues[0] = PointerGetDatum(item);
+
+                       r = HStoreIteratorGetCtx(st, &v, true);
+                       Assert(r == WHS_VALUE);
+                       hitem = HStoreValueToHStore(&v);
+                       if (hitem == NULL)
+                               nulls[1] = true;
+                       else
+                               dvalues[1] = PointerGetDatum(hitem);
+               }
+               else
+               {
+                       continue;
+               }
+
+               tuple = heap_form_tuple(funcctx->tuple_desc, dvalues, nulls);
+               res = HeapTupleGetDatum(tuple);
+
+               SRF_RETURN_NEXT(funcctx, PointerGetDatum(res));
+       }
+
+       SRF_RETURN_DONE(funcctx);
+}
+
+static bool
+deepContains(HStoreIterator **it1, HStoreIterator **it2)
+{
+       uint32                  r1, r2;
+       HStoreValue             v1, v2;
+       bool                    res = true;
+
+       r1 = HStoreIteratorGet(it1, &v1, false);
+       r2 = HStoreIteratorGet(it2, &v2, false);
+
+       if (r1 != r2)
+       {
+               res = false;
+       }
+       else if (r1 == WHS_BEGIN_HASH)
+       {
+               uint32          lowbound = 0;
+               HStoreValue     *v;
+
+               for(;;) {
+                       r2 = HStoreIteratorGet(it2, &v2, false);
+                       if (r2 == WHS_END_HASH)
+                               break;
+
+                       Assert(r2 == WHS_KEY);
+
+                       v = findUncompressedHStoreValueByValue((*it1)->buffer,
+                                                                                                  HS_FLAG_HSTORE,
+                                                                                                  &lowbound, &v2);
+
+                       if (v == NULL)
+                       {
+                               res = false;
+                               break;
+                       }
+
+                       r2 = HStoreIteratorGet(it2, &v2, true);
+                       Assert(r2 == WHS_VALUE);
+
+                       if (v->type != v2.type)
+                       {
+                               res = false;
+                               break;
+                       }
+                       else if (v->type == hsvString || v->type == hsvNull ||
+                                        v->type == hsvBool || v->type == hsvNumeric)
+                       {
+                               if (compareHStoreValue(v, &v2) != 0)
+                               {
+                                       res = false;
+                                       break;
+                               }
+                       }
+                       else
+                       {
+                               HStoreIterator  *it1a, *it2a;
+
+                               Assert(v2.type == hsvBinary);
+                               Assert(v->type == hsvBinary);
+
+                               it1a = HStoreIteratorInit(v->binary.data);
+                               it2a = HStoreIteratorInit(v2.binary.data);
+
+                               if ((res = deepContains(&it1a, &it2a)) == false)
+                                       break;
+                       }
+               }
+       }
+       else if (r1 == WHS_BEGIN_ARRAY)
+       {
+               HStoreValue             *v;
+               HStoreValue             *av = NULL;
+               uint32                  nelems = v1.array.nelems;
+
+               for(;;) {
+                       r2 = HStoreIteratorGet(it2, &v2, true);
+                       if (r2 == WHS_END_ARRAY)
+                               break;
+
+                       Assert(r2 == WHS_ELEM);
+
+                       if (v2.type == hsvString || v2.type == hsvNull ||
+                               v2.type == hsvBool || v2.type == hsvNumeric)
+                       {
+                               v = findUncompressedHStoreValueByValue((*it1)->buffer,
+                                                                                                          HS_FLAG_ARRAY, NULL,
+                                                                                                          &v2);
+                               if (v == NULL)
+                               {
+                                       res = false;
+                                       break;
+                               }
+                       }
+                       else
+                       {
+                               uint32                  i;
+
+                               if (av == NULL)
+                               {
+                                       uint32                  j = 0;
+
+                                       av = palloc(sizeof(*av) * nelems);
+
+                                       for(i=0; i<nelems; i++)
+                                       {
+                                               r2 = HStoreIteratorGet(it1, &v1, true);
+                                               Assert(r2 == WHS_ELEM);
+
+                                               if (v1.type == hsvBinary)
+                                                       av[j++] = v1;
+                                       }
+
+                                       if (j == 0)
+                                       {
+                                               res = false;
+                                               break;
+                                       }
+
+                                       nelems = j;
+                               }
+
+                               res = false;
+                               for(i = 0; res == false && i<nelems; i++)
+                               {
+                                       HStoreIterator  *it1a, *it2a;
+
+                                       it1a = HStoreIteratorInit(av[i].binary.data);
+                                       it2a = HStoreIteratorInit(v2.binary.data);
+
+                                       res = deepContains(&it1a, &it2a);
+                               }
+
+                               if (res == false)
+                                       break;
+                       }
+               }
+       }
+       else
+       {
+               elog(PANIC, "impossible state");
+       }
+
+       return res;
+}
+
+PG_FUNCTION_INFO_V1(hstore_contains);
+Datum          hstore_contains(PG_FUNCTION_ARGS);
+Datum
+hstore_contains(PG_FUNCTION_ARGS)
+{
+       HStore                  *val = PG_GETARG_HS(0);
+       HStore                  *tmpl = PG_GETARG_HS(1);
+       bool                    res = true;
+       HStoreIterator  *it1, *it2;
+
+       if (HS_ROOT_COUNT(val) < HS_ROOT_COUNT(tmpl) ||
+               HS_ROOT_IS_HASH(val) != HS_ROOT_IS_HASH(tmpl))
+               PG_RETURN_BOOL(false);
+
+       it1 = HStoreIteratorInit(VARDATA(val));
+       it2 = HStoreIteratorInit(VARDATA(tmpl));
+       res = deepContains(&it1, &it2);
+
+       PG_RETURN_BOOL(res);
+}
+
+
+PG_FUNCTION_INFO_V1(hstore_contained);
+Datum          hstore_contained(PG_FUNCTION_ARGS);
+Datum
+hstore_contained(PG_FUNCTION_ARGS)
+{
+       PG_RETURN_DATUM(DirectFunctionCall2(hstore_contains,
+                                                                               PG_GETARG_DATUM(1),
+                                                                               PG_GETARG_DATUM(0)
+                                                                               ));
+}
+
+/*
+ * btree sort order for hstores isn't intended to be useful; we really only
+ * care about equality versus non-equality.  we compare the entire string
+ * buffer first, then the entry pos array.
+ */
+
+PG_FUNCTION_INFO_V1(hstore_cmp);
+Datum          hstore_cmp(PG_FUNCTION_ARGS);
+Datum
+hstore_cmp(PG_FUNCTION_ARGS)
+{
+       HStore                  *hs1 = PG_GETARG_HS(0);
+       HStore                  *hs2 = PG_GETARG_HS(1);
+       int                             res;
+
+       if (HS_ISEMPTY(hs1) || HS_ISEMPTY(hs2))
+       {
+               if (HS_ISEMPTY(hs1))
+               {
+                       if (HS_ISEMPTY(hs2))
+                               res = 0;
+                       else
+                               res = -1;
+               }
+               else
+               {
+                       res = 1;
+               }
+       }
+       else
+       {
+               res = compareHStoreBinaryValue(VARDATA(hs1), VARDATA(hs2));
+       }
+
+       /*
+        * this is a btree support function; this is one of the few places where
+        * memory needs to be explicitly freed.
+        */
+       PG_FREE_IF_COPY(hs1, 0);
+       PG_FREE_IF_COPY(hs2, 1);
+       PG_RETURN_INT32(res);
+}
+
+
+PG_FUNCTION_INFO_V1(hstore_eq);
+Datum          hstore_eq(PG_FUNCTION_ARGS);
+Datum
+hstore_eq(PG_FUNCTION_ARGS)
+{
+       int                     res = DatumGetInt32(DirectFunctionCall2(hstore_cmp,
+                                                                                                               PG_GETARG_DATUM(0),
+                                                                                                               PG_GETARG_DATUM(1)));
+
+       PG_RETURN_BOOL(res == 0);
+}
+
+PG_FUNCTION_INFO_V1(hstore_ne);
+Datum          hstore_ne(PG_FUNCTION_ARGS);
+Datum
+hstore_ne(PG_FUNCTION_ARGS)
+{
+       int                     res = DatumGetInt32(DirectFunctionCall2(hstore_cmp,
+                                                                                                               PG_GETARG_DATUM(0),
+                                                                                                               PG_GETARG_DATUM(1)));
+
+       PG_RETURN_BOOL(res != 0);
+}
+
+PG_FUNCTION_INFO_V1(hstore_gt);
+Datum          hstore_gt(PG_FUNCTION_ARGS);
+Datum
+hstore_gt(PG_FUNCTION_ARGS)
+{
+       int                     res = DatumGetInt32(DirectFunctionCall2(hstore_cmp,
+                                                                                                               PG_GETARG_DATUM(0),
+                                                                                                               PG_GETARG_DATUM(1)));
+
+       PG_RETURN_BOOL(res > 0);
+}
+
+PG_FUNCTION_INFO_V1(hstore_ge);
+Datum          hstore_ge(PG_FUNCTION_ARGS);
+Datum
+hstore_ge(PG_FUNCTION_ARGS)
+{
+       int                     res = DatumGetInt32(DirectFunctionCall2(hstore_cmp,
+                                                                                                               PG_GETARG_DATUM(0),
+                                                                                                               PG_GETARG_DATUM(1)));
+
+       PG_RETURN_BOOL(res >= 0);
+}
+
+PG_FUNCTION_INFO_V1(hstore_lt);
+Datum          hstore_lt(PG_FUNCTION_ARGS);
+Datum
+hstore_lt(PG_FUNCTION_ARGS)
+{
+       int                     res = DatumGetInt32(DirectFunctionCall2(hstore_cmp,
+                                                                                                               PG_GETARG_DATUM(0),
+                                                                                                               PG_GETARG_DATUM(1)));
+
+       PG_RETURN_BOOL(res < 0);
+}
+
+PG_FUNCTION_INFO_V1(hstore_le);
+Datum          hstore_le(PG_FUNCTION_ARGS);
+Datum
+hstore_le(PG_FUNCTION_ARGS)
+{
+       int                     res = DatumGetInt32(DirectFunctionCall2(hstore_cmp,
+                                                                                                               PG_GETARG_DATUM(0),
+                                                                                                               PG_GETARG_DATUM(1)));
+
+       PG_RETURN_BOOL(res <= 0);
+}
+
+
+PG_FUNCTION_INFO_V1(hstore_hash);
+Datum          hstore_hash(PG_FUNCTION_ARGS);
+Datum
+hstore_hash(PG_FUNCTION_ARGS)
+{
+       HStore                  *hs = PG_GETARG_HS(0);
+       HStoreIterator  *it;
+       int32                   r;
+       HStoreValue             v;
+       int                             crc;
+
+       if (HS_ROOT_COUNT(hs) == 0)
+               PG_RETURN_INT32(0x1EEE);
+
+       it = HStoreIteratorInit(VARDATA(hs));
+       INIT_CRC32(crc);
+
+       while((r = HStoreIteratorGet(&it, &v, false)) != 0)
+       {
+               switch(r)
+               {
+                       case WHS_BEGIN_ARRAY:
+                               COMP_CRC32(crc, "ab", 3);
+                               COMP_CRC32(crc, &v.array.nelems, sizeof(v.array.nelems));
+                               COMP_CRC32(crc, &v.array.scalar, sizeof(v.array.scalar));
+                               break;
+                       case WHS_BEGIN_HASH:
+                               COMP_CRC32(crc, "hb", 3);
+                               COMP_CRC32(crc, &v.hash.npairs, sizeof(v.hash.npairs));
+                               break;
+                       case WHS_KEY:
+                               COMP_CRC32(crc, "k", 2);
+                       case WHS_VALUE:
+                       case WHS_ELEM:
+                               switch(v.type)
+                               {
+                                       case hsvString:
+                                               COMP_CRC32(crc, v.string.val, v.string.len);
+                                               break;
+                                       case hsvNull:
+                                               COMP_CRC32(crc, "N", 2);
+                                               break;
+                                       case hsvBool:
+                                               COMP_CRC32(crc, &v.boolean, sizeof(v.boolean));
+                                               break;
+                                       case hsvNumeric:
+                                               crc ^= DatumGetInt32(DirectFunctionCall1(hash_numeric,
+                                                                                        NumericGetDatum(v.numeric)));
+                                               break;
+                                       default:
+                                               elog(ERROR, "unexpected state of hstore iterator");
+                               }
+
+                               break;
+                       case WHS_END_ARRAY:
+                               COMP_CRC32(crc, "ae", 3);
+                               break;
+                       case WHS_END_HASH:
+                               COMP_CRC32(crc, "he", 3);
+                               break;
+                       default:
+                               elog(ERROR, "unexpected state of hstore iterator");
+               }
+       }
+
+       FIN_CRC32(crc);
+
+       PG_FREE_IF_COPY(hs, 0);
+       PG_RETURN_INT32(crc);
+}
+
+PG_FUNCTION_INFO_V1(hstore_typeof);
+Datum          hstore_typeof(PG_FUNCTION_ARGS);
+Datum
+hstore_typeof(PG_FUNCTION_ARGS)
+{
+       HStore                  *hs = PG_GETARG_HS(0);
+       HStoreIterator  *it;
+       HStoreValue             v;
+       uint32                  r;
+
+       if (HS_ISEMPTY(hs))
+               PG_RETURN_NULL();
+
+       it = HStoreIteratorInit(VARDATA(hs));
+       r = HStoreIteratorGet(&it, &v, false);
+
+       switch(r)
+       {
+               case WHS_BEGIN_ARRAY:
+                       if (v.array.scalar)
+                       {
+                               Assert(v.array.nelems == 1);
+                               r = HStoreIteratorGet(&it, &v, false);
+                               Assert(r == WHS_ELEM);
+
+                               switch(v.type)
+                               {
+                                       case hsvNull:
+                                               PG_RETURN_TEXT_P(cstring_to_text("null"));
+                                       case hsvBool:
+                                               PG_RETURN_TEXT_P(cstring_to_text("bool"));
+                                       case hsvNumeric:
+                                               PG_RETURN_TEXT_P(cstring_to_text("numeric"));
+                                       case hsvString:
+                                               PG_RETURN_TEXT_P(cstring_to_text("string"));
+                                       default:
+                                               elog(ERROR, "bogus hstore");
+                               }
+                       }
+                       else
+                       {
+                               PG_RETURN_TEXT_P(cstring_to_text("array"));
+                       }
+               case WHS_BEGIN_HASH:
+                       PG_RETURN_TEXT_P(cstring_to_text("hash"));
+               case 0:
+                       PG_RETURN_NULL();
+               default:
+                       elog(ERROR, "bogus hstore");
+       }
+
+       PG_RETURN_NULL();
+}
+
diff --git a/hstore_scan.l b/hstore_scan.l
new file mode 100644 (file)
index 0000000..1c994e4
--- /dev/null
@@ -0,0 +1,291 @@
+%{
+static string scanstring;
+
+/* No reason to constrain amount of data slurped */
+/* #define YY_READ_BUF_SIZE 16777216 */
+
+/* Handles to the buffer that the lexer uses internally */
+static YY_BUFFER_STATE scanbufhandle;
+static char *scanbuf;
+static int     scanbuflen;
+
+static void addstring(bool init, char *s, int l);
+static void addchar(bool init, char s);
+static int checkSpecialVal(void); /* examine scanstring for the special value */
+
+static bool    inputJSON = false;
+
+
+%}
+
+%option 8bit
+%option never-interactive
+%option nodefault
+%option noinput
+%option nounput
+%option noyywrap
+%option warn
+%option prefix="hstore_yy"
+%option bison-bridge
+
+%x xQUOTED
+%x xNONQUOTED
+
+any                    [^\,\[\]\{\}\"\=\> \t\n\r\f\\\:]
+
+
+%%
+
+<INITIAL>[\,\{\}\[\]]                  { return *yytext; }
+
+<INITIAL>\=\>                                  { return DELIMITER_P; }
+
+<INITIAL>\:                                            { 
+                                                                       if (inputJSON)
+                                                                       {
+                                                                               return DELIMITER_P;
+                                                                       }
+                                                                       else
+                                                                       {
+                                                                               addchar(true, ':');
+                                                                               BEGIN xNONQUOTED;
+                                                                       }
+                                                               }
+
+<INITIAL>[ \t\n\r\f]+                  { /* ignore */ }
+
+<INITIAL>\=/[^\>]                              {
+                                                                       addchar(true, '=');
+                                                                       BEGIN xNONQUOTED;
+                                                               }
+                                                                       
+<INITIAL>\>                                            {
+                                                                       addchar(true, yytext[0]);
+                                                                       BEGIN xNONQUOTED;
+                                                               }
+<INITIAL>\\.                                   {
+                                                                       addchar(true, yytext[1]);
+                                                                       BEGIN xNONQUOTED;
+                                                               }
+
+<INITIAL>({any}|\>)+                   {
+                                                                       addstring(true, yytext, yyleng);
+                                                                       BEGIN xNONQUOTED;
+                                                               }
+                                                                       
+<INITIAL>\"                                    {
+                                                                       addchar(true, '\0');
+                                                                       BEGIN xQUOTED;
+                                                               }
+
+<INITIAL>\=                                            {       /* =<<EOF>> */
+                                                                       addchar(true, '=');
+                                                                       yylval->str = scanstring;
+                                                                       return STRING_P;
+                                                               }
+
+<xNONQUOTED>({any}|[\>\"\:])+  { 
+                                                                       addstring(false, yytext, yyleng); 
+                                                               }
+
+<xNONQUOTED>\=/[^\>]                   { addchar(false, *yytext); }
+
+<xNONQUOTED>[ \t\n\r\f]+               { 
+                                                                       yylval->str = scanstring;
+                                                                       BEGIN INITIAL;
+                                                                       return checkSpecialVal();
+                                                               }
+
+<xNONQUOTED>\=                                 {       /* =<<EOF>> */
+                                                                       addchar(false, '=');
+                                                                       yylval->str = scanstring;
+                                                                       BEGIN INITIAL;
+                                                                       return STRING_P;
+                                                               }
+
+<xNONQUOTED>[\,\{\}\[\]]               {
+                                                                       yylval->str = scanstring;
+                                                                       yyless(0);
+                                                                       BEGIN INITIAL;
+                                                                       return checkSpecialVal();
+                                                               }
+
+<xNONQUOTED><<EOF>>                            { 
+                                                                       yylval->str = scanstring;
+                                                                       BEGIN INITIAL;
+                                                                       return checkSpecialVal();
+                                                               }
+
+<xNONQUOTED>\=\>                               {
+                                                                       yylval->str = scanstring;
+                                                                       yyless(0);
+                                                                       BEGIN INITIAL;
+                                                                       return checkSpecialVal();
+                                                               }
+                                                                       
+
+<xNONQUOTED,xQUOTED>\\.                { addchar(false, yytext[1]); }
+
+<INITIAL,xNONQUOTED,xQUOTED>\\         { yyerror("Unexpected end after backslesh"); }
+
+<xQUOTED><<EOF>>                               { yyerror("Unexpected end of quoted string"); }
+
+<xQUOTED>\"                                            {
+                                                                       yylval->str = scanstring;
+                                                                       BEGIN INITIAL;
+                                                                       return STRING_P;
+                                                               }
+
+<xQUOTED>[^\\\"]+                      { addstring(false, yytext, yyleng); }
+
+<INITIAL><<EOF>>                               { yyterminate(); }
+
+%%
+
+void
+yyerror(const char *message)
+{
+       if (*yytext == YY_END_OF_BUFFER_CHAR)
+       {
+               ereport(ERROR,
+                               (errcode(ERRCODE_SYNTAX_ERROR),
+                                errmsg("bad hstore representation"),
+                                /* translator: %s is typically "syntax error" */
+                                errdetail("%s at end of input", message)));
+       }
+       else
+       {
+               ereport(ERROR,
+                               (errcode(ERRCODE_SYNTAX_ERROR),
+                                errmsg("bad hstore representation"),
+                                /* translator: first %s is typically "syntax error" */
+                                errdetail("%s at or near \"%s\"", message, yytext)));
+       }
+}
+
+static int
+checkSpecialVal()
+{
+       int res = STRING_P;
+
+       if (stringIsNumber(scanstring.val, scanstring.len, inputJSON))
+       {
+               /* for numeric_in() call we need to make a correct C-string */
+               addchar(false, '\0');
+               res = NUMERIC_P;
+       }
+       else if (scanstring.len == 1)
+       {
+               if (*scanstring.val == 't')
+                       res = TRUE_P;
+               else if (*scanstring.val == 'f')
+                       res = FALSE_P;
+       }
+       else if (scanstring.len == 4)
+       {
+               if (pg_strncasecmp("null", scanstring.val, scanstring.len) == 0)
+                       res = NULL_P;
+               else if (pg_strncasecmp("true", scanstring.val, scanstring.len) == 0)
+                       res = TRUE_P;
+       }
+       else if (scanstring.len == 5)
+       {
+               if (pg_strncasecmp("false", scanstring.val, scanstring.len) == 0)
+                       res = FALSE_P;
+       }
+
+       return res;
+}
+/*
+ * Called before any actual parsing is done
+ */
+static void
+hstore_scanner_init(const char *str, int slen)
+{
+       if (slen <= 0)
+               slen = strlen(str);
+
+       /*
+        * Might be left over after ereport()
+        */
+       if (YY_CURRENT_BUFFER)
+               yy_delete_buffer(YY_CURRENT_BUFFER);
+
+       /*
+        * Make a scan buffer with special termination needed by flex.
+        */
+
+       scanbuflen = slen;
+       scanbuf = palloc(slen + 2);
+       memcpy(scanbuf, str, slen);
+       scanbuf[slen] = scanbuf[slen + 1] = YY_END_OF_BUFFER_CHAR;
+       scanbufhandle = yy_scan_buffer(scanbuf, slen + 2);
+
+       BEGIN(INITIAL);
+}
+
+
+/*
+ * Called after parsing is done to clean up after hstore_scanner_init()
+ */
+static void
+hstore_scanner_finish(void)
+{
+       yy_delete_buffer(scanbufhandle);
+       pfree(scanbuf);
+}
+
+static void
+addstring(bool init, char *s, int l) {
+       if (init) {
+               scanstring.total = 32;
+               scanstring.val = palloc(scanstring.total);
+               scanstring.len = 0;
+       }
+
+       if (s && l) {
+               while(scanstring.len + l + 1 >= scanstring.total) {
+                       scanstring.total *= 2;
+                       scanstring.val = repalloc(scanstring.val, scanstring.total);
+               }
+
+               memcpy(scanstring.val+scanstring.len, s, l);
+               scanstring.len+=l;
+       }
+}
+
+static void
+addchar(bool init, char s) {
+       if (init)
+       {
+               scanstring.total = 32;
+               scanstring.val = palloc(scanstring.total);
+               scanstring.len = 0;
+       }
+       else if(scanstring.len + 1 >= scanstring.total)
+       {
+               scanstring.total*=2;
+               scanstring.val=repalloc(scanstring.val, scanstring.total);
+       }
+
+       scanstring.val[ scanstring.len ] = s;
+       if (s != '\0')
+               scanstring.len++;
+}
+
+HStoreValue* 
+parseHStore(const char *str, int len, bool json) {
+       HStoreValue             *parseresult;
+
+       inputJSON = json;
+
+       hstore_scanner_init(str, len);
+
+       if (hstore_yyparse((void*)&parseresult) != 0)
+               hstore_yyerror("bugus input");
+
+       hstore_scanner_finish();
+
+       return parseresult;
+}
+
diff --git a/hstore_support.c b/hstore_support.c
new file mode 100644 (file)
index 0000000..37109e1
--- /dev/null
@@ -0,0 +1,1130 @@
+#include "postgres.h"
+#include "utils/builtins.h"
+
+#include "hstore.h"
+
+/****************************************************************************
+ *                         Compare Functions                                *
+ ****************************************************************************/
+int
+compareHStoreStringValue(const void *a, const void *b, void *arg)
+{
+       const HStoreValue  *va = a;
+       const HStoreValue  *vb = b;
+       int                                     res;
+
+       Assert(va->type == hsvString);
+       Assert(vb->type == hsvString);
+
+       if (va->string.len == vb->string.len)
+       {
+               res = memcmp(va->string.val, vb->string.val, va->string.len);
+               if (res == 0 && arg)
+                       *(bool*)arg = true;
+       }
+       else
+       {
+               res = (va->string.len > vb->string.len) ? 1 : -1;
+       }
+
+       return res;
+}
+
+int
+compareHStorePair(const void *a, const void *b, void *arg)
+{
+       const   HStorePair *pa = a;
+       const   HStorePair *pb = b;
+       int     res;
+
+       res = compareHStoreStringValue(&pa->key, &pb->key, arg);
+
+       /*
+        * guarantee keeping order of equal pair. Unique algorithm will
+        * prefer first element as value
+        */
+
+       if (res == 0)
+               res = (pa->order > pb->order) ? -1 : 1;
+
+       return res;
+}
+
+int
+compareHStoreValue(HStoreValue *a, HStoreValue *b)
+{
+       if (a->type == b->type)
+       {
+               switch(a->type)
+               {
+                       case hsvNull:
+                               return 0;
+                       case hsvString:
+                               return compareHStoreStringValue(a, b, NULL);
+                       case hsvBool:
+                               if (a->boolean == b->boolean)
+                                       return 0;
+                               return (a->boolean > b->boolean) ? 1 : -1;
+                       case hsvNumeric:
+                               return DatumGetInt32(DirectFunctionCall2(numeric_cmp,
+                                                                                                                PointerGetDatum(a->numeric),
+                                                                                                                PointerGetDatum(b->numeric)));
+                       case hsvArray:
+                               if (a->array.nelems == b->array.nelems)
+                               {
+                                       int i, r;
+
+                                       for(i=0; i<a->array.nelems; i++)
+                                               if ((r = compareHStoreValue(a->array.elems + i,
+                                                                                                       b->array.elems + i)) != 0)
+                                                       return r;
+
+                                       return 0;
+                               }
+
+                               return (a->array.nelems > b->array.nelems) ? 1 : -1;
+                       case hsvHash:
+                               if (a->hash.npairs == b->hash.npairs)
+                               {
+                                       int i, r;
+
+                                       for(i=0; i<a->hash.npairs; i++)
+                                       {
+                                               if ((r = compareHStoreStringValue(&a->hash.pairs[i].key,
+                                                                                                                 &b->hash.pairs[i].key,
+                                                                                                                 NULL)) != 0)
+                                                       return r;
+                                               if ((r = compareHStoreValue(&a->hash.pairs[i].value,
+                                                                                                       &b->hash.pairs[i].value)) != 0)
+                                                       return r;
+                                       }
+
+                                       return 0;
+                               }
+
+                               return (a->hash.npairs > b->hash.npairs) ? 1 : -1;
+                       case hsvBinary:
+                               return compareHStoreBinaryValue(a->binary.data, b->binary.data);
+                       default:
+                               elog(PANIC, "unknown HStoreValue->type: %d", a->type);
+               }
+       }
+
+       return (a->type > b->type) ? 1 : -1;
+}
+
+int
+compareHStoreBinaryValue(char *a, char *b)
+{
+       HStoreIterator  *it1, *it2;
+       int                             res = 0;
+
+       it1 = HStoreIteratorInit(a);
+       it2 = HStoreIteratorInit(b);
+
+       while(res == 0)
+       {
+               HStoreValue             v1, v2;
+               int                             r1, r2;
+
+               r1 = HStoreIteratorGet(&it1, &v1, false);
+               r2 = HStoreIteratorGet(&it2, &v2, false);
+
+               if (r1 == r2)
+               {
+                       if (r1 == 0)
+                               break; /* equal */
+
+                       if (v1.type == v2.type)
+                       {
+                               switch(v1.type)
+                               {
+                                       case hsvString:
+                                               res = compareHStoreStringValue(&v1, &v2, NULL);
+                                               break;
+                                       case hsvBool:
+                                               if (v1.boolean == v2.boolean)
+                                                       res = 0;
+                                               else
+                                                       res = (v1.boolean > v2.boolean) ? 1 : -1;
+                                               break;
+                                       case hsvNumeric:
+                                               res = DatumGetInt32(DirectFunctionCall2(numeric_cmp,
+                                                                                               PointerGetDatum(v1.numeric),
+                                                                                               PointerGetDatum(v2.numeric)));
+                                               break;
+                                       case hsvArray:
+                                               if (v1.array.nelems != v2.array.nelems)
+                                                       res = (v1.array.nelems > v2.array.nelems) ? 1 : -1;
+                                               break;
+                                       case hsvHash:
+                                               if (v1.hash.npairs != v2.hash.npairs)
+                                                       res = (v1.hash.npairs > v2.hash.npairs) ? 1 : -1;
+                                               break;
+                                       default:
+                                               break;
+                               }
+                       }
+                       else
+                       {
+                               res = (v1.type > v2.type) ?  1 : -1; /* dummy order */
+                       }
+               }
+               else
+               {
+                       res = (r1 > r2) ? 1 : -1; /* dummy order */
+               }
+       }
+
+       return res;
+}
+
+/*
+ * Sort and unique pairs in hash-like HStoreValue
+ */
+void
+uniqueHStoreValue(HStoreValue *v)
+{
+       bool    hasNonUniq = false;
+
+       Assert(v->type == hsvHash);
+
+       if (v->hash.npairs > 1)
+               qsort_arg(v->hash.pairs, v->hash.npairs, sizeof(*v->hash.pairs),
+                                 compareHStorePair, &hasNonUniq);
+
+       if (hasNonUniq)
+       {
+               HStorePair  *ptr = v->hash.pairs + 1,
+                                       *res = v->hash.pairs;
+
+               while(ptr - v->hash.pairs < v->hash.npairs)
+               {
+                       if (ptr->key.string.len == res->key.string.len &&
+                               memcmp(ptr->key.string.val, res->key.string.val,
+                                          ptr->key.string.len) == 0)
+                       {
+                               v->size -= ptr->key.size + ptr->value.size;
+                       }
+                       else
+                       {
+                               res++;
+                               if (ptr != res)
+                                       memcpy(res, ptr, sizeof(*res));
+                       }
+                       ptr++;
+               }
+
+               v->hash.npairs = res + 1 - v->hash.pairs;
+       }
+}
+
+
+/****************************************************************************
+ *                         find string key in hash or array                 *
+ ****************************************************************************/
+HStoreValue*
+findUncompressedHStoreValueByValue(char *buffer, uint32 flags, uint32 *lowbound, HStoreValue *key)
+{
+       uint32                          header = *(uint32*)buffer;
+       static HStoreValue      r;
+
+       Assert((header & (HS_FLAG_ARRAY | HS_FLAG_HSTORE)) !=
+                  (HS_FLAG_ARRAY | HS_FLAG_HSTORE));
+
+       if (flags & HS_FLAG_ARRAY & header)
+       {
+               HEntry  *array = (HEntry*)(buffer + sizeof(header));
+               char    *data = (char*)(array + (header & HS_COUNT_MASK));
+               int     i;
+
+               for(i=(lowbound) ? *lowbound : 0; i<(header & HS_COUNT_MASK); i++) {
+                       HEntry  *e = array + i;
+
+                       if (HSE_ISNULL(*e) && key->type == hsvNull)
+                       {
+                               r.type = hsvNull;
+                               if (lowbound)
+                                       *lowbound = i;
+                               r.size = sizeof(HEntry);
+
+                               return &r;
+                       }
+                       else if (HSE_ISSTRING(*e) && key->type == hsvString )
+                       {
+                               if (key->string.len == HSE_LEN(*e) &&
+                                       memcmp(key->string.val, data + HSE_OFF(*e),
+                                                  key->string.len) == 0)
+                               {
+                                       r.type = hsvString;
+                                       r.string.val = data + HSE_OFF(*e);
+                                       r.string.len = key->string.len;
+                                       r.size = sizeof(HEntry) + r.string.len;
+                                       if (lowbound)
+                                               *lowbound = i;
+
+                                       return &r;
+                               }
+                       }
+                       else if (HSE_ISBOOL(*e) && key->type == hsvBool)
+                       {
+                               if ((HSE_ISBOOL_TRUE(*e) && key->boolean == true) ||
+                                       (HSE_ISBOOL_FALSE(*e) && key->boolean == false))
+                               {
+                                       r = *key;
+                                       r.size = sizeof(HEntry);
+                                       if (lowbound)
+                                               *lowbound = i;
+
+                                       return &r;
+                               }
+                       }
+                       else if (HSE_ISNUMERIC(*e) && key->type == hsvNumeric)
+                       {
+                               if (DatumGetBool(DirectFunctionCall2(numeric_eq,
+                                                               PointerGetDatum(data + INTALIGN(HSE_OFF(*e))),
+                                                               PointerGetDatum(key->numeric))) == true)
+                               {
+                                       r.type = hsvNumeric;
+                                       r.numeric = (Numeric)(data + INTALIGN(HSE_OFF(*e)));
+                                       if (lowbound)
+                                               *lowbound = i;
+
+                                       return &r;
+                               }
+                       }
+               }
+       }
+       else if (flags & HS_FLAG_HSTORE & header)
+       {
+               HEntry  *array = (HEntry*)(buffer + sizeof(header));
+               char    *data = (char*)(array + (header & HS_COUNT_MASK) * 2);
+               uint32  stopLow = lowbound ? *lowbound : 0,
+                               stopHigh = (header & HS_COUNT_MASK),
+                               stopMiddle;
+
+               if (key->type != hsvString)
+                       return NULL;
+
+               while (stopLow < stopHigh)
+               {
+                       int             difference;
+                       HEntry  *e;
+
+                       stopMiddle = stopLow + (stopHigh - stopLow) / 2;
+
+                       e = array + stopMiddle * 2;
+
+                       if (key->string.len == HSE_LEN(*e))
+                               difference = memcmp(data + HSE_OFF(*e), key->string.val,
+                                                                       key->string.len);
+                       else
+                               difference = (HSE_LEN(*e) > key->string.len) ? 1 : -1;
+
+                       if (difference == 0)
+                       {
+                               HEntry  *v = e + 1;
+
+                               if (lowbound)
+                                       *lowbound = stopMiddle + 1;
+
+                               if (HSE_ISSTRING(*v))
+                               {
+                                       r.type = hsvString;
+                                       r.string.val = data + HSE_OFF(*v);
+                                       r.string.len = HSE_LEN(*v);
+                                       r.size = sizeof(HEntry) + r.string.len;
+                               }
+                               else if (HSE_ISBOOL(*v))
+                               {
+                                       r.type = hsvBool;
+                                       r.boolean = (HSE_ISBOOL_TRUE(*v)) ? true : false;
+                                       r.size = sizeof(HEntry);
+                               }
+                               else if (HSE_ISNUMERIC(*v))
+                               {
+                                       r.type = hsvNumeric;
+                                       r.numeric = (Numeric)(data + INTALIGN(HSE_OFF(*v)));
+                                       r.size = 2*sizeof(HEntry) + VARSIZE_ANY(r.numeric);
+                               }
+                               else if (HSE_ISNULL(*v))
+                               {
+                                       r.type = hsvNull;
+                                       r.size = sizeof(HEntry);
+                               }
+                               else
+                               {
+                                       r.type = hsvBinary;
+                                       r.binary.data = data + INTALIGN(HSE_OFF(*v));
+                                       r.binary.len = HSE_LEN(*v) -
+                                                                       (INTALIGN(HSE_OFF(*v)) - HSE_OFF(*v));
+                                       r.size = 2*sizeof(HEntry) + r.binary.len;
+                               }
+
+                               return &r;
+                       }
+                       else if (difference < 0)
+                       {
+                               stopLow = stopMiddle + 1;
+                       }
+                       else
+                       {
+                               stopHigh = stopMiddle;
+                       }
+               }
+
+               if (lowbound)
+                       *lowbound = stopLow;
+       }
+
+       return NULL;
+}
+
+HStoreValue*
+findUncompressedHStoreValue(char *buffer, uint32 flags, uint32 *lowbound,
+                                                       char *key, uint32 keylen)
+{
+       HStoreValue     v;
+
+       if (key == NULL)
+       {
+               v.type = hsvNull;
+       }
+       else
+       {
+               v.type = hsvString;
+               v.string.val = key;
+               v.string.len = keylen;
+       }
+
+       return findUncompressedHStoreValueByValue(buffer, flags, lowbound, &v);
+}
+
+HStoreValue*
+getHStoreValue(char *buffer, uint32 flags, int32 i)
+{
+       uint32                          header = *(uint32*)buffer;
+       static HStoreValue      r;
+       HEntry                          *array, *e;
+       char                            *data;
+
+       Assert((header & (HS_FLAG_ARRAY | HS_FLAG_HSTORE)) !=
+                  (HS_FLAG_ARRAY | HS_FLAG_HSTORE));
+
+       if (i >= 0)
+       {
+               if (i >= (header & HS_COUNT_MASK))
+                       return NULL;
+       }
+       else
+       {
+               if (-i > (header & HS_COUNT_MASK))
+                       return NULL;
+
+               i = (header & HS_COUNT_MASK) + i;
+       }
+
+       array = (HEntry*)(buffer + sizeof(header));
+
+       if (flags & HS_FLAG_ARRAY & header)
+       {
+               e = array + i;
+               data = (char*)(array + (header & HS_COUNT_MASK));
+       }
+       else if (flags & HS_FLAG_HSTORE & header)
+       {
+               e = array + i * 2 + 1;
+               data = (char*)(array + (header & HS_COUNT_MASK) * 2);
+       }
+       else
+       {
+               return NULL;
+       }
+
+       if (HSE_ISSTRING(*e))
+       {
+               r.type = hsvString;
+               r.string.val = data + HSE_OFF(*e);
+               r.string.len = HSE_LEN(*e);
+               r.size = sizeof(HEntry) + r.string.len;
+       }
+       else if (HSE_ISBOOL(*e))
+       {
+               r.type = hsvBool;
+               r.boolean = (HSE_ISBOOL_TRUE(*e)) ? true : false;
+               r.size = sizeof(HEntry);
+       }
+       else if (HSE_ISNUMERIC(*e))
+       {
+               r.type = hsvNumeric;
+               r.numeric = (Numeric)(data + INTALIGN(HSE_OFF(*e)));
+               r.size = 2*sizeof(HEntry) + VARSIZE_ANY(r.numeric);
+       }
+       else if (HSE_ISNULL(*e))
+       {
+               r.type = hsvNull;
+               r.size = sizeof(HEntry);
+       }
+       else
+       {
+               r.type = hsvBinary;
+               r.binary.data = data + INTALIGN(HSE_OFF(*e));
+               r.binary.len = HSE_LEN(*e) - (INTALIGN(HSE_OFF(*e)) - HSE_OFF(*e));
+               r.size = r.binary.len + 2*sizeof(HEntry);
+       }
+
+       return &r;
+}
+
+/****************************************************************************
+ *                         Walk on tree representation of hstore            *
+ ****************************************************************************/
+static void
+walkUncompressedHStoreDo(HStoreValue *v, walk_hstore_cb cb, void *cb_arg,
+                                                uint32 level)
+{
+       int i;
+
+       switch(v->type)
+       {
+               case hsvArray:
+                       cb(cb_arg, v, WHS_BEGIN_ARRAY, level);
+                       for(i=0; i<v->array.nelems; i++)
+                       {
+                               if (v->array.elems[i].type == hsvNull ||
+                                       v->array.elems[i].type == hsvString ||
+                                       v->array.elems[i].type == hsvBool ||
+                                       v->array.elems[i].type == hsvNumeric ||
+                                       v->array.elems[i].type == hsvBinary)
+                                       cb(cb_arg, v->array.elems + i, WHS_ELEM, level);
+                               else
+                                       walkUncompressedHStoreDo(v->array.elems + i, cb, cb_arg,
+                                                                                        level + 1);
+                       }
+                       cb(cb_arg, v, WHS_END_ARRAY, level);
+                       break;
+               case hsvHash:
+                       cb(cb_arg, v, WHS_BEGIN_HASH, level);
+
+                       for(i=0; i<v->hash.npairs; i++)
+                       {
+                               cb(cb_arg, &v->hash.pairs[i].key, WHS_KEY, level);
+
+                               if (v->hash.pairs[i].value.type == hsvNull ||
+                                       v->hash.pairs[i].value.type == hsvString ||
+                                       v->hash.pairs[i].value.type == hsvBool ||
+                                       v->hash.pairs[i].value.type == hsvNumeric ||
+                                       v->hash.pairs[i].value.type == hsvBinary)
+                                       cb(cb_arg, &v->hash.pairs[i].value, WHS_VALUE, level);
+                               else
+                                       walkUncompressedHStoreDo(&v->hash.pairs[i].value, cb, cb_arg, level + 1);
+                       }
+
+                       cb(cb_arg, v, WHS_END_HASH, level);
+                       break;
+               default:
+                       elog(PANIC, "impossible HStoreValue->type: %d", v->type);
+       }
+}
+
+void
+walkUncompressedHStore(HStoreValue *v, walk_hstore_cb cb, void *cb_arg)
+{
+       if (v)
+               walkUncompressedHStoreDo(v, cb, cb_arg, 0);
+}
+
+/****************************************************************************
+ *                         Iteration over binary hstore                     *
+ ****************************************************************************/
+static void
+parseBuffer(HStoreIterator *it, char *buffer)
+{
+       uint32  header = *(uint32*)buffer;
+
+       it->type = header & (HS_FLAG_ARRAY | HS_FLAG_HSTORE);
+       it->nelems = header & HS_COUNT_MASK;
+       it->buffer = buffer;
+
+
+       buffer += sizeof(uint32);
+       it->array = (HEntry*)buffer;
+
+       it->state = hsi_start;
+
+       switch(it->type)
+       {
+               case HS_FLAG_ARRAY:
+                       it->data = buffer + it->nelems * sizeof(HEntry);
+                       it->isScalar = (header & HS_FLAG_SCALAR) ? true : false;
+                       Assert(it->isScalar == false || it->nelems == 1);
+                       break;
+               case HS_FLAG_HSTORE:
+                       it->data = buffer + it->nelems * sizeof(HEntry) * 2;
+                       break;
+               default:
+                       elog(PANIC, "impossible type: %08x", it->type);
+       }
+}
+
+HStoreIterator*
+HStoreIteratorInit(char *buffer)
+{
+       HStoreIterator  *it = palloc(sizeof(*it));
+
+       parseBuffer(it, buffer);
+       it->next = NULL;
+
+       return it;
+}
+
+static bool
+formAnswer(HStoreIterator **it, HStoreValue *v, HEntry *e, bool skipNested)
+{
+       if (HSE_ISSTRING(*e))
+       {
+               v->type = hsvString;
+               v->string.val = (*it)->data + HSE_OFF(*e);
+               v->string.len = HSE_LEN(*e);
+               v->size = sizeof(HEntry) + v->string.len;
+
+               return false;
+       }
+       else if (HSE_ISBOOL(*e))
+       {
+               v->type = hsvBool;
+               v->boolean = (HSE_ISBOOL_TRUE(*e)) ? true : false;
+               v->size = sizeof(HEntry);
+
+               return false;
+       }
+       else if (HSE_ISNUMERIC(*e))
+       {
+               v->type = hsvNumeric;
+               v->numeric = (Numeric)((*it)->data + INTALIGN(HSE_OFF(*e)));
+               v->size = 2*sizeof(HEntry) + VARSIZE_ANY(v->numeric);
+
+               return false;
+       }
+       else if (HSE_ISNULL(*e))
+       {
+               v->type = hsvNull;
+               v->size = sizeof(HEntry);
+
+               return false;
+       }
+       else if (skipNested)
+       {
+               v->type = hsvBinary;
+               v->binary.data = (*it)->data + INTALIGN(HSE_OFF(*e));
+               v->binary.len = HSE_LEN(*e) - (INTALIGN(HSE_OFF(*e)) - HSE_OFF(*e));
+               v->size = v->binary.len + 2*sizeof(HEntry);
+
+               return false;
+       }
+       else
+       {
+               HStoreIterator *nit = palloc(sizeof(*nit));
+
+               parseBuffer(nit, (*it)->data + INTALIGN(HSE_OFF(*e)));
+               nit->next = *it;
+               *it = nit;
+
+               return true;
+       }
+}
+
+static HStoreIterator*
+up(HStoreIterator *it)
+{
+       HStoreIterator *v = it->next;
+
+       pfree(it);
+
+       return v;
+}
+
+int
+HStoreIteratorGet(HStoreIterator **it, HStoreValue *v, bool skipNested)
+{
+       int res;
+
+       if (*it == NULL)
+               return 0;
+
+       /*
+        * Encode all possible states by one integer. That's possible
+        * because enum members of HStoreIterator->state uses different bits
+        * than HS_FLAG_ARRAY/HS_FLAG_HSTORE. See definition of HStoreIterator
+        */
+
+       switch((*it)->type | (*it)->state)
+       {
+               case HS_FLAG_ARRAY | hsi_start:
+                       (*it)->state = hsi_elem;
+                       (*it)->i = 0;
+                       v->type = hsvArray;
+                       v->array.nelems = (*it)->nelems;
+                       res = WHS_BEGIN_ARRAY;
+                       v->array.scalar = (*it)->isScalar;
+                       break;
+               case HS_FLAG_ARRAY | hsi_elem:
+                       if ((*it)->i >= (*it)->nelems)
+                       {
+                               *it = up(*it);
+                               res = WHS_END_ARRAY;
+                       }
+                       else if (formAnswer(it, v, &(*it)->array[ (*it)->i++ ], skipNested))
+                       {
+                               res = HStoreIteratorGet(it, v, skipNested);
+                       }
+                       else
+                       {
+                               res = WHS_ELEM;
+                       }
+                       break;
+               case HS_FLAG_HSTORE | hsi_start:
+                       (*it)->state = hsi_key;
+                       (*it)->i = 0;
+                       v->type = hsvHash;
+                       v->hash.npairs = (*it)->nelems;
+                       res = WHS_BEGIN_HASH;
+                       break;
+               case HS_FLAG_HSTORE | hsi_key:
+                       if ((*it)->i >= (*it)->nelems)
+                       {
+                               *it = up(*it);
+                               res = WHS_END_HASH;
+                       }
+                       else
+                       {
+                               formAnswer(it, v, &(*it)->array[ (*it)->i * 2 ], false);
+                               (*it)->state = hsi_value;
+                               res = WHS_KEY;
+                       }
+                       break;
+               case HS_FLAG_HSTORE | hsi_value:
+                       (*it)->state = hsi_key;
+                       if (formAnswer(it, v, &(*it)->array[ ((*it)->i++) * 2 + 1],
+                                                  skipNested))
+                               res = HStoreIteratorGet(it, v, skipNested);
+                       else
+                               res = WHS_VALUE;
+                       break;
+               default:
+                       elog(PANIC,"unknown state %08x", (*it)->type & (*it)->state);
+       }
+
+       return res;
+}
+
+/****************************************************************************
+ *        Transformation from tree to binary representation of hstore       *
+ ****************************************************************************/
+typedef struct CompressState
+{
+       char    *begin;
+       char    *ptr;
+
+       struct {
+               uint32  i;
+               uint32  *header;
+               HEntry  *array;
+               char    *begin;
+       } *levelstate, *lptr, *pptr;
+
+       uint32  maxlevel;
+
+} CompressState;
+
+#define        curLevelState   state->lptr
+#define prevLevelState state->pptr
+
+static void
+putHEntryString(CompressState *state, HStoreValue* value,
+                               uint32 level, uint32 i)
+{
+       curLevelState = state->levelstate + level;
+
+       if (i == 0)
+               curLevelState->array[0].entry = HENTRY_ISFIRST;
+       else
+               curLevelState->array[i].entry = 0;
+
+       switch(value->type)
+       {
+               case hsvNull:
+                       curLevelState->array[i].entry |= HENTRY_ISNULL;
+
+                       if (i>0)
+                               curLevelState->array[i].entry |=
+                                       curLevelState->array[i - 1].entry & HENTRY_POSMASK;
+                       break;
+               case hsvString:
+                       memcpy(state->ptr, value->string.val, value->string.len);
+                       state->ptr += value->string.len;
+
+                       if (i == 0)
+                               curLevelState->array[i].entry |= value->string.len;
+                       else
+                               curLevelState->array[i].entry |=
+                                       (curLevelState->array[i - 1].entry & HENTRY_POSMASK) +
+                                       value->string.len;
+                       break;
+               case hsvBool:
+                       curLevelState->array[i].entry |=
+                               (value->boolean) ? HENTRY_ISTRUE : HENTRY_ISFALSE;
+
+                       if (i>0)
+                               curLevelState->array[i].entry |=
+                                       curLevelState->array[i - 1].entry & HENTRY_POSMASK;
+                       break;
+               case hsvNumeric:
+                       {
+                               int addlen = INTALIGN(state->ptr - state->begin) -
+                                                               (state->ptr - state->begin);
+                               int     numlen = VARSIZE_ANY(value->numeric);
+
+                               switch(addlen)
+                               {
+                                       case 3:
+                                               *state->ptr = '\0'; state->ptr++;
+                                       case 2:
+                                               *state->ptr = '\0'; state->ptr++;
+                                       case 1:
+                                               *state->ptr = '\0'; state->ptr++;
+                                       case 0:
+                                       default:
+                                               break;
+                               }
+
+                               memcpy(state->ptr, value->numeric, numlen);
+                               state->ptr += numlen;
+
+                               curLevelState->array[i].entry |= HENTRY_ISNUMERIC;
+                               if (i == 0)
+                                       curLevelState->array[i].entry |= addlen + numlen;
+                               else
+                                       curLevelState->array[i].entry |=
+                                               (curLevelState->array[i - 1].entry & HENTRY_POSMASK) +
+                                               addlen + numlen;
+                               break;
+                       }
+               case hsvBinary:
+                       {
+                               int addlen = INTALIGN(state->ptr - state->begin) -
+                                                               (state->ptr - state->begin);
+
+                               switch(addlen)
+                               {
+                                       case 3:
+                                               *state->ptr = '\0'; state->ptr++;
+                                       case 2:
+                                               *state->ptr = '\0'; state->ptr++;
+                                       case 1:
+                                               *state->ptr = '\0'; state->ptr++;
+                                       case 0:
+                                       default:
+                                               break;
+                               }
+
+                               memcpy(state->ptr, value->binary.data, value->binary.len);
+                               state->ptr += value->binary.len;
+
+                               curLevelState->array[i].entry |= HENTRY_ISNEST;
+
+                               if (i == 0)
+                                       curLevelState->array[i].entry |= addlen + value->binary.len;
+                               else
+                                       curLevelState->array[i].entry |=
+                                               (curLevelState->array[i - 1].entry & HENTRY_POSMASK) +
+                                               addlen + value->binary.len;
+                       }
+                       break;
+               default:
+                       elog(PANIC,"Unsupported HStoreValue type: %d", value->type);
+       }
+}
+
+static void
+compressCallback(void *arg, HStoreValue* value, uint32 flags, uint32 level)
+{
+       CompressState   *state = arg;
+
+       if (level == state->maxlevel) {
+               state->maxlevel *= 2;
+               state->levelstate = repalloc(state->levelstate,
+                                                                sizeof(*state->levelstate) * state->maxlevel);
+       }
+
+       curLevelState = state->levelstate + level;
+
+       if (flags & (WHS_BEGIN_ARRAY | WHS_BEGIN_HASH))
+       {
+               Assert(((flags & WHS_BEGIN_ARRAY) && value->type == hsvArray) ||
+                          ((flags & WHS_BEGIN_HASH) && value->type == hsvHash));
+
+               curLevelState->begin = state->ptr;
+
+               switch(INTALIGN(state->ptr - state->begin) -
+                                               (state->ptr - state->begin))
+               {
+                       case 3:
+                               *state->ptr = '\0'; state->ptr++;
+                       case 2:
+                               *state->ptr = '\0'; state->ptr++;
+                       case 1:
+                               *state->ptr = '\0'; state->ptr++;
+                       case 0:
+                       default:
+                               break;
+               }
+
+               curLevelState->header = (uint32*)state->ptr;
+               state->ptr += sizeof(*curLevelState->header);
+
+               curLevelState->array = (HEntry*)state->ptr;
+               curLevelState->i = 0;
+
+               if (value->type == hsvArray)
+               {
+                       *curLevelState->header = value->array.nelems | HS_FLAG_ARRAY ;
+                       state->ptr += sizeof(HEntry) * value->array.nelems;
+
+                       if (value->array.scalar)
+                       {
+                               Assert(value->array.nelems == 1);
+                               Assert(level == 0);
+                               *curLevelState->header |= HS_FLAG_SCALAR;
+                       }
+               }
+               else
+               {
+                       *curLevelState->header = value->hash.npairs | HS_FLAG_HSTORE ;
+                       state->ptr += sizeof(HEntry) * value->hash.npairs * 2;
+               }
+
+               if (level == 0)
+                       *curLevelState->header |= HS_FLAG_NEWVERSION;
+       }
+       else if (flags & WHS_ELEM)
+       {
+               putHEntryString(state, value, level, curLevelState->i);
+               curLevelState->i++;
+       }
+       else if (flags & WHS_KEY)
+       {
+               Assert(value->type == hsvString);
+
+               putHEntryString(state, value, level, curLevelState->i * 2);
+       }
+       else if (flags & WHS_VALUE)
+       {
+               putHEntryString(state, value, level, curLevelState->i * 2 + 1);
+               curLevelState->i++;
+       }
+       else if (flags & (WHS_END_ARRAY | WHS_END_HASH))
+       {
+               uint32  len, i;
+
+               Assert(((flags & WHS_END_ARRAY) && value->type == hsvArray) ||
+                          ((flags & WHS_END_HASH) && value->type == hsvHash));
+               if (level == 0)
+                       return;
+
+               len = state->ptr - (char*)curLevelState->begin;
+
+               prevLevelState = curLevelState - 1;
+
+               if (*prevLevelState->header & HS_FLAG_ARRAY) {
+                       i = prevLevelState->i;
+
+                       prevLevelState->array[i].entry = HENTRY_ISNEST;
+
+                       if (i == 0)
+                               prevLevelState->array[0].entry |= HENTRY_ISFIRST | len;
+                       else
+                               prevLevelState->array[i].entry |=
+                                       (prevLevelState->array[i - 1].entry & HENTRY_POSMASK) + len;
+               }
+               else if (*prevLevelState->header & HS_FLAG_HSTORE)
+               {
+                       i = 2 * prevLevelState->i + 1; /* VALUE, not a KEY */
+
+                       prevLevelState->array[i].entry = HENTRY_ISNEST;
+
+                       prevLevelState->array[i].entry |=
+                               (prevLevelState->array[i - 1].entry & HENTRY_POSMASK) + len;
+               }
+               else
+               {
+                       elog(PANIC, "Wrong parent");
+               }
+
+               Assert(state->ptr - curLevelState->begin <= value->size);
+               prevLevelState->i++;
+       }
+       else
+       {
+               elog(PANIC, "Wrong flags");
+       }
+}
+
+uint32
+compressHStore(HStoreValue *v, char *buffer) {
+       uint32                  l = 0;
+       CompressState   state;
+
+       state.begin = state.ptr = buffer;
+       state.maxlevel = 8;
+       state.levelstate = palloc(sizeof(*state.levelstate) * state.maxlevel);
+
+       walkUncompressedHStore(v, compressCallback, &state);
+
+       l = state.ptr - buffer;
+       Assert(l <= v->size);
+
+       return l;
+}
+
+/****************************************************************************
+ *                  Iteration-like forming hstore                           *
+ *       Note: it believ by default in already sorted keys in hash,         *
+ *     although with r == WHS_END_HASH and v == NULL  it will sort itself   *
+ ****************************************************************************/
+static ToHStoreState*
+pushState(ToHStoreState **state)
+{
+       ToHStoreState   *ns = palloc(sizeof(*ns));
+
+       ns->next = *state;
+       return ns;
+}
+
+static void
+appendArray(ToHStoreState *state, HStoreValue *v)
+{
+       HStoreValue     *a = &state->v;
+
+       Assert(a->type == hsvArray);
+
+       if (a->array.nelems >= state->size)
+       {
+               state->size *= 2;
+               a->array.elems = repalloc(a->array.elems,
+                                                                  sizeof(*a->array.elems) * state->size);
+       }
+
+       a->array.elems[a->array.nelems ++] = *v;
+
+       a->size += v->size;
+}
+
+static void
+appendKey(ToHStoreState *state, HStoreValue *v)
+{
+       HStoreValue     *h = &state->v;
+
+       Assert(h->type == hsvHash);
+
+       if (h->hash.npairs >= state->size)
+       {
+               state->size *= 2;
+               h->hash.pairs = repalloc(h->hash.pairs,
+                                                                       sizeof(*h->hash.pairs) * state->size);
+       }
+
+       h->hash.pairs[h->hash.npairs].key = *v;
+       h->hash.pairs[h->hash.npairs].order = h->hash.npairs;
+
+       h->size += v->size;
+}
+
+static void
+appendValue(ToHStoreState *state, HStoreValue *v)
+{
+
+       HStoreValue     *h = &state->v;
+
+       Assert(h->type == hsvHash);
+
+       h->hash.pairs[h->hash.npairs++].value = *v;
+
+       h->size += v->size;
+}
+
+
+HStoreValue*
+pushHStoreValue(ToHStoreState **state, int r /* WHS_* */, HStoreValue *v) {
+       HStoreValue     *h = NULL;
+
+       switch(r)
+       {
+               case WHS_BEGIN_ARRAY:
+                       *state = pushState(state);
+                       h = &(*state)->v;
+                       (*state)->v.type = hsvArray;
+                       (*state)->v.size = 3*sizeof(HEntry);
+                       (*state)->v.array.nelems = 0;
+                       (*state)->v.array.scalar = (v && v->array.scalar) ? true : false;
+                       (*state)->size = (v && v->type == hsvArray && v->array.nelems > 0)
+                                                               ? v->array.nelems : 4;
+                       (*state)->v.array.elems = palloc(sizeof(*(*state)->v.array.elems) *
+                                                                                                       (*state)->size);
+                       break;
+               case WHS_BEGIN_HASH:
+                       *state = pushState(state);
+                       h = &(*state)->v;
+                       (*state)->v.type = hsvHash;
+                       (*state)->v.size = 3*sizeof(HEntry);
+                       (*state)->v.hash.npairs = 0;
+                       (*state)->size = (v && v->type == hsvHash && v->hash.npairs > 0)
+                                                               ? v->hash.npairs : 4;
+                       (*state)->v.hash.pairs = palloc(sizeof(*(*state)->v.hash.pairs) *
+                                                                                                       (*state)->size);
+                       break;
+               case WHS_ELEM:
+                       Assert(v->type == hsvNull || v->type == hsvString ||
+                                  v->type == hsvBool || v->type == hsvNumeric ||
+                                  v->type == hsvBinary);
+                       appendArray(*state, v);
+                       break;
+               case WHS_KEY:
+                       Assert(v->type == hsvString);
+                       appendKey(*state, v);
+                       break;
+               case WHS_VALUE:
+                       Assert(v->type == hsvNull || v->type == hsvString ||
+                                  v->type == hsvBool || v->type == hsvNumeric ||
+                                  v->type == hsvBinary);
+                       appendValue(*state, v);
+                       break;
+               case WHS_END_HASH:
+                       h = &(*state)->v;
+                       if (v == NULL)
+                               uniqueHStoreValue(h);
+               case WHS_END_ARRAY:
+                       h = &(*state)->v;
+                       *state = (*state)->next;
+                       if (*state)
+                       {
+                               switch((*state)->v.type)
+                               {
+                                       case hsvArray:
+                                               appendArray(*state, h);
+                                               break;
+                                       case hsvHash:
+                                               appendValue(*state, h);
+                                               break;
+                                       default:
+                                               elog(PANIC, "wrong parent type: %d", (*state)->v.type);
+                               }
+                       }
+                       break;
+               default:
+                       elog(PANIC, "wrong type: %08x", r);
+       }
+
+       return h;
+}
+
diff --git a/sql/hstore.sql b/sql/hstore.sql
new file mode 100644 (file)
index 0000000..0b9de1d
--- /dev/null
@@ -0,0 +1,377 @@
+CREATE EXTENSION hstore;
+
+set escape_string_warning=off;
+
+--hstore;
+
+select ''::hstore;
+select 'a=>b'::hstore;
+select ' a=>b'::hstore;
+select 'a =>b'::hstore;
+select 'a=>b '::hstore;
+select 'a=> b'::hstore;
+select '"a"=>"b"'::hstore;
+select ' "a"=>"b"'::hstore;
+select '"a" =>"b"'::hstore;
+select '"a"=>"b" '::hstore;
+select '"a"=> "b"'::hstore;
+select 'aa=>bb'::hstore;
+select ' aa=>bb'::hstore;
+select 'aa =>bb'::hstore;
+select 'aa=>bb '::hstore;
+select 'aa=> bb'::hstore;
+select '"aa"=>"bb"'::hstore;
+select ' "aa"=>"bb"'::hstore;
+select '"aa" =>"bb"'::hstore;
+select '"aa"=>"bb" '::hstore;
+select '"aa"=> "bb"'::hstore;
+
+select 'aa=>bb, cc=>dd'::hstore;
+select 'aa=>bb , cc=>dd'::hstore;
+select 'aa=>bb ,cc=>dd'::hstore;
+select 'aa=>bb, "cc"=>dd'::hstore;
+select 'aa=>bb , "cc"=>dd'::hstore;
+select 'aa=>bb ,"cc"=>dd'::hstore;
+select 'aa=>"bb", cc=>dd'::hstore;
+select 'aa=>"bb" , cc=>dd'::hstore;
+select 'aa=>"bb" ,cc=>dd'::hstore;
+
+select 'aa=>null'::hstore;
+select 'aa=>NuLl'::hstore;
+select 'aa=>"NuLl"'::hstore;
+select 'aa=>nul'::hstore;
+select 'aa=>NuL'::hstore;
+select 'aa=>"NuL"'::hstore;
+
+select e'\\=a=>q=w'::hstore;
+select e'"=a"=>q\\=w'::hstore;
+select e'"\\"a"=>q>w'::hstore;
+select e'\\"a=>q"w'::hstore;
+
+select ''::hstore;
+select '       '::hstore;
+
+-- -> operator
+
+select 'aa=>b, c=>d , b=>16'::hstore->'c';
+select 'aa=>b, c=>d , b=>16'::hstore->'b';
+select 'aa=>b, c=>d , b=>16'::hstore->'aa';
+select ('aa=>b, c=>d , b=>16'::hstore->'gg') is null;
+select ('aa=>NULL, c=>d , b=>16'::hstore->'aa') is null;
+select ('aa=>"NULL", c=>d , b=>16'::hstore->'aa') is null;
+
+-- -> array operator
+
+select 'aa=>"NULL", c=>d , b=>16'::hstore -> ARRAY['aa','c'];
+select 'aa=>"NULL", c=>d , b=>16'::hstore -> ARRAY['c','aa'];
+select 'aa=>NULL, c=>d , b=>16'::hstore -> ARRAY['aa','c',null];
+select 'aa=>1, c=>3, b=>2, d=>4'::hstore -> ARRAY[['b','d'],['aa','c']];
+
+-- exists/defined
+
+select exist('a=>NULL, b=>qq', 'a');
+select exist('a=>NULL, b=>qq', 'b');
+select exist('a=>NULL, b=>qq', 'c');
+select exist('a=>"NULL", b=>qq', 'a');
+select defined('a=>NULL, b=>qq', 'a');
+select defined('a=>NULL, b=>qq', 'b');
+select defined('a=>NULL, b=>qq', 'c');
+select defined('a=>"NULL", b=>qq', 'a');
+select hstore 'a=>NULL, b=>qq' ? 'a';
+select hstore 'a=>NULL, b=>qq' ? 'b';
+select hstore 'a=>NULL, b=>qq' ? 'c';
+select hstore 'a=>"NULL", b=>qq' ? 'a';
+select hstore 'a=>NULL, b=>qq' ?| ARRAY['a','b'];
+select hstore 'a=>NULL, b=>qq' ?| ARRAY['b','a'];
+select hstore 'a=>NULL, b=>qq' ?| ARRAY['c','a'];
+select hstore 'a=>NULL, b=>qq' ?| ARRAY['c','d'];
+select hstore 'a=>NULL, b=>qq' ?| '{}'::text[];
+select hstore 'a=>NULL, b=>qq' ?& ARRAY['a','b'];
+select hstore 'a=>NULL, b=>qq' ?& ARRAY['b','a'];
+select hstore 'a=>NULL, b=>qq' ?& ARRAY['c','a'];
+select hstore 'a=>NULL, b=>qq' ?& ARRAY['c','d'];
+select hstore 'a=>NULL, b=>qq' ?& '{}'::text[];
+
+-- delete
+
+select delete('a=>1 , b=>2, c=>3'::hstore, 'a');
+select delete('a=>null , b=>2, c=>3'::hstore, 'a');
+select delete('a=>1 , b=>2, c=>3'::hstore, 'b');
+select delete('a=>1 , b=>2, c=>3'::hstore, 'c');
+select delete('a=>1 , b=>2, c=>3'::hstore, 'd');
+select 'a=>1 , b=>2, c=>3'::hstore - 'a'::text;
+select 'a=>null , b=>2, c=>3'::hstore - 'a'::text;
+select 'a=>1 , b=>2, c=>3'::hstore - 'b'::text;
+select 'a=>1 , b=>2, c=>3'::hstore - 'c'::text;
+select 'a=>1 , b=>2, c=>3'::hstore - 'd'::text;
+select pg_column_size('a=>1 , b=>2, c=>3'::hstore - 'b'::text)
+         = pg_column_size('a=>1, b=>2'::hstore);
+
+-- delete (array)
+
+select delete('a=>1 , b=>2, c=>3'::hstore, ARRAY['d','e']);
+select delete('a=>1 , b=>2, c=>3'::hstore, ARRAY['d','b']);
+select delete('a=>1 , b=>2, c=>3'::hstore, ARRAY['a','c']);
+select delete('a=>1 , b=>2, c=>3'::hstore, ARRAY[['b'],['c'],['a']]);
+select delete('a=>1 , b=>2, c=>3'::hstore, '{}'::text[]);
+select 'a=>1 , b=>2, c=>3'::hstore - ARRAY['d','e'];
+select 'a=>1 , b=>2, c=>3'::hstore - ARRAY['d','b'];
+select 'a=>1 , b=>2, c=>3'::hstore - ARRAY['a','c'];
+select 'a=>1 , b=>2, c=>3'::hstore - ARRAY[['b'],['c'],['a']];
+select 'a=>1 , b=>2, c=>3'::hstore - '{}'::text[];
+select pg_column_size('a=>1 , b=>2, c=>3'::hstore - ARRAY['a','c'])
+         = pg_column_size('b=>2'::hstore);
+select pg_column_size('a=>1 , b=>2, c=>3'::hstore - '{}'::text[])
+         = pg_column_size('a=>1, b=>2, c=>3'::hstore);
+
+-- delete (hstore)
+
+select delete('aa=>1 , b=>2, c=>3'::hstore, 'aa=>4, b=>2'::hstore);
+select delete('aa=>1 , b=>2, c=>3'::hstore, 'aa=>NULL, c=>3'::hstore);
+select delete('aa=>1 , b=>2, c=>3'::hstore, 'aa=>1, b=>2, c=>3'::hstore);
+select delete('aa=>1 , b=>2, c=>3'::hstore, 'b=>2'::hstore);
+select delete('aa=>1 , b=>2, c=>3'::hstore, ''::hstore);
+select 'aa=>1 , b=>2, c=>3'::hstore - 'aa=>4, b=>2'::hstore;
+select 'aa=>1 , b=>2, c=>3'::hstore - 'aa=>NULL, c=>3'::hstore;
+select 'aa=>1 , b=>2, c=>3'::hstore - 'aa=>1, b=>2, c=>3'::hstore;
+select 'aa=>1 , b=>2, c=>3'::hstore - 'b=>2'::hstore;
+select 'aa=>1 , b=>2, c=>3'::hstore - ''::hstore;
+select pg_column_size('a=>1 , b=>2, c=>3'::hstore - 'b=>2'::hstore)
+         = pg_column_size('a=>1, c=>3'::hstore);
+select pg_column_size('a=>1 , b=>2, c=>3'::hstore - ''::hstore)
+         = pg_column_size('a=>1, b=>2, c=>3'::hstore);
+
+-- ||
+select 'aa=>1 , b=>2, cq=>3'::hstore || 'cq=>l, b=>g, fg=>f';
+select 'aa=>1 , b=>2, cq=>3'::hstore || 'aq=>l';
+select 'aa=>1 , b=>2, cq=>3'::hstore || 'aa=>l';
+select 'aa=>1 , b=>2, cq=>3'::hstore || '';
+select ''::hstore || 'cq=>l, b=>g, fg=>f';
+select pg_column_size(''::hstore || ''::hstore) = pg_column_size(''::hstore);
+select pg_column_size('aa=>1'::hstore || 'b=>2'::hstore)
+         = pg_column_size('aa=>1, b=>2'::hstore);
+select pg_column_size('aa=>1, b=>2'::hstore || ''::hstore)
+         = pg_column_size('aa=>1, b=>2'::hstore);
+select pg_column_size(''::hstore || 'aa=>1, b=>2'::hstore)
+         = pg_column_size('aa=>1, b=>2'::hstore);
+
+-- hstore(text,text)
+select 'a=>g, b=>c'::hstore || hstore('asd', 'gf');
+select 'a=>g, b=>c'::hstore || hstore('b', 'gf');
+select 'a=>g, b=>c'::hstore || hstore('b', 'NULL');
+select 'a=>g, b=>c'::hstore || hstore('b', NULL);
+select ('a=>g, b=>c'::hstore || hstore(NULL, 'b')) is null;
+select pg_column_size(hstore('b', 'gf'))
+         = pg_column_size('b=>gf'::hstore);
+select pg_column_size('a=>g, b=>c'::hstore || hstore('b', 'gf'))
+         = pg_column_size('a=>g, b=>gf'::hstore);
+
+-- slice()
+select slice(hstore 'aa=>1, b=>2, c=>3', ARRAY['g','h','i']);
+select slice(hstore 'aa=>1, b=>2, c=>3', ARRAY['c','b']);
+select slice(hstore 'aa=>1, b=>2, c=>3', ARRAY['aa','b']);
+select slice(hstore 'aa=>1, b=>2, c=>3', ARRAY['c','b','aa']);
+select pg_column_size(slice(hstore 'aa=>1, b=>2, c=>3', ARRAY['c','b']))
+         = pg_column_size('b=>2, c=>3'::hstore);
+select pg_column_size(slice(hstore 'aa=>1, b=>2, c=>3', ARRAY['c','b','aa']))
+         = pg_column_size('aa=>1, b=>2, c=>3'::hstore);
+
+-- array input
+select '{}'::text[]::hstore;
+select ARRAY['a','g','b','h','asd']::hstore;
+select ARRAY['a','g','b','h','asd','i']::hstore;
+select ARRAY[['a','g'],['b','h'],['asd','i']]::hstore;
+select ARRAY[['a','g','b'],['h','asd','i']]::hstore;
+select ARRAY[[['a','g'],['b','h'],['asd','i']]]::hstore;
+select hstore('{}'::text[]);
+select hstore(ARRAY['a','g','b','h','asd']);
+select hstore(ARRAY['a','g','b','h','asd','i']);
+select hstore(ARRAY[['a','g'],['b','h'],['asd','i']]);
+select hstore(ARRAY[['a','g','b'],['h','asd','i']]);
+select hstore(ARRAY[[['a','g'],['b','h'],['asd','i']]]);
+select hstore('[0:5]={a,g,b,h,asd,i}'::text[]);
+select hstore('[0:2][1:2]={{a,g},{b,h},{asd,i}}'::text[]);
+
+-- pairs of arrays
+select hstore(ARRAY['a','b','asd'], ARRAY['g','h','i']);
+select hstore(ARRAY['a','b','asd'], ARRAY['g','h',NULL]);
+select hstore(ARRAY['z','y','x'], ARRAY['1','2','3']);
+select hstore(ARRAY['aaa','bb','c','d'], ARRAY[null::text,null,null,null]);
+select hstore(ARRAY['aaa','bb','c','d'], null);
+select quote_literal(hstore('{}'::text[], '{}'::text[]));
+select quote_literal(hstore('{}'::text[], null));
+select hstore(ARRAY['a'], '{}'::text[]);  -- error
+select hstore('{}'::text[], ARRAY['a']);  -- error
+select pg_column_size(hstore(ARRAY['a','b','asd'], ARRAY['g','h','i']))
+         = pg_column_size('a=>g, b=>h, asd=>i'::hstore);
+
+-- records
+select hstore(v) from (values (1, 'foo', 1.2, 3::float8)) v(a,b,c,d);
+create domain hstestdom1 as integer not null default 0;
+create table testhstore0 (a integer, b text, c numeric, d float8);
+create table testhstore1 (a integer, b text, c numeric, d float8, e hstestdom1);
+insert into testhstore0 values (1, 'foo', 1.2, 3::float8);
+insert into testhstore1 values (1, 'foo', 1.2, 3::float8);
+select hstore(v) from testhstore1 v;
+select hstore(null::testhstore0);
+select hstore(null::testhstore1);
+select pg_column_size(hstore(v))
+         = pg_column_size('a=>1, b=>"foo", c=>1.2, d=>3, e=>0'::hstore)
+  from testhstore1 v;
+select populate_record(v, hstore('c', '3.45')) from testhstore1 v;
+select populate_record(v, hstore('d', '3.45')) from testhstore1 v;
+select populate_record(v, hstore('e', '123')) from testhstore1 v;
+select populate_record(v, hstore('e', null)) from testhstore1 v;
+select populate_record(v, hstore('c', null)) from testhstore1 v;
+select populate_record(v, hstore('b', 'foo') || hstore('a', '123')) from testhstore1 v;
+select populate_record(v, hstore('b', 'foo') || hstore('e', null)) from testhstore0 v;
+select populate_record(v, hstore('b', 'foo') || hstore('e', null)) from testhstore1 v;
+select populate_record(v, '') from testhstore0 v;
+select populate_record(v, '') from testhstore1 v;
+select populate_record(null::testhstore1, hstore('c', '3.45') || hstore('a', '123'));
+select populate_record(null::testhstore1, hstore('c', '3.45') || hstore('e', '123'));
+select populate_record(null::testhstore0, '');
+select populate_record(null::testhstore1, '');
+select v #= hstore('c', '3.45') from testhstore1 v;
+select v #= hstore('d', '3.45') from testhstore1 v;
+select v #= hstore('e', '123') from testhstore1 v;
+select v #= hstore('c', null) from testhstore1 v;
+select v #= hstore('e', null) from testhstore0 v;
+select v #= hstore('e', null) from testhstore1 v;
+select v #= (hstore('b', 'foo') || hstore('a', '123')) from testhstore1 v;
+select v #= (hstore('b', 'foo') || hstore('e', '123')) from testhstore1 v;
+select v #= hstore '' from testhstore0 v;
+select v #= hstore '' from testhstore1 v;
+select null::testhstore1 #= (hstore('c', '3.45') || hstore('a', '123'));
+select null::testhstore1 #= (hstore('c', '3.45') || hstore('e', '123'));
+select null::testhstore0 #= hstore '';
+select null::testhstore1 #= hstore '';
+select v #= h from testhstore1 v, (values (hstore 'a=>123',1),('b=>foo,c=>3.21',2),('a=>null',3),('e=>123',4),('f=>blah',5)) x(h,i) order by i;
+
+-- keys/values
+select akeys('aa=>1 , b=>2, cq=>3'::hstore || 'cq=>l, b=>g, fg=>f');
+select akeys('""=>1');
+select akeys('');
+select avals('aa=>1 , b=>2, cq=>3'::hstore || 'cq=>l, b=>g, fg=>f');
+select avals('aa=>1 , b=>2, cq=>3'::hstore || 'cq=>l, b=>g, fg=>NULL');
+select avals('""=>1');
+select avals('');
+
+select hstore_to_array('aa=>1, cq=>l, b=>g, fg=>NULL'::hstore);
+select %% 'aa=>1, cq=>l, b=>g, fg=>NULL';
+
+select hstore_to_matrix('aa=>1, cq=>l, b=>g, fg=>NULL'::hstore);
+select %# 'aa=>1, cq=>l, b=>g, fg=>NULL';
+
+select * from skeys('aa=>1 , b=>2, cq=>3'::hstore || 'cq=>l, b=>g, fg=>f');
+select * from skeys('""=>1');
+select * from skeys('');
+select * from svals('aa=>1 , b=>2, cq=>3'::hstore || 'cq=>l, b=>g, fg=>f');
+select *, svals is null from svals('aa=>1 , b=>2, cq=>3'::hstore || 'cq=>l, b=>g, fg=>NULL');
+select * from svals('""=>1');
+select * from svals('');
+
+select * from each('aaa=>bq, b=>NULL, ""=>1 ');
+
+-- @>
+select 'a=>b, b=>1, c=>NULL'::hstore @> 'a=>b';
+select 'a=>b, b=>1, c=>NULL'::hstore @> 'a=>b, c=>NULL';
+select 'a=>b, b=>1, c=>NULL'::hstore @> 'a=>b, g=>NULL';
+select 'a=>b, b=>1, c=>NULL'::hstore @> 'g=>NULL';
+select 'a=>b, b=>1, c=>NULL'::hstore @> 'a=>c';
+select 'a=>b, b=>1, c=>NULL'::hstore @> 'a=>b';
+select 'a=>b, b=>1, c=>NULL'::hstore @> 'a=>b, c=>q';
+
+CREATE TABLE testhstore (h hstore);
+\copy testhstore from 'data/hstore.data'
+
+select count(*) from testhstore where h @> 'wait=>NULL';
+select count(*) from testhstore where h @> 'wait=>CC';
+select count(*) from testhstore where h @> 'wait=>CC, public=>t';
+select count(*) from testhstore where h @> 'age=>25';
+select count(*) from testhstore where h @> 'age=>25.0';
+select count(*) from testhstore where h @> 'age=>+25.00';
+select count(*) from testhstore where h ? 'public';
+select count(*) from testhstore where h ?| ARRAY['public','disabled'];
+select count(*) from testhstore where h ?& ARRAY['public','disabled'];
+
+create index hidx on testhstore using gist(h);
+set enable_seqscan=off;
+
+select count(*) from testhstore where h @> 'wait=>NULL';
+select count(*) from testhstore where h @> 'wait=>CC';
+select count(*) from testhstore where h @> 'wait=>CC, public=>t';
+select count(*) from testhstore where h @> 'age=>25';
+select count(*) from testhstore where h @> 'age=>25.0';
+select count(*) from testhstore where h @> 'age=>+25.00';
+select count(*) from testhstore where h ? 'public';
+select count(*) from testhstore where h ?| ARRAY['public','disabled'];
+select count(*) from testhstore where h ?& ARRAY['public','disabled'];
+
+RESET enable_seqscan;
+
+drop index hidx;
+create index hidx on testhstore using gin (h);
+set enable_seqscan=off;
+
+select count(*) from testhstore where h @> 'wait=>NULL';
+select count(*) from testhstore where h @> 'wait=>CC';
+select count(*) from testhstore where h @> 'wait=>CC, public=>t';
+select count(*) from testhstore where h @> 'age=>25';
+select count(*) from testhstore where h @> 'age=>25.0';
+select count(*) from testhstore where h @> 'age=>+25.00';
+select count(*) from testhstore where h ? 'public';
+select count(*) from testhstore where h ?| ARRAY['public','disabled'];
+select count(*) from testhstore where h ?& ARRAY['public','disabled'];
+
+RESET enable_seqscan;
+
+select count(*) from (select (each(h)).key from testhstore) as wow ;
+select key, count(*) from (select (each(h)).key from testhstore) as wow group by key order by count desc, key;
+
+-- sort/hash
+select count(distinct h) from testhstore;
+set enable_hashagg = false;
+select count(*) from (select h from (select * from testhstore union all select * from testhstore) hs group by h) hs2;
+set enable_hashagg = true;
+set enable_sort = false;
+select count(*) from (select h from (select * from testhstore union all select * from testhstore) hs group by h) hs2;
+select distinct * from (values (hstore '' || ''),('')) v(h);
+set enable_sort = true;
+
+RESET enable_hashagg;
+RESET enable_sort;
+
+-- btree
+drop index hidx;
+create index hidx on testhstore using btree (h);
+set enable_seqscan=off;
+
+select count(*) from testhstore where h #># 'p=>1';
+select count(*) from testhstore where h = 'pos=>98, line=>371, node=>CBA, indexed=>t';
+
+--gin hash
+drop index hidx;
+create index hidx on testhstore using gin (h gin_hstore_hash_ops);
+set enable_seqscan=off;
+
+select count(*) from testhstore where h @> 'wait=>NULL';
+select count(*) from testhstore where h @> 'wait=>CC';
+select count(*) from testhstore where h @> 'wait=>CC, public=>t';
+select count(*) from testhstore where h @> 'age=>25';
+select count(*) from testhstore where h @> 'age=>25.0';
+select count(*) from testhstore where h @> 'age=>+25.00';
+
+RESET enable_seqscan;
+drop index hidx;
+
+-- json
+select hstore_to_json('"a key" =>1, b => t, c => null, d=> 12345, e => 012345, f=> 1.234, g=> 2.345e+4');
+select cast( hstore  '"a key" =>1, b => t, c => null, d=> 12345, e => 012345, f=> 1.234, g=> 2.345e+4' as json);
+select hstore_to_json_loose('"a key" =>1, b => t, c => null, d=> 12345, e => 012345, f=> 1.234, g=> 2.345e+4');
+
+create table test_json_agg (f1 text, f2 hstore);
+insert into test_json_agg values ('rec1','"a key" =>1, b => t, c => null, d=> 12345, e => 012345, f=> 1.234, g=> 2.345e+4'),
+       ('rec2','"a key" =>2, b => f, c => "null", d=> -12345, e => 012345.6, f=> -1.234, g=> 0.345e-4');
+select json_agg(q) from test_json_agg q;
+select json_agg(q) from (select f1, hstore_to_json_loose(f2) as f2 from test_json_agg) q;
diff --git a/sql/nested.sql b/sql/nested.sql
new file mode 100644 (file)
index 0000000..a998650
--- /dev/null
@@ -0,0 +1,480 @@
+
+SELECT 'ff => {a=>12, b=>16}'::hstore;
+
+SELECT 'ff => {a=>12, b=>16}, qq=> 123'::hstore;
+
+SELECT 'aa => {a,aaa}, qq=>{ a=>12, b=>16 , c=> { c1, c2}, d=>{d1=>d1, d2=>d2, d1=>d3} }'::hstore;
+
+SELECT '"aa"=>{a,aaa}, "qq"=>{"a"=>"12", "b"=>"16", "c"=>{c1,c2}, "d"=>{"d1"=>"d1", "d2"=>"d2"}}'::hstore;
+
+SELECT '"aa"=>{a,aaa}, "qq"=>{"a"=>"12", "b"=>"16", "c"=>{c1,c2,{c3},{c4=>4}}, "d"=>{"d1"=>"d1", "d2"=>"d2"}}'::hstore;
+
+SELECT 'ff => {a,aaa}'::hstore;
+
+
+select 'null'::hstore;
+select '{null}'::hstore;
+select ''::hstore;
+select '{}'::hstore;
+
+--test optional outer braces
+SELECT 'a=>1'::hstore;
+SELECT '{a=>1}'::hstore;
+SELECT '{a,b}'::hstore;
+SELECT '{a,{b}}'::hstore;
+SELECT '{{a},b}'::hstore;
+SELECT '{a,{b},{c}}'::hstore;
+SELECT '{{a},{b},c}'::hstore;
+SELECT '{{a},b,{c}}'::hstore;
+SELECT '{a,{b=>1}}'::hstore;
+SELECT '{{a},{b=>1}}'::hstore;
+SELECT 'a'::hstore;
+SELECT '{a}'::hstore;
+SELECT ''::hstore;
+SELECT '{}'::hstore;
+
+--nested json
+
+SELECT hstore_to_json('a=>1');
+SELECT hstore_to_json('{a=>1}');
+SELECT hstore_to_json('{a,b}');
+SELECT hstore_to_json('{a,{b}}');
+SELECT hstore_to_json('{{a},b}');
+SELECT hstore_to_json('{a,{b},{c}}');
+SELECT hstore_to_json('{{a},{b},c}');
+SELECT hstore_to_json('{{a},b,{c}}');
+SELECT hstore_to_json('{a,{b=>1}}');
+SELECT hstore_to_json('{{a},{b=>1}}');
+SELECT hstore_to_json('{{a},{b=>1},{c}}');
+SELECT hstore_to_json('a');
+SELECT hstore_to_json('{a}');
+SELECT hstore_to_json('');
+SELECT hstore_to_json('{}');
+
+SELECT hstore_to_json('"aa"=>{a,aaa}, "qq"=>{"a"=>"12", "b"=>"16", "c"=>{c1,c2,{c3},{c4=>4}}, "d"=>{"d1"=>"d1", "d2"=>"d2"}}'::hstore);
+
+--
+
+SELECT 'ff => {a=>12, b=>16}, qq=> 123, x=>{1,2}, Y=>NULL'::hstore -> 'ff', 
+          'ff => {a=>12, b=>16}, qq=> 123, x=>{1,2}, Y=>NULL'::hstore -> 'qq', 
+          ('ff => {a=>12, b=>16}, qq=> 123, x=>{1,2}, Y=>NULL'::hstore -> 'Y') IS NULL AS t, 
+          'ff => {a=>12, b=>16}, qq=> 123, x=>{1,2}, Y=>NULL'::hstore -> 'x'; 
+
+SELECT '[ a, b, c, d]'::hstore -> 'a';
+--
+
+CREATE TABLE testtype (i int, h hstore, a int[], j json);
+INSERT INTO testtype VALUES (1, 'a=>1', '{1,2,3}', '{"x": 2}');
+
+SELECT populate_record(v, 'i=>2'::hstore) FROM testtype v;
+SELECT populate_record(v, 'i=>2, a=>{7,8,9}'::hstore) FROM testtype v;
+SELECT populate_record(v, 'i=>2, h=>{b=>3}, a=>{7,8,9}'::hstore) FROM testtype v;
+SELECT populate_record(v, 'i=>2, h=>{b=>3}, a=>{7,8,9}, j=>{a=>{1,2,3}}'::hstore) FROM testtype v;
+
+--complex delete
+
+SELECT 'b=>{a,c}'::hstore - 'a'::text;
+SELECT 'b=>{a,c}, a=>1'::hstore - 'a'::text;
+SELECT 'b=>{a,c}, a=>[2,3]'::hstore - 'a'::text;
+SELECT 'b=>{a,c}, a=>[2,3]'::hstore - 'a'::text;
+SELECT '[2,3,a]'::hstore - 'a'::text;
+SELECT '[a,2,3,a]'::hstore - 'a'::text;
+SELECT '[a,a]'::hstore - 'a'::text;
+SELECT '[a]'::hstore - 'a'::text;
+SELECT 'a=>1'::hstore - 'a'::text;
+SELECT ''::hstore - 'a'::text;
+
+SELECT '{a, 1 , b,2, c,3}'::hstore - ARRAY['d','b'];
+
+SELECT '{a=>{1,2}, v=>23, b=>c}'::hstore - 'v'::hstore;
+SELECT '{a=>{1,2}, v=>23, b=>c}'::hstore - 'v=>23'::hstore;
+SELECT '{a=>{1,2}, v=>23, b=>c}'::hstore - 'v=>{1,2}'::hstore;
+SELECT '{a=>{1,2}, v=>23, b=>c}'::hstore - 'a=>{1,2}'::hstore;
+SELECT '{a, {1,2}, v, 23, b, c}'::hstore - 'v'::hstore;
+SELECT '{a, {1,2}, v, 23, b, c}'::hstore - 'v=>23'::hstore;
+SELECT '{a, {1,2}, v, 23, b, c}'::hstore - '[v,23]'::hstore;
+SELECT '{a, {1,2}, v, 23, b, c}'::hstore - '[v,{1,2}]'::hstore;
+
+--joining
+
+SELECT 'aa=>1 , b=>2, cq=>3'::hstore || '{cq,l, b,g, fg,f, 1,2}'::hstore;
+SELECT '{aa,1 , b,2, cq,3}'::hstore || '{cq,l, b,g, fg,f, 1,2}'::hstore;
+SELECT  'x'::hstore || 'a=>"1"':: hstore;
+
+--slice
+SELECT slice_array(hstore 'aa=>1, b=>2, c=>3', ARRAY['g','h','i']);
+SELECT slice_array(hstore '{aa,1, b,2, c,3}', ARRAY['g','h','i']);
+SELECT slice_array(hstore 'aa=>1, b=>2, c=>3', ARRAY['b','c']);
+SELECT slice_array(hstore '{aa,1, b,2, c,3}', ARRAY['b','c']);
+SELECT slice_array(hstore 'aa=>1, b=>{2=>1}, c=>{1,2}', ARRAY['b','c']);
+
+SELECT slice(hstore '{aa=>1, b=>2, c=>3}', ARRAY['g','h','i']);
+SELECT slice(hstore '{aa,1, b,2, c,3}', ARRAY['g','h','i']);
+SELECT slice(hstore '{aa=>1, b=>2, c=>3}', ARRAY['b','c']);
+SELECT slice(hstore '{aa,1, b,2, c,3}', ARRAY['b','c']);
+SELECT slice(hstore '{aa=>1, b=>{2=>1}, c=>{1,2}}', ARRAY['b','c']);
+
+--to array
+SELECT %% 'aa=>1, cq=>l, b=>{a,n}, fg=>NULL';
+SELECT %% '{aa,1, cq,l, b,g, fg,NULL}';
+SELECT hstore_to_matrix( 'aa=>1, cq=>l, b=>{a,n}, fg=>NULL');
+SELECT hstore_to_matrix( '{aa,1, cq,l, b,g, fg,NULL}');
+
+
+--contains
+SELECT 'a=>b'::hstore @> 'a=>b, c=>b';
+SELECT 'a=>b, c=>b'::hstore @> 'a=>b';
+SELECT 'a=>{1,2}, c=>b'::hstore @> 'a=>{1,2}';
+SELECT 'a=>{2,1}, c=>b'::hstore @> 'a=>{1,2}';
+SELECT 'a=>{1=>2}, c=>b'::hstore @> 'a=>{1,2}';
+SELECT 'a=>{2=>1}, c=>b'::hstore @> 'a=>{1,2}';
+SELECT 'a=>{1=>2}, c=>b'::hstore @> 'a=>{1=>2}';
+SELECT 'a=>{2=>1}, c=>b'::hstore @> 'a=>{1=>2}';
+SELECT '{a,b}'::hstore @> '{a,b, c,b}';
+SELECT '{a,b, c,b}'::hstore @> '{a,b}';
+SELECT '{a,b, c,{1,2}}'::hstore @> '{a,{1,2}}';
+SELECT '{a,b, c,{1,2}}'::hstore @> '{b,{1,2}}';
+
+SELECT 'a=>{1,2}, c=>b'::hstore @> 'a=>{1}';
+SELECT 'a=>{1,2}, c=>b'::hstore @> 'a=>{2}';
+SELECT 'a=>{1,2}, c=>b'::hstore @> 'a=>{3}';
+SELECT 'a=>{1,2,{c=>3, x=>4}}, c=>b'::hstore @> 'a=>{{c=>3}}';
+SELECT 'a=>{1,2,{c=>3, x=>4}}, c=>b'::hstore @> 'a=>{{x=>4}}';
+SELECT 'a=>{1,2,{c=>3, x=>4}}, c=>b'::hstore @> 'a=>{{x=>4},3}';
+SELECT 'a=>{1,2,{c=>3, x=>4}}, c=>b'::hstore @> 'a=>{{x=>4},1}';
+
+-- %>
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 'n';
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 'a';
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 'b';
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 'c';
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 'd';
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 'd' %> '1';
+
+SELECT '[1,2,3,{a,b}]'::hstore %> '1';
+SELECT '["1",2,3,{a,b}]'::hstore %> '1';
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 5;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 4;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 3;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 2;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 1;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore %> 0;
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore %> 5;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore %> 4;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore %> 3;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore %> 2;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore %> 1;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore %> 0;
+
+-- ->
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> 5;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> 4;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> 3;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> 2;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> 1;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> 0;
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> 5;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> 4;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> 3;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> 2;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> 1;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> 0;
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> -6;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> -5;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> -4;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> -3;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> -2;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore -> -1;
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> -6;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> -5;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> -4;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> -3;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> -2;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore -> -1;
+
+-- #>
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{0}';
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{a}';
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{c}';
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{c, 0}';
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{c, 1}';
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{c, 2}';
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{c, 3}';
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{c, -1}';
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{c, -2}';
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{c, -3}';
+SELECT 'a=>b, c=>{1,2,3}'::hstore #> '{c, -4}';
+
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #> '{0}';
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #> '{3}';
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #> '{4}';
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #> '{4,5}';
+
+-- #%>
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{0}';
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{a}';
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{c}';
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{c, 0}';
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{c, 1}';
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{c, 2}';
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{c, 3}';
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{c, -1}';
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{c, -2}';
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{c, -3}';
+SELECT 'a=>b, c=>{1,2,3}'::hstore #%> '{c, -4}';
+
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #%> '{0}';
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #%> '{3}';
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #%> '{4}';
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #%> '{4,5}';
+
+-- ?
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? 5;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? 4;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? 3;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? 2;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? 1;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? 0;
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? 5;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? 4;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? 3;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? 2;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? 1;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? 0;
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? -6;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? -5;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? -4;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? -3;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? -2;
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore ? -1;
+
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? -6;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? -5;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? -4;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? -3;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? -2;
+SELECT '[a,b, c,{1,2}, NULL]'::hstore ? -1;
+
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{0}'::text[];
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{a}'::text[];
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{c}'::text[];
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{b}'::text[];
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{c, 0}'::text[];
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{c, 1}'::text[];
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{c, 2}'::text[];
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{c, 3}'::text[];
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{c, -1}'::text[];
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{c, -2}'::text[];
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{c, -3}'::text[];
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{c, -4}'::text[];
+SELECT 'a=>b, c=>{1,2,3}'::hstore #? '{c, -5}'::text[];
+
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #? '{0}'::text[];
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #? '{3}'::text[];
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #? '{4}'::text[];
+SELECT '[0, 1, 2, {3,4}, {5=>five}]'::hstore #? '{4,5}'::text[];
+
+--deep delete
+
+SELECT 'a=>1'::hstore #- '{x}';
+SELECT 'a=>1'::hstore #- '{a}';
+SELECT 'a=>1'::hstore #- '{NULL}';
+SELECT 'a=>1, b=>2, c=>3'::hstore #- '{x}';
+SELECT 'a=>1, b=>2, c=>3'::hstore #- '{a}';
+SELECT 'a=>1, b=>2, c=>3'::hstore #- '{b}';
+SELECT 'a=>1, b=>2, c=>3'::hstore #- '{c}';
+SELECT 'a=>1'::hstore #- '{x,1}';
+SELECT 'a=>1'::hstore #- '{a,1}';
+SELECT 'a=>1'::hstore #- '{NULL,1}';
+SELECT 'a=>1, b=>2, c=>3'::hstore #- '{x,1}';
+SELECT 'a=>1, b=>2, c=>3'::hstore #- '{a,1}';
+SELECT 'a=>1, b=>2, c=>3'::hstore #- '{b,1}';
+SELECT 'a=>1, b=>2, c=>3'::hstore #- '{c,1}';
+
+SELECT '[a]'::hstore #- '{2}';
+SELECT '[a]'::hstore #- '{1}';
+SELECT '[a]'::hstore #- '{0}';
+SELECT '[a]'::hstore #- '{-1}';
+SELECT '[a]'::hstore #- '{-2}';
+
+SELECT '[a,b,c]'::hstore #- '{3}';
+SELECT '[a,b,c]'::hstore #- '{2}';
+SELECT '[a,b,c]'::hstore #- '{1}';
+SELECT '[a,b,c]'::hstore #- '{0}';
+SELECT '[a,b,c]'::hstore #- '{-1}';
+SELECT '[a,b,c]'::hstore #- '{-2}';
+SELECT '[a,b,c]'::hstore #- '{-3}';
+SELECT '[a,b,c]'::hstore #- '{-4}';
+
+SELECT '[a,b,c]'::hstore #- '{0,0}';
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{x}';
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{a}';
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{b}';
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{c}';
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{d}';
+
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{b, 0}';
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{b, -1}';
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{b, -1}' #- '{b, -1}';
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{c, 1}';
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{c, 2}';
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{d, 1, -2}';
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{d, 1, 1}';
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{d, 1, 0}';
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{d, 1, 0}' #- '{d, 1, 0}';
+SELECT 'n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore #- '{d, 1, 0}' #- '{d, 1, 0}' #- '{d, 1, 0}';
+
+-- delete(int)
+
+SELECT '[a,b,c]'::hstore - 3;
+SELECT '[a,b,c]'::hstore - 2;
+SELECT '[a,b,c]'::hstore - 1;
+SELECT '[a,b,c]'::hstore - 0;
+SELECT '[a,b,c]'::hstore - -1;
+SELECT '[a,b,c]'::hstore - -2;
+SELECT '[a,b,c]'::hstore - -3;
+SELECT '[a,b,c]'::hstore - -4;
+
+SELECT 'a=>1, b=>2, c=>3'::hstore - 3;
+SELECT 'a=>1, b=>2, c=>3'::hstore - 2;
+SELECT 'a=>1, b=>2, c=>3'::hstore - 1;
+SELECT 'a=>1, b=>2, c=>3'::hstore - 0;
+SELECT 'a=>1, b=>2, c=>3'::hstore - -1;
+SELECT 'a=>1, b=>2, c=>3'::hstore - -2;
+SELECT 'a=>1, b=>2, c=>3'::hstore - -3;
+SELECT 'a=>1, b=>2, c=>3'::hstore - -4;
+
+--replace
+
+SELECT replace('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{n}', '{1,2,3}');
+SELECT replace('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{b,-1}', '{1,2,3}');
+SELECT replace('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{d,1,0}', '{1,2,3}');
+SELECT replace('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{d,NULL,0}', '{1,2,3}');
+
+--deep concat
+
+SELECT concat_path('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{}', 'n=>not_null');
+SELECT concat_path('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{n}', 'n=>not_null');
+SELECT concat_path('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{n}', 'not_null');
+SELECT concat_path('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{n}', '{not_null}');
+SELECT concat_path('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{}', 'b=>{3,4}');
+SELECT concat_path('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{b}', '{3,4}');
+SELECT concat_path('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{d,1}', '{4,5}');
+SELECT concat_path('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{d,1}', '4=>5');
+SELECT concat_path('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{d}', '2=>{4,5}');
+SELECT concat_path('n=>NULL, a=>1, b=>{1,2}, c=>{1=>2}, d=>{1=>{2,3}}'::hstore, '{NULL,1}', '4=>5');
+SELECT concat_path('x'::hstore, '{}'::text[], 'a=>"1"':: hstore);
+
+--cast 
+
+SELECT ('{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}'::text)::hstore AS err;
+SELECT ('{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}'::json)::hstore AS ok;
+
+--hvals
+
+SELECT q->'tags' FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore) AS q;
+
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{}') AS q;
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-3}') AS q;
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-2}') AS q;
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-1}') AS q;
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{0}') AS q;
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{1}') AS q;
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{2}') AS q;
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{NULL}') AS q;
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-3,tags}') AS q;
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-2,tags}') AS q;
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-1,tags}') AS q;
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{0,tags}') AS q;
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{1,tags}') AS q;
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{2,tags}') AS q;
+SELECT q FROM hvals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{NULL,tags}') AS q;
+
+SELECT q FROM hvals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{}') AS q;
+SELECT q FROM hvals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{1}') AS q;
+SELECT q FROM hvals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{a}') AS q;
+SELECT q FROM hvals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{b}') AS q;
+SELECT q FROM hvals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{c}') AS q;
+SELECT q FROM hvals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{NULL}') AS q;
+SELECT q FROM hvals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{a,c}') AS q;
+SELECT q FROM hvals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{NULL,c}') AS q;
+SELECT q FROM hvals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{b,NULL}') AS q;
+SELECT q FROM hvals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{NULL,1}') AS q;
+SELECT q FROM hvals('a=>{b=>c, c=>b, 1=>first}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{NULL,1}') AS q;
+
+--svals path
+
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{}') AS q;
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-3}') AS q;
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-2}') AS q;
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-1}') AS q;
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{0}') AS q;
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{1}') AS q;
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{2}') AS q;
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{NULL}') AS q;
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-3,tags}') AS q;
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-2,tags}') AS q;
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{-1,tags}') AS q;
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{0,tags}') AS q;
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{1,tags}') AS q;
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{2,tags}') AS q;
+SELECT q FROM svals('{{tags=>1, sh=>2}, {tags=>3, sh=>4}}'::hstore, '{NULL,tags}') AS q;
+
+SELECT q FROM svals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{}') AS q;
+SELECT q FROM svals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{1}') AS q;
+SELECT q FROM svals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{a}') AS q;
+SELECT q FROM svals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{b}') AS q;
+SELECT q FROM svals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{c}') AS q;
+SELECT q FROM svals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{NULL}') AS q;
+SELECT q FROM svals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{a,c}') AS q;
+SELECT q FROM svals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{NULL,c}') AS q;
+SELECT q FROM svals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{b,NULL}') AS q;
+SELECT q FROM svals('a=>{b=>c, c=>b}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{NULL,1}') AS q;
+SELECT q FROM svals('a=>{b=>c, c=>b, 1=>first}, b=>{1,2}, c=>cc, 1=>first'::hstore, '{NULL,1}') AS q;
+
+--each
+
+SELECT * FROM each('a=>b, c=>cc'::hstore) AS q;
+SELECT * FROM each('[a, b, c, cc]'::hstore) AS q;
+SELECT * FROM each('a=>{b=>c, c=>b, 1=>first}, b=>{1,2}, c=>cc, 1=>first, n=>null'::hstore) AS q;
+
+SELECT * FROM each_hstore('a=>b, c=>cc'::hstore) AS q;
+SELECT * FROM each_hstore('[a, b, c, cc]'::hstore) AS q;
+SELECT * FROM each_hstore('a=>{b=>c, c=>b, 1=>first}, b=>{1,2}, c=>cc, 1=>first, n=>null'::hstore) AS q;
+
+--decoration
+
+SELECT 'a=>1, b=>{c=>3}, d=>[4,[5]]'::hstore AS h, '[a, {b=>c}, [c, d, e]]'::hstore AS a;
+
+SET hstore.pretty_print = true;
+SELECT 'a=>1, b=>{c=>3}, d=>[4,[5]], e=>[1,2,3,4], f=>g, g=>j'::hstore AS h, 
+          '[a, {b=>c, c=>d}, [c, d, e, [1,2], h, {f=>g, g=>f}]]'::hstore AS a;
+RESET hstore.pretty_print;
+
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore);
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, loose := true );
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, root_hash_decorated := true );
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, array_curly_braces := true );
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, json := true );
+
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, json := true, loose := true );
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, json := true, root_hash_decorated := true );
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, json := true, array_curly_braces := true );
+
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, loose := true, root_hash_decorated := true );
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, loose := true, array_curly_braces := true );
+
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, root_hash_decorated := true, array_curly_braces := true );
+SELECT hstore_print('a=>t, f=>t, t=>"f", arr=>[1,2,3,"3",x], 123=>string'::hstore, root_hash_decorated := true, array_curly_braces := true, loose := true);
diff --git a/sql/types.sql b/sql/types.sql
new file mode 100644 (file)
index 0000000..b441f15
--- /dev/null
@@ -0,0 +1,152 @@
+SELECT '"foo"=>true'::hstore;
+SELECT 'foo=>true'::hstore;
+SELECT '"true"=>true'::hstore;
+SELECT 'true=>true'::hstore;
+SELECT '"t"=>true'::hstore;
+SELECT 't=>true'::hstore;
+SELECT '"false"=>true'::hstore;
+SELECT 'false=>true'::hstore;
+SELECT '"f"=>true'::hstore;
+SELECT 'f=>true'::hstore;
+
+SELECT '"foo"=>false'::hstore;
+SELECT 'foo=>false'::hstore;
+SELECT '"false"=>false'::hstore;
+SELECT 'false=>false'::hstore;
+SELECT '"t"=>false'::hstore;
+SELECT 't=>false'::hstore;
+SELECT '"false"=>false'::hstore;
+SELECT 'false=>false'::hstore;
+SELECT '"f"=>false'::hstore;
+SELECT 'f=>false'::hstore;
+
+SELECT '"1"=>x'::hstore;
+SELECT '1=>x'::hstore;
+SELECT 'foo=>1'::hstore;
+SELECT 'foo=>1.'::hstore;
+SELECT 'foo=>1.0'::hstore;
+SELECT 'foo=>1.01'::hstore;
+SELECT 'foo=>1.01e'::hstore;
+SELECT 'foo=>1.01e1'::hstore;
+SELECT 'foo=>1.01e+1'::hstore;
+SELECT 'foo=>1.01e-1'::hstore;
+SELECT 'foo=>.1'::hstore;
+SELECT 'foo=>.1e'::hstore;
+SELECT 'foo=>.1e1'::hstore;
+SELECT 'foo=>.1e+1'::hstore;
+SELECT 'foo=>.1e-1'::hstore;
+SELECT 'foo=>0.1e-1'::hstore;
+SELECT 'foo=>00.1e-1'::hstore;
+
+SELECT 'foo=>+1'::hstore;
+SELECT 'foo=>+1.'::hstore;
+SELECT 'foo=>+1.0'::hstore;
+SELECT 'foo=>+1.01'::hstore;
+SELECT 'foo=>+1.01e'::hstore;
+SELECT 'foo=>+1.01e1'::hstore;
+SELECT 'foo=>+1.01e+1'::hstore;
+SELECT 'foo=>+1.01e-1'::hstore;
+SELECT 'foo=>+.1'::hstore;
+SELECT 'foo=>+.1e'::hstore;
+SELECT 'foo=>+.1e1'::hstore;
+SELECT 'foo=>+.1e+1'::hstore;
+SELECT 'foo=>+.1e-1'::hstore;
+
+SELECT 'foo=>-1'::hstore;
+SELECT 'foo=>-1.'::hstore;
+SELECT 'foo=>-1.0'::hstore;
+SELECT 'foo=>-1.01'::hstore;
+SELECT 'foo=>-1.01e'::hstore;
+SELECT 'foo=>-1.01e1'::hstore;
+SELECT 'foo=>-1.01e+1'::hstore;
+SELECT 'foo=>-1.01e-1'::hstore;
+SELECT 'foo=>-.1'::hstore;
+SELECT 'foo=>-.1e'::hstore;
+SELECT 'foo=>-.1e1'::hstore;
+SELECT 'foo=>-.1e+1'::hstore;
+SELECT 'foo=>-.1e-1'::hstore;
+
+SELECT 'foo=>1e2000'::hstore;
+
+SELECT 'foo=>1e12, bar=>x'::hstore ^> 'foo';
+SELECT 'foo=>1e12, bar=>x'::hstore ^> 'bar';
+SELECT 'foo=>1e12, bar=>x'::hstore ^> 0;
+SELECT 'foo=>1e12, bar=>x'::hstore ^> 1;
+
+SELECT '[foo, 1e12, bar, x]'::hstore ^> 'foo';
+SELECT '[foo, 1e12, bar, x]'::hstore ^> 'bar';
+SELECT '[foo, 1e12, bar, x]'::hstore ^> 0;
+SELECT '[foo, 1e12, bar, x]'::hstore ^> 1;
+
+SELECT 'foo=>{x, 1e-12}'::hstore #^> '{foo, 0}';
+SELECT 'foo=>{x, 1e-12}'::hstore #^> '{foo, 1}';
+
+SELECT 'foo=>t, bar=>x'::hstore ?> 'foo';
+SELECT 'foo=>t, bar=>x'::hstore ?> 'bar';
+SELECT 'foo=>t, bar=>x'::hstore ?> 0;
+SELECT 'foo=>t, bar=>x'::hstore ?> 1;
+
+SELECT '[foo, t, bar, x]'::hstore ?> 'foo';
+SELECT '[foo, t, bar, x]'::hstore ?> 'bar';
+SELECT '[foo, t, bar, x]'::hstore ?> 0;
+SELECT '[foo, t, bar, x]'::hstore ?> 1;
+
+SELECT 'foo=>{x, t}'::hstore #?> '{foo, 0}';
+SELECT 'foo=>{x, t}'::hstore #?> '{foo, 1}';
+
+SELECT 'foo=>f, bar=>x'::hstore ?> 'foo';
+SELECT 'foo=>f, bar=>x'::hstore ?> 'bar';
+SELECT 'foo=>f, bar=>x'::hstore ?> 0;
+SELECT 'foo=>f, bar=>x'::hstore ?> 1;
+
+SELECT '[foo, f, bar, x]'::hstore ?> 'foo';
+SELECT '[foo, f, bar, x]'::hstore ?> 'bar';
+SELECT '[foo, f, bar, x]'::hstore ?> 0;
+SELECT '[foo, f, bar, x]'::hstore ?> 1;
+
+SELECT 'foo=>{x, f}'::hstore #?> '{foo, 0}';
+SELECT 'foo=>{x, f}'::hstore #?> '{foo, 1}';
+
+
+SELECT hstore_typeof('a=>b') AS hash;
+SELECT hstore_typeof('{a=>b}') AS hash;
+SELECT hstore_typeof('{a, b}') AS array;
+SELECT hstore_typeof('{{a=>b}}') AS array;
+SELECT hstore_typeof('[a, b]') AS array;
+SELECT hstore_typeof('') AS "NULL";
+SELECT hstore_typeof('NULL') AS "null";
+SELECT hstore_typeof('1.0') AS numeric;
+SELECT hstore_typeof('t') AS bool;
+SELECT hstore_typeof('f') AS bool;
+
+SELECT hstore('xxx', 't'::bool);
+SELECT hstore('xxx', 'f'::bool);
+
+SELECT hstore('xxx', 3.14);
+SELECT hstore('xxx', 3.14::numeric);
+SELECT hstore('xxx', '3.14'::numeric);
+
+SELECT hstore(NULL);
+SELECT hstore('NULL');
+
+SELECT hstore('t'::bool) AS "true", hstore('f'::bool) AS "false";
+
+SELECT hstore(3.14), hstore(3.14::numeric), hstore('3.14'::numeric);
+
+SELECT hstore('xxx', 'foo=>t, bar=>3.14, zzz=>xxx'::hstore);
+
+SELECT array_to_hstore('{{1,1,4},{23,3,5}}'::int2[]);
+SELECT array_to_hstore('{{1,1,4},{23,3,5}}'::int4[]);
+SELECT array_to_hstore('{{1,1,4},{23,3,5}}'::int8[]);
+SELECT array_to_hstore('{{1,1,4},{23,3,5}}'::float4[]);
+SELECT array_to_hstore('{{1,1,4},{23,3,5}}'::float8[]);
+SELECT array_to_hstore('{{1,1,f},{f,t,NULL}}'::bool[]);
+SELECT array_to_hstore('{{1,1,4},{23,3,5}}'::text[]);
+SELECT array_to_hstore('{{1,1,4},{23,3,5}}'::varchar[]);
+
+SELECT array_to_hstore('{{{1,11},{1,1},{4,41}},{{23,231},{3,31},{5,51}}}'::int4[]);
+SELECT hstore('array', array_to_hstore('{{{1,11},{1,1},{4,41}},{{23,231},{3,31},{5,51}}}'::int4[]));
+
+SELECT 'a=>"00012333", b=>"12233", c=>00012333, d=>12233'::hstore;
+SELECT hstore_to_json('a=>"00012333", b=>"12233", c=>00012333, d=>12233'::hstore);
+SELECT hstore_to_json_loose('a=>"00012333", b=>"12233", c=>00012333, d=>12233'::hstore);