pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Nikita Glukhov <n.gluhov@postgrespro.ru>
To: Alexander Korotkov <a.korotkov@postgrespro.ru>
Cc: Tomas Vondra <tomas.vondra@2ndquadrant.com>
Cc: Andres Freund <andres@anarazel.de>
Cc: Oleg Bartunov <obartunov@postgrespro.ru>
Cc: Michael Paquier <michael@paquier.xyz>
Cc: Stas Kelvich <s.kelvich@postgrespro.ru>
Cc: PostgreSQL-development <pgsql-hackers@postgresql.org>
Cc: Thomas Munro <thomas.munro@enterprisedb.com>
Cc: David Steele <david@pgmasters.net>
Cc: Tom Lane <tgl@sss.pgh.pa.us>
Cc: Andrew Dunstan <andrew.dunstan@2ndquadrant.com>
Cc: Robert Haas <robertmhaas@gmail.com>
Cc: Pavel Stehule <pavel.stehule@gmail.com>
Subject: Re: jsonpath
Date: Fri, 1 Mar 2019 03:36:49 +0300
Message-ID: <a3be6a7a-77d3-0e88-4f9d-4f725d11d7cd@postgrespro.ru> (raw)
In-Reply-To: <CAPpHfdu+y1tkiidwu0i=XyGK5eOTOu1fPbuYs=XT32g7tzGd4Q@mail.gmail.com>
References: <CAPpHfdv2bro1224314aRijKJu1bfwEimKr6hExoOaF4sqSDTQA@mail.gmail.com>
	<CAF4Au4zTZ18j_7Q4VeiJvJ3egJkEQtu7MfgU_ADp5pYVbdnkpA@mail.gmail.com>
	<264a6413-7175-9680-b976-d50392c001c0@postgrespro.ru>
	<CAPpHfdtxOuEu4t-uGwJF9qzusAmViBf_e3cLYUx1mEoqwWD21g@mail.gmail.com>
	<CAPpHfdu4nKqccH0tE84fTJqc7qV-9_w_uic1_zGTYY4FEbQUOw@mail.gmail.com>
	<CAPpHfduk=0DOKa40A+0Gi-eo03on_7DZgLZV9vNGdgfUMF_v2w@mail.gmail.com>
	<CAPpHfdv+YtPtmircv0kDNH8t9CJ2u8NVGT0JMOxxG2Tdi9BAYg@mail.gmail.com>
	<eebc218c-7aaa-c425-6ba0-78b28c751830@2ndquadrant.com>
	<9f5f1247-29f4-17cd-edd9-38e9bcd95b14@postgrespro.ru>
	<CAPpHfdsxacOREFDAhhZFwL=-x8Z49LCrEK8T9Zn=SJY-EJ+S_Q@mail.gmail.com>
	<20190130022826.of7w6xv5lbvzqxfp@alap3.anarazel.de>
	<CAPpHfdvov6kWfT3hk8KMSah+kzNuN2AXaZfBqnSU0YkzDVkR2Q@mail.gmail.com>
	<957ee2ff-f9a6-0ba1-13e2-9c4d320f63ac@2ndquadrant.com>
	<CAPpHfdu+y1tkiidwu0i=XyGK5eOTOu1fPbuYs=XT32g7tzGd4Q@mail.gmail.com>

Attached 34th version of the patches.

1. Partial jsonpath support:
    - Fixed copying of jsonb with vars jsonb_path_query() into SRF context
    - Fixed error message for jsonpath vars
    - Fixed file-level comment in jsonpath.c

2. Suppression of numeric errors:
    Now error handling is done without PG_TRY/PG_CATCH using a bunch of internal
    numeric functions with 'bool *error' flag.

3. Datetime support:
    Problems with timzeones still exist.  Comparison of tz types with
    non-tz types is simply disallowed.  Default integer timezone offset (not
    abbreviation) can be specified with the second .datetime() argument.
    Error handling also is done using internal functions.

4. Json type support:
    Json support was completely refactored since v23: double compilation with
    function redefinitions was replaced with passing 'isJsonb' flag to low-level
    json/jsonb access functions.
    Also major refactoring with introduction of struct JsonItem was made.
    JsonItem is used in executor instead of raw JsonbValue.  This helps to avoid
    extending of JsonbValue for datetime types and also other numeric types
    (integers and floats) required by standard.

5. GIN support:
    Nothing was changed since v23.


Patch 1 is what we are going to commit in PG12.
Patches 2 and 3 add code that was removed in the previous v33 version.


On 24.02.2019 15:34, Alexander Korotkov wrote:

> On Sun, Feb 24, 2019 at 2:44 PM Tomas Vondra
> <tomas.vondra@2ndquadrant.com> wrote:
>> On 2/24/19 10:03 AM, Alexander Korotkov wrote:
>>> Attached is revised version of jsonpath.  Assuming that jsonpath have
>>> problem places, I decided to propose partial implementation.
>>> Following functionality was cut from jsonpath:
>>> 1) Support of datetime datatypes.  Besides error suppression, this
>>> functionality have troubles with timezones.  According to standard we
>>> should support timezones in jsonpath expressions.  But that would
>>> prevent jsonpath functions from being immutable, that in turn limits
>>> their usage in expression indexes.
>> Assuming we get the patch committed without the datetime stuff now, what
>> does that mean for the future? Does that mean we'll be unable to extend
>> it to support datetime in the future, or what? If we define the jsonpath
>> functions as immutable now, people may create indexes - which means we
>> won't be able to downgrade it to stable later.
>>
>> So, what's the plan here? The only thing I can think of is having two
>> sets of functions - an immutable one, prohibiting datetime expressions,
>> and stable that can't be used for indexes etc.
> Reasonable question.  As I understand, not datetime support itself
> making jsonpath functions not immutable, but implicit cast happening
> during comparison timestamp vs. timestamptz (and time vs. timetz).
> So, in future immutable functions can have limited support of
> datetime, where comparison of non-tz vs. tz types is restricted.  And
> stable versions of functions (for instance, with '_tz' prefix) with
> full datetime support.

I can also offset to explicitly pass timezone info into jsonpath function using
the special user dataype encapsulating struct pg_tz.

But simple integer timezone offset can be passed now using jsonpath variables
(standard says only about integer timezone offsets; also it requires presence
of timezone offset it in the input string if the format string contain timezone
components):

=# SELECT jsonb_path_query(
      '"28-02-2019 12:34"',
      '$.datetime("DD-MM-YYYY HH24:MI TZH", $tz)',
      jsonb_build_object('tz', EXTRACT(TIMEZONE FROM now()))
    );
  
       jsonb_path_query
-----------------------------
  "2019-02-28T12:34:00+03:00"
(1 row)

>>> 2) Suppression of numeric errors.  I will post it as a separate patch.
>>> Pushing this even this partial implementation of jsonpath to PG 12 is
>>> still very useful.  Also it will simplify a lot pushing other parts of
>>> SQL/JSON to future releases.
>> +1 to push at least partial (but still useful) subset, instead of just
>> bumping the patch to PG13
See patch #2.
> Thank you for support!
-- 
Nikita Glukhov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

Attachments:

  [text/x-patch] 0001-Partial-implementation-of-SQL-JSON-path-language-v34.patch (260.9K, ../a3be6a7a-77d3-0e88-4f9d-4f725d11d7cd@postgrespro.ru/3-0001-Partial-implementation-of-SQL-JSON-path-language-v34.patch)
  download | inline diff:
From 6a34d286396ca5720b29b332306f387e0716e0c2 Mon Sep 17 00:00:00 2001
From: Nikita Glukhov <n.gluhov@postgrespro.ru>
Date: Fri, 1 Mar 2019 03:15:18 +0300
Subject: [PATCH 01/13] Partial implementation of SQL/JSON path language

SQL 2016 standards among other things contains set of SQL/JSON features for
JSON processing inside of relational database.  The core of SQL/JSON is JSON
path language, allowing access parts of JSON documents and make computations
over them.  This commit implements partial support JSON path language as
separate datatype called "jsonpath".  The implementation is partial because
it's lacking datetime support and suppression of numeric errors.  Missing
features will be added later by separate commits.

Support of SQL/JSON features requires implementation of separate nodes, and it
will be considered in subsequent patches.  This commit includes following
set of plain functions, allowing to execute jsonpath over jsonb values:

 * jsonb_path_exists(jsonb, jsonpath[, jsonb, bool]),
 * jsonb_path_match(jsonb, jsonpath[, jsonb, bool]),
 * jsonb_path_query(jsonb, jsonpath[, jsonb, bool]),
 * jsonb_path_query_array(jsonb, jsonpath[, jsonb, bool]).
 * jsonb_path_query_first(jsonb, jsonpath[, jsonb, bool]).

This commit also implements "jsonb @? jsonpath" and "jsonb @@ jsonpath", which
are wrappers over jsonpath_exists(jsonb, jsonpath) and jsonpath_predicate(jsonb,
jsonpath) correspondingly.  These operators will have an index support
(implemented in subsequent patches).

Code was written by Nikita Glukhov and Teodor Sigaev, revised by me.
Documentation was written by Oleg Bartunov and Liudmila Mantrova.  The work
was inspired by Oleg Bartunov.

Discussion: https://postgr.es/m/fcc6fc6a-b497-f39a-923d-aa34d0c588e8%402ndQuadrant.com
Author: Nikita Glukhov, Teodor Sigaev, Alexander Korotkov, Oleg Bartunov, Liudmila Mantrova
Reviewed-by: Andrew Dunstan, Pavel Stehule, Tomas Vondra, Alexander Korotkov
---
 doc/src/sgml/biblio.sgml                     |   11 +
 doc/src/sgml/func.sgml                       |  729 ++++++++-
 doc/src/sgml/json.sgml                       |  237 ++-
 src/backend/Makefile                         |   11 +-
 src/backend/catalog/system_views.sql         |   40 +
 src/backend/utils/adt/.gitignore             |    3 +
 src/backend/utils/adt/Makefile               |   19 +-
 src/backend/utils/adt/jsonb.c                |   91 +-
 src/backend/utils/adt/jsonb_util.c           |    8 +
 src/backend/utils/adt/jsonpath.c             | 1051 ++++++++++++
 src/backend/utils/adt/jsonpath_exec.c        | 2273 ++++++++++++++++++++++++++
 src/backend/utils/adt/jsonpath_gram.y        |  480 ++++++
 src/backend/utils/adt/jsonpath_scan.l        |  638 ++++++++
 src/backend/utils/adt/regexp.c               |    4 +-
 src/backend/utils/errcodes.txt               |   15 +
 src/include/catalog/pg_operator.dat          |    8 +
 src/include/catalog/pg_proc.dat              |   39 +
 src/include/catalog/pg_type.dat              |    5 +
 src/include/regex/regex.h                    |    8 +
 src/include/utils/.gitignore                 |    1 +
 src/include/utils/jsonb.h                    |    4 +
 src/include/utils/jsonpath.h                 |  245 +++
 src/include/utils/jsonpath_scanner.h         |   32 +
 src/test/regress/expected/jsonb_jsonpath.out | 1564 ++++++++++++++++++
 src/test/regress/expected/jsonpath.out       |  806 +++++++++
 src/test/regress/parallel_schedule           |    7 +-
 src/test/regress/serial_schedule             |    2 +
 src/test/regress/sql/jsonb_jsonpath.sql      |  329 ++++
 src/test/regress/sql/jsonpath.sql            |  147 ++
 src/tools/msvc/Mkvcbuild.pm                  |    2 +
 src/tools/msvc/Solution.pm                   |   18 +
 src/tools/pgindent/typedefs.list             |   17 +
 32 files changed, 8789 insertions(+), 55 deletions(-)
 create mode 100644 src/backend/utils/adt/.gitignore
 create mode 100644 src/backend/utils/adt/jsonpath.c
 create mode 100644 src/backend/utils/adt/jsonpath_exec.c
 create mode 100644 src/backend/utils/adt/jsonpath_gram.y
 create mode 100644 src/backend/utils/adt/jsonpath_scan.l
 create mode 100644 src/include/utils/jsonpath.h
 create mode 100644 src/include/utils/jsonpath_scanner.h
 create mode 100644 src/test/regress/expected/jsonb_jsonpath.out
 create mode 100644 src/test/regress/expected/jsonpath.out
 create mode 100644 src/test/regress/sql/jsonb_jsonpath.sql
 create mode 100644 src/test/regress/sql/jsonpath.sql

diff --git a/doc/src/sgml/biblio.sgml b/doc/src/sgml/biblio.sgml
index 4953024..f06305d 100644
--- a/doc/src/sgml/biblio.sgml
+++ b/doc/src/sgml/biblio.sgml
@@ -136,6 +136,17 @@
     <pubdate>1988</pubdate>
    </biblioentry>
 
+   <biblioentry id="sqltr-19075-6">
+    <title>SQL Technical Report</title>
+    <subtitle>Part 6: SQL support for JavaScript Object
+      Notation (JSON)</subtitle>
+    <edition>First Edition.</edition>
+    <biblioid>
+    <ulink url="http://standards.iso.org/ittf/PubliclyAvailableStandards/c067367_ISO_IEC_TR_19075-6_2017.zip"></ulink>.
+    </biblioid>
+    <pubdate>2017.</pubdate>
+   </biblioentry>
+
   </bibliodiv>
 
   <bibliodiv>
diff --git a/doc/src/sgml/func.sgml b/doc/src/sgml/func.sgml
index 86ff4e5..275fb3f 100644
--- a/doc/src/sgml/func.sgml
+++ b/doc/src/sgml/func.sgml
@@ -11289,26 +11289,563 @@ table2-mapping
  </sect1>
 
  <sect1 id="functions-json">
-  <title>JSON Functions and Operators</title>
+  <title>JSON Functions, Operators, and Expressions</title>
 
-  <indexterm zone="functions-json">
+  <para>
+   The functions, operators, and expressions described in this section
+   operate on JSON data:
+  </para>
+
+  <itemizedlist>
+   <listitem>
+    <para>
+     SQL/JSON path expressions
+     (see <xref linkend="functions-sqljson-path"/>).
+    </para>
+   </listitem>
+   <listitem>
+    <para>
+     PostgreSQL-specific functions and operators for JSON
+     data types (see <xref linkend="functions-pgjson"/>).
+    </para>
+   </listitem>
+  </itemizedlist>
+
+  <para>
+    To learn more about the SQL/JSON standard, see
+    <xref linkend="sqltr-19075-6"/>. For details on JSON types
+    supported in <productname>PostgreSQL</productname>,
+    see <xref linkend="datatype-json"/>.
+  </para>
+
+ <sect2 id="functions-sqljson-path">
+  <title>SQL/JSON Path Expressions</title>
+
+  <para>
+   SQL/JSON path expressions specify the items to be retrieved
+   from the JSON data, similar to XPath expressions used
+   for SQL access to XML. In <productname>PostgreSQL</productname>,
+   path expressions are implemented as the <type>jsonpath</type>
+   data type, described in <xref linkend="datatype-jsonpath"/>.
+  </para>
+
+  <para>JSON query functions and operators
+   pass the provided path expression to the <firstterm>path engine</firstterm>
+   for evaluation. If the expression matches the JSON data to be queried,
+   the corresponding SQL/JSON item is returned.
+   Path expressions are written in the SQL/JSON path language
+   and can also include arithmetic expressions and functions.
+   Query functions treat the provided expression as a
+   text string, so it must be enclosed in single quotes.
+  </para>
+
+  <para>
+   A path expression consists of a sequence of elements allowed
+   by the <type>jsonpath</type> data type.
+   The path expression is evaluated from left to right, but
+   you can use parentheses to change the order of operations.
+   If the evaluation is successful, an SQL/JSON sequence is produced,
+   and the evaluation result is returned to the JSON query function
+   that completes the specified computation.
+  </para>
+
+  <para>
+   To refer to the JSON data to be queried (the
+   <firstterm>context item</firstterm>), use the <literal>$</literal> sign
+   in the path expression. It can be followed by one or more
+   <link linkend="type-jsonpath-accessors">accessor operators</link>,
+   which go down the JSON structure level by level to retrieve the
+   content of context item. Each operator that follows deals with the
+   result of the previous evaluation step.
+  </para>
+
+  <para>
+   For example, suppose you have some JSON data from a GPS tracker that you
+   would like to parse, such as:
+<programlisting>
+{ "track" :
+  {
+    "segments" : [ 
+      { "location":   [ 47.763, 13.4034 ],
+        "start time": "2018-10-14 10:05:14",
+        "HR": 73
+      },
+      { "location":   [ 47.706, 13.2635 ],
+        "start time": "2018-10-14 10:39:21",
+        "HR": 130
+      } ]
+  }
+}
+</programlisting>
+  </para>
+
+  <para>
+   To retrieve the available track segments, you need to use the
+   <literal>.<replaceable>key</replaceable></literal> accessor
+   operator for all the preceding JSON objects:
+<programlisting>
+'$.track.segments'
+</programlisting>
+  </para>
+
+  <para>
+   If the item to retrieve is an element of an array, you have
+   to unnest this array using the [*] operator. For example,
+   the following path will return location coordinates for all
+   the available track segments:
+<programlisting>
+'$.track.segments[*].location'
+</programlisting>
+  </para>
+
+  <para>
+   To return the coordinates of the first segment only, you can
+   specify the corresponding subscript in the <literal>[]</literal>
+   accessor operator. Note that the SQL/JSON arrays are 0-relative:
+<programlisting>
+'$.track.segments[0].location'
+</programlisting>
+  </para>
+
+  <para>
+   The result of each path evaluation step can be processed
+   by one or more <type>jsonpath</type> operators and methods
+   listed in <xref linkend="functions-sqljson-path-operators"/>.
+   Each method must be preceded by a dot, while arithmetic and boolean
+   operators are separated from the operands by spaces. For example,
+   you can get an array size:
+<programlisting>
+'$.track.segments.size()'
+</programlisting>
+   For more examples of using <type>jsonpath</type> operators
+   and methods within path expressions, see
+   <xref linkend="functions-sqljson-path-operators"/>.
+  </para>
+
+  <para>
+   When defining the path, you can also use one or more
+   <firstterm>filter expressions</firstterm>, which work similar to
+   the <command>WHERE</command> clause in SQL. Each filter expression
+   can provide one or more filtering conditions that are applied
+   to the result of the path evaluation. Each filter expression must
+   be enclosed in parentheses and preceded by a question mark.
+   Filter expressions are applied from left to right and can be nested.
+   The <literal>@</literal> variable denotes the current path evaluation
+   result to be filtered, and can be followed by one or more accessor
+   operators to define the JSON element by which to filter the result.
+   Functions and operators that can be used in the filtering condition
+   are listed in <xref linkend="functions-sqljson-filter-ex-table"/>.
+   The result of the filter expression may be true, false, or unknown.
+  </para>
+
+  <para>
+   For example, the following path expression returns the heart
+   rate value only if it is higher than 130:
+<programlisting>
+'$.track.segments[*].HR ? (@ > 130)'
+</programlisting>
+  </para>
+
+  <para>
+   But suppose you would like to retrieve the start time of this segment
+   instead. In this case, you have to filter out irrelevant
+   segments before getting the start time, so the path in the
+   filter condition looks differently:
+<programlisting>
+'$.track.segments[*] ? (@.HR > 130)."start time"'
+</programlisting>
+  </para>
+
+  <para>
+   <productname>PostgreSQL</productname> also implements the following
+   extensions of the SQL/JSON standard:
+  </para>
+
+  <itemizedlist>
+   <listitem>
+    <para>
+     A path expression can be a boolean predicate. For example:
+<programlisting>
+'$.track.segments[*].HR &lt; 70'
+</programlisting>
+    </para>
+   </listitem>
+   <listitem>
+    <para>Writing the path as an expression is also valid:
+<programlisting>
+'$' || '.' || 'a'
+</programlisting>
+    </para>
+   </listitem>
+  </itemizedlist>
+
+   <sect3 id="strict-and-lax-modes">
+   <title>Strict and Lax Modes</title>
+    <para>
+     When you query JSON data, the path expression may not match the
+     actual JSON data structure. An attempt to access a non-existent
+     member of an object or element of an array results in a
+     structural error. SQL/JSON path expressions have two modes
+     of handling structural errors:
+    </para>
+
+   <itemizedlist>
+    <listitem>
+     <para>
+      lax (default) &mdash; the path engine implicitly adapts
+      the queried data to the specified path.
+      Any remaining structural errors are suppressed and converted
+      to empty SQL/JSON sequences.
+     </para>
+    </listitem>
+    <listitem>
+     <para>
+      strict &mdash; if a structural error occurs, an error is raised.
+     </para>
+    </listitem>
+   </itemizedlist>
+
+   <para>
+    The lax mode facilitates matching of a JSON document structure and path
+    expression if the JSON data does not conform to the expected schema.
+    If an operand does not match the requirements of a particular operation,
+    it can be automatically wrapped as an SQL/JSON array or unwrapped by
+    converting its elements into an SQL/JSON sequence before performing
+    this operation. Besides, comparison operators automatically unwrap their
+    operands in the lax mode, so you can compare SQL/JSON arrays
+    out-of-the-box. Arrays of size 1 are interchangeable with a singleton.
+   </para>
+
+   <para>
+    For example, when querying the GPS data listed above, you can
+    abstract from the fact that it stores an array of segments
+    when using the lax mode:
+<programlisting>
+'lax $.track.segments.location'
+</programlisting>
+   </para>
+
+   <para>
+    In the strict mode, the specified path must exactly match the structure of
+    the queried JSON document to return an SQL/JSON item, so using this
+    path expression will cause an error. To get the same result as in
+    the lax mode, you have to explicitly unwrap the
+    <literal>segments</literal> array:
+<programlisting>
+'strict $.track.segments[*].location'
+</programlisting>
+   </para>
+
+   <para>
+    Implicit unwrapping in the lax mode is not performed in the following cases:
+    <itemizedlist>
+     <listitem>
+      <para>
+       The path expression contains <literal>type()</literal> or
+       <literal>size()</literal> methods that return the type
+       and the number of elements in the array, respectively.
+      </para>
+     </listitem>
+     <listitem>
+      <para>
+       The queried JSON data contain nested arrays. In this case, only
+       the outermost array is unwrapped, while all the inner arrays
+       remain unchanged. Thus, implicit unwrapping can only go one
+       level down within each path evaluation step.
+      </para>
+     </listitem>
+    </itemizedlist>
+   </para>
+
+   </sect3>
+
+   <sect3 id="functions-sqljson-path-operators">
+   <title>SQL/JSON Path Operators and Methods</title>
+
+   <table id="functions-sqljson-op-table">
+    <title><type>jsonpath</type> Operators and Methods</title>
+     <tgroup cols="5">
+      <thead>
+       <row>
+        <entry>Operator/Method</entry>
+        <entry>Description</entry>
+        <entry>Example JSON</entry>
+        <entry>Example Query</entry>
+        <entry>Result</entry>
+       </row>
+      </thead>
+      <tbody>
+       <row>
+        <entry><literal>+</literal> (unary)</entry>
+        <entry>Plus operator that iterates over the json sequence</entry>
+        <entry><literal>{"x": [2.85, -14.7, -9.4]}</literal></entry>
+        <entry><literal>+ $.x.floor()</literal></entry>
+        <entry><literal>2, -15, -10</literal></entry>
+       </row>
+       <row>
+        <entry><literal>-</literal> (unary)</entry>
+        <entry>Minus operator that iterates over the json sequence</entry>
+        <entry><literal>{"x": [2.85, -14.7, -9.4]}</literal></entry>
+        <entry><literal>- $.x.floor()</literal></entry>
+        <entry><literal>-2, 15, 10</literal></entry>
+       </row>
+       <row>
+        <entry><literal>+</literal> (binary)</entry>
+        <entry>Addition</entry>
+        <entry><literal>[2]</literal></entry>
+        <entry><literal>2 + $[0]</literal></entry>
+        <entry><literal>4</literal></entry>
+       </row>
+       <row>
+        <entry><literal>-</literal> (binary)</entry>
+        <entry>Subtraction</entry>
+        <entry><literal>[2]</literal></entry>
+        <entry><literal>4 - $[0]</literal></entry>
+        <entry><literal>2</literal></entry>
+       </row>
+       <row>
+        <entry><literal>*</literal></entry>
+        <entry>Multiplication</entry>
+        <entry><literal>[4]</literal></entry>
+        <entry><literal>2 * $[0]</literal></entry>
+        <entry><literal>8</literal></entry>
+       </row>
+       <row>
+        <entry><literal>/</literal></entry>
+        <entry>Division</entry>
+        <entry><literal>[8]</literal></entry>
+        <entry><literal>$[0] / 2</literal></entry>
+        <entry><literal>4</literal></entry>
+       </row>
+       <row>
+        <entry><literal>%</literal></entry>
+        <entry>Modulus</entry>
+        <entry><literal>[32]</literal></entry>
+        <entry><literal>$[0] % 10</literal></entry>
+        <entry><literal>2</literal></entry>
+       </row>
+       <row>
+        <entry><literal>type()</literal></entry>
+        <entry>Type of the SQL/JSON item</entry>
+        <entry><literal>[1, "2", {}]</literal></entry>
+        <entry><literal>$[*].type()</literal></entry>
+        <entry><literal>"number", "string", "object"</literal></entry>
+       </row>
+       <row>
+        <entry><literal>size()</literal></entry>
+        <entry>Size of the SQL/JSON item</entry>
+        <entry><literal>{"m": [11, 15]}</literal></entry>
+        <entry><literal>$.m.size()</literal></entry>
+        <entry><literal>2</literal></entry>
+       </row>
+       <row>
+        <entry><literal>double()</literal></entry>
+        <entry>Approximate numeric value converted from a string</entry>
+        <entry><literal>{"len": "1.9"}</literal></entry>
+        <entry><literal>$.len.double() * 2</literal></entry>
+        <entry><literal>3.8</literal></entry>
+       </row>
+       <row>
+        <entry><literal>ceiling()</literal></entry>
+        <entry>Nearest integer greater than or equal to the SQL/JSON number</entry>
+        <entry><literal>{"h": 1.3}</literal></entry>
+        <entry><literal>$.h.ceiling()</literal></entry>
+        <entry><literal>2</literal></entry>
+       </row>
+       <row>
+        <entry><literal>floor()</literal></entry>
+        <entry>Nearest integer less than or equal to the SQL/JSON number</entry>
+        <entry><literal>{"h": 1.3}</literal></entry>
+        <entry><literal>$.h.floor()</literal></entry>
+        <entry><literal>1</literal></entry>
+       </row>
+       <row>
+        <entry><literal>abs()</literal></entry>
+        <entry>Absolute value of the SQL/JSON number</entry>
+        <entry><literal>{"z": -0.3}</literal></entry>
+        <entry><literal>$.z.abs()</literal></entry>
+        <entry><literal>0.3</literal></entry>
+       </row>
+       <row>
+        <entry><literal>keyvalue()</literal></entry>
+        <entry>
+          Sequence of object's key-value pairs represented as array of objects
+          containing three fields (<literal>"key"</literal>,
+          <literal>"value"</literal>, and <literal>"id"</literal>).
+          <literal>"id"</literal> is an unique identifier of the object
+          key-value pair belongs to.
+        </entry>
+        <entry><literal>{"x": "20", "y": 32}</literal></entry>
+        <entry><literal>$.keyvalue()</literal></entry>
+        <entry><literal>{"key": "x", "value": "20", "id": 0}, {"key": "y", "value": 32, "id": 0}</literal></entry>
+       </row>
+      </tbody>
+     </tgroup>
+    </table>
+
+    <table id="functions-sqljson-filter-ex-table">
+     <title><type>jsonpath</type> Filter Expression Elements</title>
+     <tgroup cols="5">
+      <thead>
+       <row>
+        <entry>Value/Predicate</entry>
+        <entry>Description</entry>
+        <entry>Example JSON</entry>
+        <entry>Example Query</entry>
+        <entry>Result</entry>
+       </row>
+      </thead>
+      <tbody>
+       <row>
+        <entry><literal>==</literal></entry>
+        <entry>Equality operator</entry>
+        <entry><literal>[1, 2, 1, 3]</literal></entry>
+        <entry><literal>$[*] ? (@ == 1)</literal></entry>
+        <entry><literal>1, 1</literal></entry>
+       </row>
+       <row>
+        <entry><literal>!=</literal></entry>
+        <entry>Non-equality operator</entry>
+        <entry><literal>[1, 2, 1, 3]</literal></entry>
+        <entry><literal>$[*] ? (@ != 1)</literal></entry>
+        <entry><literal>2, 3</literal></entry>
+       </row>
+       <row>
+        <entry><literal>&lt;&gt;</literal></entry>
+        <entry>Non-equality operator (same as <literal>!=</literal>)</entry>
+        <entry><literal>[1, 2, 1, 3]</literal></entry>
+        <entry><literal>$[*] ? (@ &lt;&gt; 1)</literal></entry>
+        <entry><literal>2, 3</literal></entry>
+       </row>
+       <row>
+        <entry><literal>&lt;</literal></entry>
+        <entry>Less-than operator</entry>
+        <entry><literal>[1, 2, 3]</literal></entry>
+        <entry><literal>$[*] ? (@ &lt; 2)</literal></entry>
+        <entry><literal>1, 2</literal></entry>
+       </row>
+       <row>
+        <entry><literal>&lt;=</literal></entry>
+        <entry>Less-than-or-equal-to operator</entry>
+        <entry><literal>[1, 2, 3]</literal></entry>
+        <entry><literal>$[*] ? (@ &lt; 2)</literal></entry>
+        <entry><literal>1</literal></entry>
+       </row>
+       <row>
+        <entry><literal>&gt;</literal></entry>
+        <entry>Greater-than operator</entry>
+        <entry><literal>[1, 2, 3]</literal></entry>
+        <entry><literal>$[*] ? (@ &gt; 2)</literal></entry>
+        <entry><literal>3</literal></entry>
+       </row>
+       <row>
+        <entry><literal>&gt;</literal></entry>
+        <entry>Greater-than-or-equal-to operator</entry>
+        <entry><literal>[1, 2, 3]</literal></entry>
+        <entry><literal>$[*] ? (@ &gt;= 2)</literal></entry>
+        <entry><literal>2, 3</literal></entry>
+       </row>
+       <row>
+        <entry><literal>true</literal></entry>
+        <entry>Value used to perform comparison with JSON <literal>true</literal> literal</entry>
+        <entry><literal>[{"name": "John", "parent": false},
+                           {"name": "Chris", "parent": true}]</literal></entry>
+        <entry><literal>$[*] ? (@.parent == true)</literal></entry>
+        <entry><literal>{"name": "Chris", "parent": true}</literal></entry>
+       </row>
+       <row>
+        <entry><literal>false</literal></entry>
+        <entry>Value used to perform comparison with JSON <literal>false</literal> literal</entry>
+        <entry><literal>[{"name": "John", "parent": false},
+                           {"name": "Chris", "parent": true}]</literal></entry>
+        <entry><literal>$[*] ? (@.parent == false)</literal></entry>
+        <entry><literal>{"name": "John", "parent": false}</literal></entry>
+       </row>
+       <row>
+        <entry><literal>null</literal></entry>
+        <entry>Value used to perform comparison with JSON <literal>null</literal> value</entry>
+        <entry><literal>[{"name": "Mary", "job": null},
+                         {"name": "Michael", "job": "driver"}]</literal></entry>
+        <entry><literal>$[*] ? (@.job == null) .name</literal></entry>
+        <entry><literal>"Mary"</literal></entry>
+       </row>
+       <row>
+        <entry><literal>&amp;&amp;</literal></entry>
+        <entry>Boolean AND</entry>
+        <entry><literal>[1, 3, 7]</literal></entry>
+        <entry><literal>$[*] ? (@ &gt; 1 &amp;&amp; @ &lt; 5)</literal></entry>
+        <entry><literal>3</literal></entry>
+       </row>
+       <row>
+        <entry><literal>||</literal></entry>
+        <entry>Boolean OR</entry>
+        <entry><literal>[1, 3, 7]</literal></entry>
+        <entry><literal>$[*] ? (@ &lt; 1 || @ &gt; 5)</literal></entry>
+        <entry><literal>7</literal></entry>
+       </row>
+       <row>
+        <entry><literal>!</literal></entry>
+        <entry>Boolean NOT</entry>
+        <entry><literal>[1, 3, 7]</literal></entry>
+        <entry><literal>$[*] ? (!(@ &lt; 5))</literal></entry>
+        <entry><literal>7</literal></entry>
+       </row>
+       <row>
+        <entry><literal>like_regex</literal></entry>
+        <entry>Tests pattern matching with POSIX regular expressions</entry>
+        <entry><literal>["abc", "abd", "aBdC", "abdacb", "babc"]</literal></entry>
+        <entry><literal>$[*] ? (@ like_regex "^ab.*c" flag "i")</literal></entry>
+        <entry><literal>"abc", "aBdC", "abdacb"</literal></entry>
+       </row>
+       <row>
+        <entry><literal>starts with</literal></entry>
+        <entry>Tests whether the second operand is an initial substring of the first operand</entry>
+        <entry><literal>["John Smith", "Mary Stone", "Bob Johnson"]</literal></entry>
+        <entry><literal>$[*] ? (@ starts with "John")</literal></entry>
+        <entry><literal>"John Smith"</literal></entry>
+       </row>
+       <row>
+        <entry><literal>exists</literal></entry>
+        <entry>Tests whether a path expression has at least one SQL/JSON item</entry>
+        <entry><literal>{"x": [1, 2], "y": [2, 4]}</literal></entry>
+        <entry><literal>strict $.* ? (exists (@ ? (@[*] > 2)))</literal></entry>
+        <entry><literal>2, 4</literal></entry>
+       </row>
+       <row>
+        <entry><literal>is unknown</literal></entry>
+        <entry>Tests whether a boolean condition is <literal>unknown</literal></entry>
+        <entry><literal>[-1, 2, 7, "infinity"]</literal></entry>
+        <entry><literal>$[*] ? ((@ > 0) is unknown)</literal></entry>
+        <entry><literal>"infinity"</literal></entry>
+       </row>
+      </tbody>
+     </tgroup>
+    </table>
+   </sect3>
+
+  </sect2>
+
+  <sect2 id="functions-pgjson">
+  <title>PostgreSQL-specific JSON Functions and Operators</title>
+  <indexterm zone="functions-pgjson">
     <primary>JSON</primary>
     <secondary>functions and operators</secondary>
   </indexterm>
 
-   <para>
+  <para>
    <xref linkend="functions-json-op-table"/> shows the operators that
-   are available for use with the two JSON data types (see <xref
+   are available for use with JSON data types (see <xref
    linkend="datatype-json"/>).
   </para>
 
   <table id="functions-json-op-table">
      <title><type>json</type> and <type>jsonb</type> Operators</title>
-     <tgroup cols="5">
+     <tgroup cols="6">
       <thead>
        <row>
         <entry>Operator</entry>
         <entry>Right Operand Type</entry>
+        <entry>Return type</entry>
         <entry>Description</entry>
         <entry>Example</entry>
         <entry>Example Result</entry>
@@ -11318,6 +11855,7 @@ table2-mapping
        <row>
         <entry><literal>-&gt;</literal></entry>
         <entry><type>int</type></entry>
+        <entry><type>json</type> or <type>jsonb</type></entry>
         <entry>Get JSON array element (indexed from zero, negative
         integers count from the end)</entry>
         <entry><literal>'[{"a":"foo"},{"b":"bar"},{"c":"baz"}]'::json-&gt;2</literal></entry>
@@ -11326,6 +11864,7 @@ table2-mapping
        <row>
         <entry><literal>-&gt;</literal></entry>
         <entry><type>text</type></entry>
+        <entry><type>json</type> or <type>jsonb</type></entry>
         <entry>Get JSON object field by key</entry>
         <entry><literal>'{"a": {"b":"foo"}}'::json-&gt;'a'</literal></entry>
         <entry><literal>{"b":"foo"}</literal></entry>
@@ -11333,6 +11872,7 @@ table2-mapping
         <row>
         <entry><literal>-&gt;&gt;</literal></entry>
         <entry><type>int</type></entry>
+        <entry><type>text</type></entry>
         <entry>Get JSON array element as <type>text</type></entry>
         <entry><literal>'[1,2,3]'::json-&gt;&gt;2</literal></entry>
         <entry><literal>3</literal></entry>
@@ -11340,6 +11880,7 @@ table2-mapping
        <row>
         <entry><literal>-&gt;&gt;</literal></entry>
         <entry><type>text</type></entry>
+        <entry><type>text</type></entry>
         <entry>Get JSON object field as <type>text</type></entry>
         <entry><literal>'{"a":1,"b":2}'::json-&gt;&gt;'b'</literal></entry>
         <entry><literal>2</literal></entry>
@@ -11347,14 +11888,16 @@ table2-mapping
        <row>
         <entry><literal>#&gt;</literal></entry>
         <entry><type>text[]</type></entry>
-        <entry>Get JSON object at specified path</entry>
+        <entry><type>json</type> or <type>jsonb</type></entry>
+        <entry>Get JSON object at the specified path</entry>
         <entry><literal>'{"a": {"b":{"c": "foo"}}}'::json#&gt;'{a,b}'</literal></entry>
         <entry><literal>{"c": "foo"}</literal></entry>
        </row>
        <row>
         <entry><literal>#&gt;&gt;</literal></entry>
         <entry><type>text[]</type></entry>
-        <entry>Get JSON object at specified path as <type>text</type></entry>
+        <entry><type>text</type></entry>
+        <entry>Get JSON object at the specified path as <type>text</type></entry>
         <entry><literal>'{"a":[1,2,3],"b":[4,5,6]}'::json#&gt;&gt;'{a,2}'</literal></entry>
         <entry><literal>3</literal></entry>
        </row>
@@ -11479,6 +12022,21 @@ table2-mapping
         JSON arrays, negative integers count from the end)</entry>
         <entry><literal>'["a", {"b":1}]'::jsonb #- '{1,b}'</literal></entry>
        </row>
+       <row>
+        <entry><literal>@?</literal></entry>
+        <entry><type>jsonpath</type></entry>
+        <entry>Does JSON path returns any item for the specified JSON value?</entry>
+        <entry><literal>'{"a":[1,2,3,4,5]}'::jsonb @? '$.a[*] ? (@ > 2)'</literal></entry>
+       </row>
+       <row>
+        <entry><literal>@@</literal></entry>
+        <entry><type>jsonpath</type></entry>
+        <entry>JSON path predicate check result for the specified JSON value.
+        Only first result item is taken into account.  If there is no results
+        or first result item is not bool, then <literal>NULL</literal>
+        is returned.</entry>
+        <entry><literal>'{"a":[1,2,3,4,5]}'::jsonb @@ '$.a[*] > 2'</literal></entry>
+       </row>
       </tbody>
      </tgroup>
    </table>
@@ -11492,6 +12050,16 @@ table2-mapping
    </para>
   </note>
 
+  <note>
+   <para>
+    The <literal>@?</literal> and <literal>@@</literal> operators suppress
+    errors including: lacking object field or array element, unexpected JSON
+    item type.
+    This behavior might be helpful while searching over JSON document
+    collections of varying structure.
+   </para>
+  </note>
+
   <para>
    <xref linkend="functions-json-creation-table"/> shows the functions that are
    available for creating <type>json</type> and <type>jsonb</type> values.
@@ -11752,6 +12320,21 @@ table2-mapping
   <indexterm>
    <primary>jsonb_pretty</primary>
   </indexterm>
+  <indexterm>
+   <primary>jsonb_path_exists</primary>
+  </indexterm>
+  <indexterm>
+   <primary>jsonb_path_match</primary>
+  </indexterm>
+  <indexterm>
+   <primary>jsonb_path_query</primary>
+  </indexterm>
+  <indexterm>
+   <primary>jsonb_path_query_array</primary>
+  </indexterm>
+  <indexterm>
+   <primary>jsonb_path_query_first</primary>
+  </indexterm>
 
   <table id="functions-json-processing-table">
     <title>JSON Processing Functions</title>
@@ -12086,6 +12669,116 @@ table2-mapping
 </programlisting>
         </entry>
        </row>
+       <row>
+        <entry>
+         <para><literal>
+           jsonb_path_exists(target jsonb, path jsonpath [, vars jsonb, silent bool])
+         </literal></para>
+        </entry>
+        <entry><type>boolean</type></entry>
+        <entry>
+          Checks whether JSON path returns any item for the specified JSON
+          value.
+        </entry>
+        <entry>
+         <para><literal>
+           jsonb_path_exists('{"a":[1,2,3,4,5]}', '$.a[*] ? (@ >= $min &amp;&amp; @ &lt;= $max)', '{"min":2,"max":4}')
+         </literal></para>
+        </entry>
+        <entry>
+          <para><literal>true</literal></para>
+        </entry>
+       </row>
+       <row>
+        <entry>
+         <para><literal>
+           jsonb_path_match(target jsonb, path jsonpath [, vars jsonb, silent bool])
+         </literal></para>
+        </entry>
+        <entry><type>boolean</type></entry>
+        <entry>
+          Returns JSON path predicate result for the specified JSON value.
+          Only first result item is taken into account.  If there is no results
+          or first result item is not bool, then <literal>NULL</literal>
+          is returned.
+        </entry>
+        <entry>
+         <para><literal>
+           jsonb_path_match('{"a":[1,2,3,4,5]}', 'exists($.a[*] ? (@ >= $min &amp;&amp; @ &lt;= $max))', '{"min":2,"max":4}')
+        </literal></para>
+        </entry>
+        <entry>
+          <para><literal>true</literal></para>
+        </entry>
+       </row>
+       <row>
+        <entry>
+         <para><literal>
+           jsonb_path_query(target jsonb, path jsonpath [, vars jsonb, silent bool])
+         </literal></para>
+        </entry>
+        <entry><type>setof jsonb</type></entry>
+        <entry>
+          Gets all JSON items returned by JSON path for the specified JSON
+          value.
+        </entry>
+        <entry>
+         <para><literal>
+           select * jsonb_path_query('{"a":[1,2,3,4,5]}', '$.a[*] ? (@ >= $min &amp;&amp; @ &lt;= $max)', '{"min":2,"max":4}');
+         </literal></para>
+        </entry>
+        <entry>
+         <para>
+           <programlisting>
+ jsonb_path_query
+------------------
+ 2
+ 3
+ 4
+           </programlisting>
+         </para>
+        </entry>
+       </row>
+       <row>
+        <entry>
+         <para><literal>
+           jsonb_path_query_array(target jsonb, path jsonpath [, vars jsonb, silent bool])
+         </literal></para>
+        </entry>
+        <entry><type>jsonb</type></entry>
+        <entry>
+          Gets all JSON items returned by JSON path for the specified JSON
+          value and wraps result into an array.
+        </entry>
+        <entry>
+         <para><literal>
+           jsonb_path_query_array('{"a":[1,2,3,4,5]}', '$.a[*] ? (@ >= $min &amp;&amp; @ &lt;= $max)', '{"min":2,"max":4}')
+         </literal></para>
+        </entry>
+        <entry>
+          <para><literal>[2, 3, 4]</literal></para>
+        </entry>
+       </row>
+       <row>
+        <entry>
+         <para><literal>
+           jsonb_path_query_first(target jsonb, path jsonpath [, vars jsonb, silent bool])
+         </literal></para>
+        </entry>
+        <entry><type>jsonb</type></entry>
+        <entry>
+          Gets the first JSON item returned by JSON path for the specified JSON
+          value.  Returns <literal>NULL</literal> on no results.
+        </entry>
+        <entry>
+         <para><literal>
+           jsonb_path_query_first('{"a":[1,2,3,4,5]}', '$.a[*] ? (@ >= $min &amp;&amp; @ &lt;= $max)', '{"min":2,"max":4}')
+         </literal></para>
+        </entry>
+        <entry>
+          <para><literal>2</literal></para>
+        </entry>
+       </row>
      </tbody>
     </tgroup>
    </table>
@@ -12123,6 +12816,7 @@ table2-mapping
       JSON fields that do not appear in the target row type will be
       omitted from the output, and target columns that do not match any
       JSON field will simply be NULL.
+
     </para>
   </note>
 
@@ -12168,6 +12862,26 @@ table2-mapping
     </para>
   </note>
 
+  <note>
+   <para>
+    The <literal>jsonb_path_exists</literal>, <literal>jsonb_path_match</literal>,
+    <literal>jsonb_path_query</literal>, <literal>jsonb_path_query_array</literal> and
+    <literal>jsonb_path_query_first</literal>
+    functions have optional <literal>vars</literal> and <literal>silent</literal>
+    argument.
+   </para>
+   <para>
+    When <literal>vars</literal> argument is specified, it constitutes an object
+    contained variables to be substituted into <literal>jsonpath</literal>
+    expression.
+   </para>
+   <para>
+    When <literal>silent</literal> argument is specified and has
+    <literal>true</literal> value, the same errors are suppressed as it is in
+    the <literal>@?</literal> and <literal>@@</literal> operators.
+   </para>
+  </note>
+
   <para>
     See also <xref linkend="functions-aggregate"/> for the aggregate
     function <function>json_agg</function> which aggregates record
@@ -12177,6 +12891,7 @@ table2-mapping
     <function>jsonb_agg</function> and <function>jsonb_object_agg</function>.
   </para>
 
+ </sect2>
  </sect1>
 
  <sect1 id="functions-sequence">
diff --git a/doc/src/sgml/json.sgml b/doc/src/sgml/json.sgml
index e7b68fa..2eccf24 100644
--- a/doc/src/sgml/json.sgml
+++ b/doc/src/sgml/json.sgml
@@ -22,8 +22,16 @@
  </para>
 
  <para>
-  There are two JSON data types: <type>json</type> and <type>jsonb</type>.
-  They accept <emphasis>almost</emphasis> identical sets of values as
+  <productname>PostgreSQL</productname> offers two types for storing JSON
+  data: <type>json</type> and <type>jsonb</type>. To implement effective query
+  mechanisms for these data types, <productname>PostgreSQL</productname>
+  also provides the <type>jsonpath</type> data type described in
+  <xref linkend="datatype-jsonpath"/>.
+ </para>
+
+ <para>
+  The <type>json</type> and <type>jsonb</type> data types
+  accept <emphasis>almost</emphasis> identical sets of values as
   input.  The major practical difference is one of efficiency.  The
   <type>json</type> data type stores an exact copy of the input text,
   which processing functions must reparse on each execution; while
@@ -217,6 +225,11 @@ SELECT '{"reading": 1.230e-5}'::json, '{"reading": 1.230e-5}'::jsonb;
    in this example, even though those are semantically insignificant for
    purposes such as equality checks.
   </para>
+
+  <para>
+    For the list of built-in functions and operators available for
+    constructing and processing JSON values, see <xref linkend="functions-json"/>.
+  </para>
  </sect2>
 
  <sect2 id="json-doc-design">
@@ -593,4 +606,224 @@ SELECT jdoc-&gt;'guid', jdoc-&gt;'name' FROM api WHERE jdoc @&gt; '{"tags": ["qu
    lists, and scalars, as appropriate.
   </para>
  </sect2>
+
+ <sect2 id="datatype-jsonpath">
+  <title>jsonpath Type</title> 
+
+  <indexterm zone="datatype-jsonpath">
+   <primary>jsonpath</primary>
+  </indexterm>
+
+  <para>
+   The <type>jsonpath</type> type implements support for the SQL/JSON path language
+   in <productname>PostgreSQL</productname> to effectively query JSON data.
+   It provides a binary representation of the parsed SQL/JSON path
+   expression that specifies the items to be retrieved by the path
+   engine from the JSON data for further processing with the
+   SQL/JSON query functions.
+  </para>
+
+  <para>
+   The SQL/JSON path language is fully integrated into the SQL engine:
+   the semantics of its predicates and operators generally follow SQL.
+   At the same time, to provide a most natural way of working with JSON data,
+   SQL/JSON path syntax uses some of the JavaScript conventions:
+  </para>
+
+  <itemizedlist>
+   <listitem>
+    <para>
+     Dot <literal>.</literal> is used for member access.
+    </para>
+   </listitem>
+   <listitem>
+    <para>
+     Square brackets <literal>[]</literal> are used for array access.
+    </para>
+   </listitem>
+   <listitem>
+    <para>
+     SQL/JSON arrays are 0-relative, unlike regular SQL arrays that start from 1.
+    </para>
+   </listitem>
+  </itemizedlist>
+
+  <para>
+   An SQL/JSON path expression is an SQL character string literal,
+   so it must be enclosed in single quotes when passed to an SQL/JSON
+   query function. Following the JavaScript
+   conventions, character string literals within the path expression
+   must be enclosed in double quotes. Any single quotes within this
+   character string literal must be escaped with a single quote
+   by the SQL convention.
+  </para>
+
+  <para>
+   A path expression consists of a sequence of path elements,
+   which can be the following:
+   <itemizedlist>
+    <listitem>
+     <para>
+      Path literals of JSON primitive types:
+      Unicode text, numeric, true, false, or null.
+     </para>
+    </listitem>
+    <listitem>
+     <para>
+      Path variables listed in <xref linkend="type-jsonpath-variables"/>.
+     </para>
+    </listitem>
+    <listitem>
+     <para>
+      Accessor operators listed in <xref linkend="type-jsonpath-accessors"/>.
+     </para>
+    </listitem>
+    <listitem>
+     <para>
+      <type>jsonpath</type> operators and methods listed
+      in <xref linkend="functions-sqljson-path-operators"/>
+     </para>
+    </listitem>
+    <listitem>
+     <para>
+      Parentheses, which can be used to provide filter expressions
+      or define the order of path evaluation.
+     </para>
+    </listitem>
+   </itemizedlist>
+  </para>
+
+  <para>
+   For details on using <type>jsonpath</type> expressions with SQL/JSON
+   query functions, see <xref linkend="functions-sqljson-path"/>.
+  </para>
+
+  <table id="type-jsonpath-variables">
+   <title><type>jsonpath</type> Variables</title>
+   <tgroup cols="2">
+    <thead>
+     <row>
+      <entry>Variable</entry>
+      <entry>Description</entry>
+     </row>
+    </thead>
+    <tbody>
+     <row>
+      <entry><literal>$</literal></entry>
+      <entry>A variable representing the JSON text to be queried
+      (the <firstterm>context item</firstterm>).
+      </entry>
+     </row>
+     <row>
+      <entry><literal>$varname</literal></entry>
+      <entry>A named variable. Its value must be set in the
+      <command>PASSING</command> clause of an SQL/JSON query function.
+ <!-- TBD: See <xref linkend="sqljson-input-clause"/> -->
+      for details.
+      </entry>
+     </row>
+     <row>
+      <entry><literal>@</literal></entry>
+      <entry>A variable representing the result of path evaluation
+      in filter expressions.
+      </entry>
+     </row>
+    </tbody>
+   </tgroup>
+  </table>
+
+  <table id="type-jsonpath-accessors">
+   <title><type>jsonpath</type> Accessors</title>
+   <tgroup cols="2">
+    <thead>
+     <row>
+      <entry>Accessor Operator</entry>
+      <entry>Description</entry>
+     </row>
+    </thead>
+    <tbody>
+     <row>
+      <entry>
+       <para>
+        <literal>.<replaceable>key</replaceable></literal>
+       </para>
+       <para>
+        <literal>."$<replaceable>varname</replaceable>"</literal>
+       </para>
+      </entry>
+      <entry>
+       <para>
+        Member accessor that returns an object member with
+        the specified key. If the key name is a named variable
+        starting with <literal>$</literal> or does not meet the
+        JavaScript rules of an identifier, it must be enclosed in
+        double quotes as a character string literal.
+       </para>
+      </entry>
+     </row>
+     <row>
+      <entry>
+       <para>
+        <literal>.*</literal>
+       </para>
+      </entry>
+      <entry>
+       <para>
+        Wildcard member accessor that returns the values of all
+        members located at the top level of the current object.
+       </para>
+      </entry>
+     </row>
+     <row>
+      <entry>
+       <para>
+        <literal>.**</literal>
+       </para>
+      </entry>
+      <entry>
+       <para>
+        Recursive wildcard member accessor that processes all levels
+        of the JSON hierarchy of the current object and returns all
+        the member values, regardless of their nesting level. This
+        is a <productname>PostgreSQL</productname> extension of
+        the SQL/JSON standard.
+       </para>
+      </entry>
+     </row>
+     <row>
+      <entry>
+       <para>
+        <literal>[<replaceable>subscript</replaceable>, ...]</literal>
+       </para>
+       <para>
+        <literal>[<replaceable>subscript</replaceable> to last]</literal>
+       </para>
+      </entry>
+      <entry>
+       <para>
+        Array element accessor. The provided numeric subscripts return the
+        corresponding array elements. The first element in an array is
+        accessed with [0]. The <literal>last</literal> keyword denotes
+        the last subscript in an array and can be used to handle arrays
+        of unknown length.
+       </para>
+      </entry>
+     </row>
+     <row>
+      <entry>
+       <para>
+        <literal>[*]</literal>
+       </para>
+      </entry>
+      <entry>
+       <para>
+        Wildcard array element accessor that returns all array elements.
+       </para>
+      </entry>
+     </row>
+    </tbody>
+   </tgroup>
+  </table>
+
+ </sect2>
 </sect1>
diff --git a/src/backend/Makefile b/src/backend/Makefile
index 478a96d..31d9d66 100644
--- a/src/backend/Makefile
+++ b/src/backend/Makefile
@@ -136,6 +136,9 @@ parser/gram.h: parser/gram.y
 storage/lmgr/lwlocknames.h: storage/lmgr/generate-lwlocknames.pl storage/lmgr/lwlocknames.txt
 	$(MAKE) -C storage/lmgr lwlocknames.h lwlocknames.c
 
+utils/adt/jsonpath_gram.h: utils/adt/jsonpath_gram.y
+	$(MAKE) -C utils/adt jsonpath_gram.h
+
 # run this unconditionally to avoid needing to know its dependencies here:
 submake-catalog-headers:
 	$(MAKE) -C catalog distprep generated-header-symlinks
@@ -159,7 +162,7 @@ submake-utils-headers:
 
 .PHONY: generated-headers
 
-generated-headers: $(top_builddir)/src/include/parser/gram.h $(top_builddir)/src/include/storage/lwlocknames.h submake-catalog-headers submake-utils-headers
+generated-headers: $(top_builddir)/src/include/parser/gram.h $(top_builddir)/src/include/storage/lwlocknames.h $(top_builddir)/src/include/utils/jsonpath_gram.h submake-catalog-headers submake-utils-headers
 
 $(top_builddir)/src/include/parser/gram.h: parser/gram.h
 	prereqdir=`cd '$(dir $<)' >/dev/null && pwd` && \
@@ -171,6 +174,10 @@ $(top_builddir)/src/include/storage/lwlocknames.h: storage/lmgr/lwlocknames.h
 	  cd '$(dir $@)' && rm -f $(notdir $@) && \
 	  $(LN_S) "$$prereqdir/$(notdir $<)" .
 
+$(top_builddir)/src/include/utils/jsonpath_gram.h: utils/adt/jsonpath_gram.h
+	prereqdir=`cd '$(dir $<)' >/dev/null && pwd` && \
+	  cd '$(dir $@)' && rm -f $(notdir $@) && \
+	  $(LN_S) "$$prereqdir/$(notdir $<)" .
 
 utils/probes.o: utils/probes.d $(SUBDIROBJS)
 	$(DTRACE) $(DTRACEFLAGS) -C -G -s $(call expand_subsys,$^) -o $@
@@ -186,6 +193,7 @@ distprep:
 	$(MAKE) -C replication	repl_gram.c repl_scanner.c syncrep_gram.c syncrep_scanner.c
 	$(MAKE) -C storage/lmgr	lwlocknames.h lwlocknames.c
 	$(MAKE) -C utils	distprep
+	$(MAKE) -C utils/adt	jsonpath_gram.c jsonpath_gram.h jsonpath_scan.c
 	$(MAKE) -C utils/misc	guc-file.c
 	$(MAKE) -C utils/sort	qsort_tuple.c
 
@@ -308,6 +316,7 @@ maintainer-clean: distclean
 	      storage/lmgr/lwlocknames.c \
 	      storage/lmgr/lwlocknames.h \
 	      utils/misc/guc-file.c \
+	      utils/adt/jsonpath_gram.h \
 	      utils/sort/qsort_tuple.c
 
 
diff --git a/src/backend/catalog/system_views.sql b/src/backend/catalog/system_views.sql
index 3e229c6..f5d11d5 100644
--- a/src/backend/catalog/system_views.sql
+++ b/src/backend/catalog/system_views.sql
@@ -1127,6 +1127,46 @@ LANGUAGE INTERNAL
 STRICT IMMUTABLE PARALLEL SAFE
 AS 'jsonb_insert';
 
+CREATE OR REPLACE FUNCTION
+  jsonb_path_exists(target jsonb, path jsonpath, vars jsonb DEFAULT '{}',
+                    silent boolean DEFAULT false)
+RETURNS boolean
+LANGUAGE INTERNAL
+STRICT IMMUTABLE PARALLEL SAFE
+AS 'jsonb_path_exists';
+
+CREATE OR REPLACE FUNCTION
+  jsonb_path_match(target jsonb, path jsonpath, vars jsonb DEFAULT '{}',
+                   silent boolean DEFAULT false)
+RETURNS boolean
+LANGUAGE INTERNAL
+STRICT IMMUTABLE PARALLEL SAFE
+AS 'jsonb_path_match';
+
+CREATE OR REPLACE FUNCTION
+  jsonb_path_query(target jsonb, path jsonpath, vars jsonb DEFAULT '{}',
+                   silent boolean DEFAULT false)
+RETURNS SETOF jsonb
+LANGUAGE INTERNAL
+STRICT IMMUTABLE PARALLEL SAFE
+AS 'jsonb_path_query';
+
+CREATE OR REPLACE FUNCTION
+  jsonb_path_query_array(target jsonb, path jsonpath, vars jsonb DEFAULT '{}',
+                         silent boolean DEFAULT false)
+RETURNS jsonb
+LANGUAGE INTERNAL
+STRICT IMMUTABLE PARALLEL SAFE
+AS 'jsonb_path_query_array';
+
+CREATE OR REPLACE FUNCTION
+  jsonb_path_query_first(target jsonb, path jsonpath, vars jsonb DEFAULT '{}',
+                         silent boolean DEFAULT false)
+RETURNS jsonb
+LANGUAGE INTERNAL
+STRICT IMMUTABLE PARALLEL SAFE
+AS 'jsonb_path_query_first';
+
 --
 -- The default permissions for functions mean that anyone can execute them.
 -- A number of functions shouldn't be executable by just anyone, but rather
diff --git a/src/backend/utils/adt/.gitignore b/src/backend/utils/adt/.gitignore
new file mode 100644
index 0000000..7fab054
--- /dev/null
+++ b/src/backend/utils/adt/.gitignore
@@ -0,0 +1,3 @@
+/jsonpath_gram.h
+/jsonpath_gram.c
+/jsonpath_scan.c
diff --git a/src/backend/utils/adt/Makefile b/src/backend/utils/adt/Makefile
index 82d10af..6b24a9c 100644
--- a/src/backend/utils/adt/Makefile
+++ b/src/backend/utils/adt/Makefile
@@ -17,8 +17,8 @@ OBJS = acl.o amutils.o arrayfuncs.o array_expanded.o array_selfuncs.o \
 	float.o format_type.o formatting.o genfile.o \
 	geo_ops.o geo_selfuncs.o geo_spgist.o inet_cidr_ntop.o inet_net_pton.o \
 	int.o int8.o json.o jsonb.o jsonb_gin.o jsonb_op.o jsonb_util.o \
-	jsonfuncs.o like.o like_support.o lockfuncs.o \
-	mac.o mac8.o misc.o name.o \
+	jsonfuncs.o jsonpath_gram.o jsonpath_scan.o jsonpath.o jsonpath_exec.o \
+	like.o like_support.o lockfuncs.o mac.o mac8.o misc.o name.o \
 	network.o network_gist.o network_selfuncs.o network_spgist.o \
 	numeric.o numutils.o oid.o oracle_compat.o \
 	orderedsetaggs.o partitionfuncs.o pg_locale.o pg_lsn.o \
@@ -33,6 +33,21 @@ OBJS = acl.o amutils.o arrayfuncs.o array_expanded.o array_selfuncs.o \
 	txid.o uuid.o varbit.o varchar.o varlena.o version.o \
 	windowfuncs.o xid.o xml.o
 
+jsonpath_gram.c: BISONFLAGS += -d
+
+jsonpath_scan.c: FLEXFLAGS = -CF -p -p
+
+jsonpath_gram.h: jsonpath_gram.c ;
+
+# Force these dependencies to be known even without dependency info built:
+jsonpath_gram.o jsonpath_scan.o jsonpath_parser.o: jsonpath_gram.h
+
+# jsonpath_gram.c, jsonpath_gram.h, and jsonpath_scan.c are in the
+# distribution tarball, so they are not cleaned here.
+clean distclean maintainer-clean:
+	rm -f lex.backup
+
+
 like.o: like.c like_match.c
 
 varlena.o: varlena.c levenshtein.c
diff --git a/src/backend/utils/adt/jsonb.c b/src/backend/utils/adt/jsonb.c
index c02c856..7af4091 100644
--- a/src/backend/utils/adt/jsonb.c
+++ b/src/backend/utils/adt/jsonb.c
@@ -164,6 +164,55 @@ jsonb_send(PG_FUNCTION_ARGS)
 }
 
 /*
+ * Get the type name of a jsonb container.
+ */
+static const char *
+JsonbContainerTypeName(JsonbContainer *jbc)
+{
+	JsonbValue	scalar;
+
+	if (JsonbExtractScalar(jbc, &scalar))
+		return JsonbTypeName(&scalar);
+	else if (JsonContainerIsArray(jbc))
+		return "array";
+	else if (JsonContainerIsObject(jbc))
+		return "object";
+	else
+	{
+		elog(ERROR, "invalid jsonb container type: 0x%08x", jbc->header);
+		return "unknown";
+	}
+}
+
+/*
+ * Get the type name of a jsonb value.
+ */
+const char *
+JsonbTypeName(JsonbValue *jbv)
+{
+	switch (jbv->type)
+	{
+		case jbvBinary:
+			return JsonbContainerTypeName(jbv->val.binary.data);
+		case jbvObject:
+			return "object";
+		case jbvArray:
+			return "array";
+		case jbvNumeric:
+			return "number";
+		case jbvString:
+			return "string";
+		case jbvBool:
+			return "boolean";
+		case jbvNull:
+			return "null";
+		default:
+			elog(ERROR, "unrecognized jsonb value type: %d", jbv->type);
+			return "unknown";
+	}
+}
+
+/*
  * SQL function jsonb_typeof(jsonb) -> text
  *
  * This function is here because the analog json function is in json.c, since
@@ -173,45 +222,7 @@ Datum
 jsonb_typeof(PG_FUNCTION_ARGS)
 {
 	Jsonb	   *in = PG_GETARG_JSONB_P(0);
-	JsonbIterator *it;
-	JsonbValue	v;
-	char	   *result;
-
-	if (JB_ROOT_IS_OBJECT(in))
-		result = "object";
-	else if (JB_ROOT_IS_ARRAY(in) && !JB_ROOT_IS_SCALAR(in))
-		result = "array";
-	else
-	{
-		Assert(JB_ROOT_IS_SCALAR(in));
-
-		it = JsonbIteratorInit(&in->root);
-
-		/*
-		 * A root scalar is stored as an array of one element, so we get the
-		 * array and then its first (and only) member.
-		 */
-		(void) JsonbIteratorNext(&it, &v, true);
-		Assert(v.type == jbvArray);
-		(void) JsonbIteratorNext(&it, &v, true);
-		switch (v.type)
-		{
-			case jbvNull:
-				result = "null";
-				break;
-			case jbvString:
-				result = "string";
-				break;
-			case jbvNumeric:
-				result = "number";
-				break;
-			case jbvBool:
-				result = "boolean";
-				break;
-			default:
-				elog(ERROR, "unknown jsonb scalar type");
-		}
-	}
+	const char *result = JsonbContainerTypeName(&in->root);
 
 	PG_RETURN_TEXT_P(cstring_to_text(result));
 }
@@ -1857,7 +1868,7 @@ jsonb_object_agg_finalfn(PG_FUNCTION_ARGS)
 /*
  * Extract scalar value from raw-scalar pseudo-array jsonb.
  */
-static bool
+bool
 JsonbExtractScalar(JsonbContainer *jbc, JsonbValue *res)
 {
 	JsonbIterator *it;
diff --git a/src/backend/utils/adt/jsonb_util.c b/src/backend/utils/adt/jsonb_util.c
index 6695363..d8276ab 100644
--- a/src/backend/utils/adt/jsonb_util.c
+++ b/src/backend/utils/adt/jsonb_util.c
@@ -1728,6 +1728,14 @@ convertJsonbScalar(StringInfo buffer, JEntry *jentry, JsonbValue *scalarVal)
 			break;
 
 		case jbvNumeric:
+			/* replace numeric NaN with string "NaN" */
+			if (numeric_is_nan(scalarVal->val.numeric))
+			{
+				appendToBuffer(buffer, "NaN", 3);
+				*jentry = 3;
+				break;
+			}
+
 			numlen = VARSIZE_ANY(scalarVal->val.numeric);
 			padlen = padBufferToInt(buffer);
 
diff --git a/src/backend/utils/adt/jsonpath.c b/src/backend/utils/adt/jsonpath.c
new file mode 100644
index 0000000..0696b04
--- /dev/null
+++ b/src/backend/utils/adt/jsonpath.c
@@ -0,0 +1,1051 @@
+/*-------------------------------------------------------------------------
+ *
+ * jsonpath.c
+ *	 Input/output and supporting routines for jsonpath
+ *
+ * jsonpath expression is a chain of path items.  First path item is $, $var,
+ * literal or arithmetic expression.  Subsequent path items are accessors
+ * (.key, .*, [subscripts], [*]), filters (? (predicate)) and methods (.type(),
+ * .size() etc).
+ *
+ * For instance, structure of path items for simple expression:
+ *
+ *		$.a[*].type()
+ *
+ * is pretty evident:
+ *
+ *		$ => .a => [*] => .type()
+ *
+ * Some path items such as arithmetic operations, predicates or array
+ * subscripts may comprise subtrees.  For instance, more complex expression
+ *
+ *		($.a + $[1 to 5, 7] ? (@ > 3).double()).type()
+ *
+ * have following structure of path items:
+ *
+ *			   +  =>  .type()
+ *		  ___/ \___
+ *		 /		   \
+ *		$ => .a 	$  =>  []  =>	?  =>  .double()
+ *						  _||_		|
+ *						 /	  \ 	>
+ *						to	  to   / \
+ *					   / \	  /   @   3
+ *					  1   5  7
+ *
+ * Binary encoding of jsonpath constitutes a sequence of 4-bytes aligned
+ * variable-length path items connected by links.  Every item has a header
+ * consisting of item type (enum JsonPathItemType) and offset of next item
+ * (zero means no next item).  After the header, item may have payload
+ * depending on item type.  For instance, payload of '.key' accessor item is
+ * length of key name and key name itself.  Payload of '>' arithmetic operator
+ * item is offsets of right and left operands.
+ *
+ * So, binary representation of sample expression above is:
+ * (bottom arrows are next links, top lines are argument links)
+ *
+ *								  _____
+ *		 _____				  ___/____ \				__
+ *	  _ /_	  \ 		_____/__/____ \ \	   __    _ /_ \
+ *	 / /  \    \	   /	/  /	 \ \ \ 	  /  \  / /  \ \
+ * +(LR)  $ .a	$  [](* to *, * to *) 1 5 7 ?(A)  >(LR)   @ 3 .double() .type()
+ * |	  |  ^	|  ^|						 ^|					  ^		   ^
+ * |	  |__|	|__||________________________||___________________|		   |
+ * |_______________________________________________________________________|
+ *
+ * Copyright (c) 2019, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ *	src/backend/utils/adt/jsonpath.c
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#include "postgres.h"
+
+#include "funcapi.h"
+#include "lib/stringinfo.h"
+#include "libpq/pqformat.h"
+#include "miscadmin.h"
+#include "utils/builtins.h"
+#include "utils/json.h"
+#include "utils/jsonpath.h"
+
+
+static Datum jsonPathFromCstring(char *in, int len);
+static char *jsonPathToCstring(StringInfo out, JsonPath *in,
+				  int estimated_len);
+static int flattenJsonPathParseItem(StringInfo buf, JsonPathParseItem *item,
+						 int nestingLevel, bool insideArraySubscript);
+static void alignStringInfoInt(StringInfo buf);
+static void printJsonPathItem(StringInfo buf, JsonPathItem *v, bool inKey,
+				  bool printBracketes);
+static int	operationPriority(JsonPathItemType op);
+
+
+/**************************** INPUT/OUTPUT ********************************/
+
+/*
+ * jsonpath type input function
+ */
+Datum
+jsonpath_in(PG_FUNCTION_ARGS)
+{
+	char	   *in = PG_GETARG_CSTRING(0);
+	int			len = strlen(in);
+
+	return jsonPathFromCstring(in, len);
+}
+
+/*
+ * jsonpath type recv function
+ *
+ * The type is sent as text in binary mode, so this is almost the same
+ * as the input function, but it's prefixed with a version number so we
+ * can change the binary format sent in future if necessary. For now,
+ * only version 1 is supported.
+ */
+Datum
+jsonpath_recv(PG_FUNCTION_ARGS)
+{
+	StringInfo	buf = (StringInfo) PG_GETARG_POINTER(0);
+	int			version = pq_getmsgint(buf, 1);
+	char	   *str;
+	int			nbytes;
+
+	if (version == 1)
+		str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
+	else
+		elog(ERROR, "unsupported jsonb version number %d", version);
+
+	return jsonPathFromCstring(str, nbytes);
+}
+
+/*
+ * jsonpath type output function
+ */
+Datum
+jsonpath_out(PG_FUNCTION_ARGS)
+{
+	JsonPath   *in = PG_GETARG_JSONPATH_P(0);
+
+	PG_RETURN_CSTRING(jsonPathToCstring(NULL, in, VARSIZE(in)));
+}
+
+/*
+ * jsonpath type send function
+ *
+ * Just send jsonpath as a version number, then a string of text
+ */
+Datum
+jsonpath_send(PG_FUNCTION_ARGS)
+{
+	JsonPath   *in = PG_GETARG_JSONPATH_P(0);
+	StringInfoData buf;
+	StringInfo	jtext = makeStringInfo();
+	int			version = 1;
+
+	(void) jsonPathToCstring(jtext, in, VARSIZE(in));
+
+	pq_begintypsend(&buf);
+	pq_sendint8(&buf, version);
+	pq_sendtext(&buf, jtext->data, jtext->len);
+	pfree(jtext->data);
+	pfree(jtext);
+
+	PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
+}
+
+/*
+ * Converts C-string to a jsonpath value.
+ *
+ * Uses jsonpath parser to turn string into an AST, then
+ * flattenJsonPathParseItem() does second pass turning AST into binary
+ * representation of jsonpath.
+ */
+static Datum
+jsonPathFromCstring(char *in, int len)
+{
+	JsonPathParseResult *jsonpath = parsejsonpath(in, len);
+	JsonPath   *res;
+	StringInfoData buf;
+
+	initStringInfo(&buf);
+	enlargeStringInfo(&buf, 4 * len /* estimation */ );
+
+	appendStringInfoSpaces(&buf, JSONPATH_HDRSZ);
+
+	if (!jsonpath)
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
+				 errmsg("invalid input syntax for jsonpath: \"%s\"", in)));
+
+	flattenJsonPathParseItem(&buf, jsonpath->expr, 0, false);
+
+	res = (JsonPath *) buf.data;
+	SET_VARSIZE(res, buf.len);
+	res->header = JSONPATH_VERSION;
+	if (jsonpath->lax)
+		res->header |= JSONPATH_LAX;
+
+	PG_RETURN_JSONPATH_P(res);
+}
+
+/*
+ * Converts jsonpath value to a C-string.
+ *
+ * If 'out' argument is non-null, the resulting C-string is stored inside the
+ * StringBuffer.  The resulting string is always returned.
+ */
+static char *
+jsonPathToCstring(StringInfo out, JsonPath *in, int estimated_len)
+{
+	StringInfoData buf;
+	JsonPathItem v;
+
+	if (!out)
+	{
+		out = &buf;
+		initStringInfo(out);
+	}
+	enlargeStringInfo(out, estimated_len);
+
+	if (!(in->header & JSONPATH_LAX))
+		appendBinaryStringInfo(out, "strict ", 7);
+
+	jspInit(&v, in);
+	printJsonPathItem(out, &v, false, true);
+
+	return out->data;
+}
+
+/*
+ * Recursive function converting given jsonpath parse item and all its
+ * children into a binary representation.
+ */
+static int
+flattenJsonPathParseItem(StringInfo buf, JsonPathParseItem *item,
+						 int nestingLevel, bool insideArraySubscript)
+{
+	/* position from begining of jsonpath data */
+	int32		pos = buf->len - JSONPATH_HDRSZ;
+	int32		chld;
+	int32		next;
+	int			argNestingLevel = 0;
+
+	check_stack_depth();
+	CHECK_FOR_INTERRUPTS();
+
+	appendStringInfoChar(buf, (char) (item->type));
+	alignStringInfoInt(buf);
+
+	next = (item->next) ? buf->len : 0;
+
+	/*
+	 * Actual value will be recorded later, after next and children
+	 * processing.
+	 */
+	appendBinaryStringInfo(buf,
+						   (char *) &next,	/* fake value */
+						   sizeof(next));
+
+	switch (item->type)
+	{
+		case jpiString:
+		case jpiVariable:
+		case jpiKey:
+			appendBinaryStringInfo(buf, (char *) &item->value.string.len,
+								   sizeof(item->value.string.len));
+			appendBinaryStringInfo(buf, item->value.string.val,
+								   item->value.string.len);
+			appendStringInfoChar(buf, '\0');
+			break;
+		case jpiNumeric:
+			appendBinaryStringInfo(buf, (char *) item->value.numeric,
+								   VARSIZE(item->value.numeric));
+			break;
+		case jpiBool:
+			appendBinaryStringInfo(buf, (char *) &item->value.boolean,
+								   sizeof(item->value.boolean));
+			break;
+		case jpiAnd:
+		case jpiOr:
+		case jpiEqual:
+		case jpiNotEqual:
+		case jpiLess:
+		case jpiGreater:
+		case jpiLessOrEqual:
+		case jpiGreaterOrEqual:
+		case jpiAdd:
+		case jpiSub:
+		case jpiMul:
+		case jpiDiv:
+		case jpiMod:
+		case jpiStartsWith:
+			{
+				int32		left,
+							right;
+
+				left = buf->len;
+
+				/*
+				 * First, reserve place for left/right arg's positions, then
+				 * record both args and sets actual position in reserved
+				 * places.
+				 */
+				appendBinaryStringInfo(buf,
+									   (char *) &left,	/* fake value */
+									   sizeof(left));
+				right = buf->len;
+				appendBinaryStringInfo(buf,
+									   (char *) &right, /* fake value */
+									   sizeof(right));
+
+				chld = !item->value.args.left ? pos :
+					flattenJsonPathParseItem(buf, item->value.args.left,
+											 nestingLevel + argNestingLevel,
+											 insideArraySubscript);
+				*(int32 *) (buf->data + left) = chld - pos;
+				chld = !item->value.args.right ? pos :
+					flattenJsonPathParseItem(buf, item->value.args.right,
+											 nestingLevel + argNestingLevel,
+											 insideArraySubscript);
+				*(int32 *) (buf->data + right) = chld - pos;
+			}
+			break;
+		case jpiLikeRegex:
+			{
+				int32		offs;
+
+				appendBinaryStringInfo(buf,
+									   (char *) &item->value.like_regex.flags,
+									   sizeof(item->value.like_regex.flags));
+				offs = buf->len;
+				appendBinaryStringInfo(buf,
+									   (char *) &offs,	/* fake value */
+									   sizeof(offs));
+				appendBinaryStringInfo(buf,
+									   (char *) &item->value.like_regex.patternlen,
+									   sizeof(item->value.like_regex.patternlen));
+				appendBinaryStringInfo(buf, item->value.like_regex.pattern,
+									   item->value.like_regex.patternlen);
+				appendStringInfoChar(buf, '\0');
+
+				chld = flattenJsonPathParseItem(buf, item->value.like_regex.expr,
+												nestingLevel,
+												insideArraySubscript);
+				*(int32 *) (buf->data + offs) = chld - pos;
+			}
+			break;
+		case jpiFilter:
+			argNestingLevel++;
+			/* fall through */
+		case jpiIsUnknown:
+		case jpiNot:
+		case jpiPlus:
+		case jpiMinus:
+		case jpiExists:
+			{
+				int32		arg;
+
+				arg = buf->len;
+				appendBinaryStringInfo(buf,
+									   (char *) &arg,	/* fake value */
+									   sizeof(arg));
+
+				chld = flattenJsonPathParseItem(buf, item->value.arg,
+												nestingLevel + argNestingLevel,
+												insideArraySubscript);
+				*(int32 *) (buf->data + arg) = chld - pos;
+			}
+			break;
+		case jpiNull:
+			break;
+		case jpiRoot:
+			break;
+		case jpiAnyArray:
+		case jpiAnyKey:
+			break;
+		case jpiCurrent:
+			if (nestingLevel <= 0)
+				ereport(ERROR,
+						(errcode(ERRCODE_SYNTAX_ERROR),
+						 errmsg("@ is not allowed in root expressions")));
+			break;
+		case jpiLast:
+			if (!insideArraySubscript)
+				ereport(ERROR,
+						(errcode(ERRCODE_SYNTAX_ERROR),
+						 errmsg("LAST is allowed only in array subscripts")));
+			break;
+		case jpiIndexArray:
+			{
+				int32		nelems = item->value.array.nelems;
+				int			offset;
+				int			i;
+
+				appendBinaryStringInfo(buf, (char *) &nelems, sizeof(nelems));
+
+				offset = buf->len;
+
+				appendStringInfoSpaces(buf, sizeof(int32) * 2 * nelems);
+
+				for (i = 0; i < nelems; i++)
+				{
+					int32	   *ppos;
+					int32		topos;
+					int32		frompos =
+					flattenJsonPathParseItem(buf,
+											 item->value.array.elems[i].from,
+											 nestingLevel, true) - pos;
+
+					if (item->value.array.elems[i].to)
+						topos = flattenJsonPathParseItem(buf,
+														 item->value.array.elems[i].to,
+														 nestingLevel, true) - pos;
+					else
+						topos = 0;
+
+					ppos = (int32 *) &buf->data[offset + i * 2 * sizeof(int32)];
+
+					ppos[0] = frompos;
+					ppos[1] = topos;
+				}
+			}
+			break;
+		case jpiAny:
+			appendBinaryStringInfo(buf,
+								   (char *) &item->value.anybounds.first,
+								   sizeof(item->value.anybounds.first));
+			appendBinaryStringInfo(buf,
+								   (char *) &item->value.anybounds.last,
+								   sizeof(item->value.anybounds.last));
+			break;
+		case jpiType:
+		case jpiSize:
+		case jpiAbs:
+		case jpiFloor:
+		case jpiCeiling:
+		case jpiDouble:
+		case jpiKeyValue:
+			break;
+		default:
+			elog(ERROR, "unrecognized jsonpath item type: %d", item->type);
+	}
+
+	if (item->next)
+	{
+		chld = flattenJsonPathParseItem(buf, item->next, nestingLevel,
+										insideArraySubscript) - pos;
+		*(int32 *) (buf->data + next) = chld;
+	}
+
+	return pos;
+}
+
+/*
+ * Aling StringInfo to int by adding zero padding bytes
+ */
+static void
+alignStringInfoInt(StringInfo buf)
+{
+	switch (INTALIGN(buf->len) - buf->len)
+	{
+		case 3:
+			appendStringInfoCharMacro(buf, 0);
+		case 2:
+			appendStringInfoCharMacro(buf, 0);
+		case 1:
+			appendStringInfoCharMacro(buf, 0);
+		default:
+			break;
+	}
+}
+
+/*
+ * Prints text representation of given jsonpath item and all its children.
+ */
+static void
+printJsonPathItem(StringInfo buf, JsonPathItem *v, bool inKey,
+				  bool printBracketes)
+{
+	JsonPathItem elem;
+	int			i;
+
+	check_stack_depth();
+
+	switch (v->type)
+	{
+		case jpiNull:
+			appendStringInfoString(buf, "null");
+			break;
+		case jpiKey:
+			if (inKey)
+				appendStringInfoChar(buf, '.');
+			escape_json(buf, jspGetString(v, NULL));
+			break;
+		case jpiString:
+			escape_json(buf, jspGetString(v, NULL));
+			break;
+		case jpiVariable:
+			appendStringInfoChar(buf, '$');
+			escape_json(buf, jspGetString(v, NULL));
+			break;
+		case jpiNumeric:
+			appendStringInfoString(buf,
+								   DatumGetCString(DirectFunctionCall1(numeric_out,
+																	   PointerGetDatum(jspGetNumeric(v)))));
+			break;
+		case jpiBool:
+			if (jspGetBool(v))
+				appendBinaryStringInfo(buf, "true", 4);
+			else
+				appendBinaryStringInfo(buf, "false", 5);
+			break;
+		case jpiAnd:
+		case jpiOr:
+		case jpiEqual:
+		case jpiNotEqual:
+		case jpiLess:
+		case jpiGreater:
+		case jpiLessOrEqual:
+		case jpiGreaterOrEqual:
+		case jpiAdd:
+		case jpiSub:
+		case jpiMul:
+		case jpiDiv:
+		case jpiMod:
+		case jpiStartsWith:
+			if (printBracketes)
+				appendStringInfoChar(buf, '(');
+			jspGetLeftArg(v, &elem);
+			printJsonPathItem(buf, &elem, false,
+							  operationPriority(elem.type) <=
+							  operationPriority(v->type));
+			appendStringInfoChar(buf, ' ');
+			appendStringInfoString(buf, jspOperationName(v->type));
+			appendStringInfoChar(buf, ' ');
+			jspGetRightArg(v, &elem);
+			printJsonPathItem(buf, &elem, false,
+							  operationPriority(elem.type) <=
+							  operationPriority(v->type));
+			if (printBracketes)
+				appendStringInfoChar(buf, ')');
+			break;
+		case jpiLikeRegex:
+			if (printBracketes)
+				appendStringInfoChar(buf, '(');
+
+			jspInitByBuffer(&elem, v->base, v->content.like_regex.expr);
+			printJsonPathItem(buf, &elem, false,
+							  operationPriority(elem.type) <=
+							  operationPriority(v->type));
+
+			appendBinaryStringInfo(buf, " like_regex ", 12);
+
+			escape_json(buf, v->content.like_regex.pattern);
+
+			if (v->content.like_regex.flags)
+			{
+				appendBinaryStringInfo(buf, " flag \"", 7);
+
+				if (v->content.like_regex.flags & JSP_REGEX_ICASE)
+					appendStringInfoChar(buf, 'i');
+				if (v->content.like_regex.flags & JSP_REGEX_SLINE)
+					appendStringInfoChar(buf, 's');
+				if (v->content.like_regex.flags & JSP_REGEX_MLINE)
+					appendStringInfoChar(buf, 'm');
+				if (v->content.like_regex.flags & JSP_REGEX_WSPACE)
+					appendStringInfoChar(buf, 'x');
+
+				appendStringInfoChar(buf, '"');
+			}
+
+			if (printBracketes)
+				appendStringInfoChar(buf, ')');
+			break;
+		case jpiPlus:
+		case jpiMinus:
+			if (printBracketes)
+				appendStringInfoChar(buf, '(');
+			appendStringInfoChar(buf, v->type == jpiPlus ? '+' : '-');
+			jspGetArg(v, &elem);
+			printJsonPathItem(buf, &elem, false,
+							  operationPriority(elem.type) <=
+							  operationPriority(v->type));
+			if (printBracketes)
+				appendStringInfoChar(buf, ')');
+			break;
+		case jpiFilter:
+			appendBinaryStringInfo(buf, "?(", 2);
+			jspGetArg(v, &elem);
+			printJsonPathItem(buf, &elem, false, false);
+			appendStringInfoChar(buf, ')');
+			break;
+		case jpiNot:
+			appendBinaryStringInfo(buf, "!(", 2);
+			jspGetArg(v, &elem);
+			printJsonPathItem(buf, &elem, false, false);
+			appendStringInfoChar(buf, ')');
+			break;
+		case jpiIsUnknown:
+			appendStringInfoChar(buf, '(');
+			jspGetArg(v, &elem);
+			printJsonPathItem(buf, &elem, false, false);
+			appendBinaryStringInfo(buf, ") is unknown", 12);
+			break;
+		case jpiExists:
+			appendBinaryStringInfo(buf, "exists (", 8);
+			jspGetArg(v, &elem);
+			printJsonPathItem(buf, &elem, false, false);
+			appendStringInfoChar(buf, ')');
+			break;
+		case jpiCurrent:
+			Assert(!inKey);
+			appendStringInfoChar(buf, '@');
+			break;
+		case jpiRoot:
+			Assert(!inKey);
+			appendStringInfoChar(buf, '$');
+			break;
+		case jpiLast:
+			appendBinaryStringInfo(buf, "last", 4);
+			break;
+		case jpiAnyArray:
+			appendBinaryStringInfo(buf, "[*]", 3);
+			break;
+		case jpiAnyKey:
+			if (inKey)
+				appendStringInfoChar(buf, '.');
+			appendStringInfoChar(buf, '*');
+			break;
+		case jpiIndexArray:
+			appendStringInfoChar(buf, '[');
+			for (i = 0; i < v->content.array.nelems; i++)
+			{
+				JsonPathItem from;
+				JsonPathItem to;
+				bool		range = jspGetArraySubscript(v, &from, &to, i);
+
+				if (i)
+					appendStringInfoChar(buf, ',');
+
+				printJsonPathItem(buf, &from, false, false);
+
+				if (range)
+				{
+					appendBinaryStringInfo(buf, " to ", 4);
+					printJsonPathItem(buf, &to, false, false);
+				}
+			}
+			appendStringInfoChar(buf, ']');
+			break;
+		case jpiAny:
+			if (inKey)
+				appendStringInfoChar(buf, '.');
+
+			if (v->content.anybounds.first == 0 &&
+				v->content.anybounds.last == PG_UINT32_MAX)
+				appendBinaryStringInfo(buf, "**", 2);
+			else if (v->content.anybounds.first == v->content.anybounds.last)
+			{
+				if (v->content.anybounds.first == PG_UINT32_MAX)
+					appendStringInfo(buf, "**{last}");
+				else
+					appendStringInfo(buf, "**{%u}",
+									 v->content.anybounds.first);
+			}
+			else if (v->content.anybounds.first == PG_UINT32_MAX)
+				appendStringInfo(buf, "**{last to %u}",
+								 v->content.anybounds.last);
+			else if (v->content.anybounds.last == PG_UINT32_MAX)
+				appendStringInfo(buf, "**{%u to last}",
+								 v->content.anybounds.first);
+			else
+				appendStringInfo(buf, "**{%u to %u}",
+								 v->content.anybounds.first,
+								 v->content.anybounds.last);
+			break;
+		case jpiType:
+			appendBinaryStringInfo(buf, ".type()", 7);
+			break;
+		case jpiSize:
+			appendBinaryStringInfo(buf, ".size()", 7);
+			break;
+		case jpiAbs:
+			appendBinaryStringInfo(buf, ".abs()", 6);
+			break;
+		case jpiFloor:
+			appendBinaryStringInfo(buf, ".floor()", 8);
+			break;
+		case jpiCeiling:
+			appendBinaryStringInfo(buf, ".ceiling()", 10);
+			break;
+		case jpiDouble:
+			appendBinaryStringInfo(buf, ".double()", 9);
+			break;
+		case jpiKeyValue:
+			appendBinaryStringInfo(buf, ".keyvalue()", 11);
+			break;
+		default:
+			elog(ERROR, "unrecognized jsonpath item type: %d", v->type);
+	}
+
+	if (jspGetNext(v, &elem))
+		printJsonPathItem(buf, &elem, true, true);
+}
+
+const char *
+jspOperationName(JsonPathItemType type)
+{
+	switch (type)
+	{
+		case jpiAnd:
+			return "&&";
+		case jpiOr:
+			return "||";
+		case jpiEqual:
+			return "==";
+		case jpiNotEqual:
+			return "!=";
+		case jpiLess:
+			return "<";
+		case jpiGreater:
+			return ">";
+		case jpiLessOrEqual:
+			return "<=";
+		case jpiGreaterOrEqual:
+			return ">=";
+		case jpiPlus:
+		case jpiAdd:
+			return "+";
+		case jpiMinus:
+		case jpiSub:
+			return "-";
+		case jpiMul:
+			return "*";
+		case jpiDiv:
+			return "/";
+		case jpiMod:
+			return "%";
+		case jpiStartsWith:
+			return "starts with";
+		case jpiLikeRegex:
+			return "like_regex";
+		case jpiType:
+			return "type";
+		case jpiSize:
+			return "size";
+		case jpiKeyValue:
+			return "keyvalue";
+		case jpiDouble:
+			return "double";
+		case jpiAbs:
+			return "abs";
+		case jpiFloor:
+			return "floor";
+		case jpiCeiling:
+			return "ceiling";
+		default:
+			elog(ERROR, "unrecognized jsonpath item type: %d", type);
+			return NULL;
+	}
+}
+
+static int
+operationPriority(JsonPathItemType op)
+{
+	switch (op)
+	{
+		case jpiOr:
+			return 0;
+		case jpiAnd:
+			return 1;
+		case jpiEqual:
+		case jpiNotEqual:
+		case jpiLess:
+		case jpiGreater:
+		case jpiLessOrEqual:
+		case jpiGreaterOrEqual:
+		case jpiStartsWith:
+			return 2;
+		case jpiAdd:
+		case jpiSub:
+			return 3;
+		case jpiMul:
+		case jpiDiv:
+		case jpiMod:
+			return 4;
+		case jpiPlus:
+		case jpiMinus:
+			return 5;
+		default:
+			return 6;
+	}
+}
+
+/******************* Support functions for JsonPath *************************/
+
+/*
+ * Support macros to read stored values
+ */
+
+#define read_byte(v, b, p) do {			\
+	(v) = *(uint8*)((b) + (p));			\
+	(p) += 1;							\
+} while(0)								\
+
+#define read_int32(v, b, p) do {		\
+	(v) = *(uint32*)((b) + (p));		\
+	(p) += sizeof(int32);				\
+} while(0)								\
+
+#define read_int32_n(v, b, p, n) do {	\
+	(v) = (void *)((b) + (p));			\
+	(p) += sizeof(int32) * (n);			\
+} while(0)								\
+
+/*
+ * Read root node and fill root node representation
+ */
+void
+jspInit(JsonPathItem *v, JsonPath *js)
+{
+	Assert((js->header & ~JSONPATH_LAX) == JSONPATH_VERSION);
+	jspInitByBuffer(v, js->data, 0);
+}
+
+/*
+ * Read node from buffer and fill its representation
+ */
+void
+jspInitByBuffer(JsonPathItem *v, char *base, int32 pos)
+{
+	v->base = base + pos;
+
+	read_byte(v->type, base, pos);
+	pos = INTALIGN((uintptr_t) (base + pos)) - (uintptr_t) base;
+	read_int32(v->nextPos, base, pos);
+
+	switch (v->type)
+	{
+		case jpiNull:
+		case jpiRoot:
+		case jpiCurrent:
+		case jpiAnyArray:
+		case jpiAnyKey:
+		case jpiType:
+		case jpiSize:
+		case jpiAbs:
+		case jpiFloor:
+		case jpiCeiling:
+		case jpiDouble:
+		case jpiKeyValue:
+		case jpiLast:
+			break;
+		case jpiKey:
+		case jpiString:
+		case jpiVariable:
+			read_int32(v->content.value.datalen, base, pos);
+			/* follow next */
+		case jpiNumeric:
+		case jpiBool:
+			v->content.value.data = base + pos;
+			break;
+		case jpiAnd:
+		case jpiOr:
+		case jpiAdd:
+		case jpiSub:
+		case jpiMul:
+		case jpiDiv:
+		case jpiMod:
+		case jpiEqual:
+		case jpiNotEqual:
+		case jpiLess:
+		case jpiGreater:
+		case jpiLessOrEqual:
+		case jpiGreaterOrEqual:
+		case jpiStartsWith:
+			read_int32(v->content.args.left, base, pos);
+			read_int32(v->content.args.right, base, pos);
+			break;
+		case jpiLikeRegex:
+			read_int32(v->content.like_regex.flags, base, pos);
+			read_int32(v->content.like_regex.expr, base, pos);
+			read_int32(v->content.like_regex.patternlen, base, pos);
+			v->content.like_regex.pattern = base + pos;
+			break;
+		case jpiNot:
+		case jpiExists:
+		case jpiIsUnknown:
+		case jpiPlus:
+		case jpiMinus:
+		case jpiFilter:
+			read_int32(v->content.arg, base, pos);
+			break;
+		case jpiIndexArray:
+			read_int32(v->content.array.nelems, base, pos);
+			read_int32_n(v->content.array.elems, base, pos,
+						 v->content.array.nelems * 2);
+			break;
+		case jpiAny:
+			read_int32(v->content.anybounds.first, base, pos);
+			read_int32(v->content.anybounds.last, base, pos);
+			break;
+		default:
+			elog(ERROR, "unrecognized jsonpath item type: %d", v->type);
+	}
+}
+
+void
+jspGetArg(JsonPathItem *v, JsonPathItem *a)
+{
+	Assert(v->type == jpiFilter ||
+		   v->type == jpiNot ||
+		   v->type == jpiIsUnknown ||
+		   v->type == jpiExists ||
+		   v->type == jpiPlus ||
+		   v->type == jpiMinus);
+
+	jspInitByBuffer(a, v->base, v->content.arg);
+}
+
+bool
+jspGetNext(JsonPathItem *v, JsonPathItem *a)
+{
+	if (jspHasNext(v))
+	{
+		Assert(v->type == jpiString ||
+			   v->type == jpiNumeric ||
+			   v->type == jpiBool ||
+			   v->type == jpiNull ||
+			   v->type == jpiKey ||
+			   v->type == jpiAny ||
+			   v->type == jpiAnyArray ||
+			   v->type == jpiAnyKey ||
+			   v->type == jpiIndexArray ||
+			   v->type == jpiFilter ||
+			   v->type == jpiCurrent ||
+			   v->type == jpiExists ||
+			   v->type == jpiRoot ||
+			   v->type == jpiVariable ||
+			   v->type == jpiLast ||
+			   v->type == jpiAdd ||
+			   v->type == jpiSub ||
+			   v->type == jpiMul ||
+			   v->type == jpiDiv ||
+			   v->type == jpiMod ||
+			   v->type == jpiPlus ||
+			   v->type == jpiMinus ||
+			   v->type == jpiEqual ||
+			   v->type == jpiNotEqual ||
+			   v->type == jpiGreater ||
+			   v->type == jpiGreaterOrEqual ||
+			   v->type == jpiLess ||
+			   v->type == jpiLessOrEqual ||
+			   v->type == jpiAnd ||
+			   v->type == jpiOr ||
+			   v->type == jpiNot ||
+			   v->type == jpiIsUnknown ||
+			   v->type == jpiType ||
+			   v->type == jpiSize ||
+			   v->type == jpiAbs ||
+			   v->type == jpiFloor ||
+			   v->type == jpiCeiling ||
+			   v->type == jpiDouble ||
+			   v->type == jpiKeyValue ||
+			   v->type == jpiStartsWith);
+
+		if (a)
+			jspInitByBuffer(a, v->base, v->nextPos);
+		return true;
+	}
+
+	return false;
+}
+
+void
+jspGetLeftArg(JsonPathItem *v, JsonPathItem *a)
+{
+	Assert(v->type == jpiAnd ||
+		   v->type == jpiOr ||
+		   v->type == jpiEqual ||
+		   v->type == jpiNotEqual ||
+		   v->type == jpiLess ||
+		   v->type == jpiGreater ||
+		   v->type == jpiLessOrEqual ||
+		   v->type == jpiGreaterOrEqual ||
+		   v->type == jpiAdd ||
+		   v->type == jpiSub ||
+		   v->type == jpiMul ||
+		   v->type == jpiDiv ||
+		   v->type == jpiMod ||
+		   v->type == jpiStartsWith);
+
+	jspInitByBuffer(a, v->base, v->content.args.left);
+}
+
+void
+jspGetRightArg(JsonPathItem *v, JsonPathItem *a)
+{
+	Assert(v->type == jpiAnd ||
+		   v->type == jpiOr ||
+		   v->type == jpiEqual ||
+		   v->type == jpiNotEqual ||
+		   v->type == jpiLess ||
+		   v->type == jpiGreater ||
+		   v->type == jpiLessOrEqual ||
+		   v->type == jpiGreaterOrEqual ||
+		   v->type == jpiAdd ||
+		   v->type == jpiSub ||
+		   v->type == jpiMul ||
+		   v->type == jpiDiv ||
+		   v->type == jpiMod ||
+		   v->type == jpiStartsWith);
+
+	jspInitByBuffer(a, v->base, v->content.args.right);
+}
+
+bool
+jspGetBool(JsonPathItem *v)
+{
+	Assert(v->type == jpiBool);
+
+	return (bool) *v->content.value.data;
+}
+
+Numeric
+jspGetNumeric(JsonPathItem *v)
+{
+	Assert(v->type == jpiNumeric);
+
+	return (Numeric) v->content.value.data;
+}
+
+char *
+jspGetString(JsonPathItem *v, int32 *len)
+{
+	Assert(v->type == jpiKey ||
+		   v->type == jpiString ||
+		   v->type == jpiVariable);
+
+	if (len)
+		*len = v->content.value.datalen;
+	return v->content.value.data;
+}
+
+bool
+jspGetArraySubscript(JsonPathItem *v, JsonPathItem *from, JsonPathItem *to,
+					 int i)
+{
+	Assert(v->type == jpiIndexArray);
+
+	jspInitByBuffer(from, v->base, v->content.array.elems[i].from);
+
+	if (!v->content.array.elems[i].to)
+		return false;
+
+	jspInitByBuffer(to, v->base, v->content.array.elems[i].to);
+
+	return true;
+}
diff --git a/src/backend/utils/adt/jsonpath_exec.c b/src/backend/utils/adt/jsonpath_exec.c
new file mode 100644
index 0000000..87f432b
--- /dev/null
+++ b/src/backend/utils/adt/jsonpath_exec.c
@@ -0,0 +1,2273 @@
+/*-------------------------------------------------------------------------
+ *
+ * jsonpath_exec.c
+ *	 Routines for SQL/JSON path execution.
+ *
+ * Jsonpath is executed in the global context stored in JsonPathExecContext,
+ * which is passed to almost every function involved into execution.  Entry
+ * point for jsonpath execution is executeJsonPath() function, which
+ * initializes execution context including initial JsonPathItem and JsonbValue,
+ * flags, stack for calculation of @ in filters.
+ *
+ * The result of jsonpath query execution is enum JsonPathExecResult and
+ * if succeeded sequence of JsonbValue, written to JsonValueList *found, which
+ * is passed through the jsonpath items.  When found == NULL, we're inside
+ * exists-query and we're interested only in whether result is empty.  In this
+ * case execution is stopped once first result item is found, and the only
+ * execution result is JsonPathExecResult.  The values of JsonPathExecResult
+ * are following:
+ * - jperOk			-- result sequence is not empty
+ * - jperNotFound	-- result sequence is empty
+ * - jperError		-- error occurred during execution
+ *
+ * Jsonpath is executed recursively (see recursiveExecute()) starting form the
+ * first path item (which in turn might be, for instance, an arithmetic
+ * expression evaluated separately).  On each step single JsonbValue obtained
+ * from previous path item is processed.  The result of processing is a
+ * sequence of JsonbValue (probably empty), which is passed to the next path
+ * item one by one.  When there is no next path item, then JsonbValue is added
+ * to the 'found' list.  When found == NULL, then execution functions just
+ * return jperOk (see recursiveExecuteNext()).
+ *
+ * Many of jsonpath operations require automatic unwrapping of arrays in lax
+ * mode.  So, if input value is array, then corresponding operation is
+ * processed not on array itself, but on all of its members one by one.
+ * recursiveExecuteUnwrap() function have 'unwrap' argument, which indicates
+ * whether unwrapping of array is needed.  When unwrap == true, each of array
+ * members is passed to recursiveExecuteUnwrap() again but with unwrap == false
+ * in order to evade subsequent array unwrapping.
+ *
+ * All boolean expressions (predicates) are evaluated by recursiveExecuteBool()
+ * function, which returns tri-state JsonPathBool.  When error is occurred
+ * during predicate execution, it returns jpbUnknown.  According to standard
+ * predicates can be only inside filters.  But we support their usage as
+ * jsonpath expression.  This helps us to implement @@ operator.  In this case
+ * resulting JsonPathBool is transformed into jsonb bool or null.
+ *
+ * Arithmetic and boolean expression are evaluated recursively from expression
+ * tree top down to the leaves.  Therefore, for binary arithmetic expressions
+ * we calculate operands first.  Then we check that results are numeric
+ * singleton lists, calculate the result and pass it to the next path item.
+ *
+ * Copyright (c) 2019, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ *	src/backend/utils/adt/jsonpath_exec.c
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#include "postgres.h"
+
+#include "catalog/pg_collation.h"
+#include "catalog/pg_type.h"
+#include "funcapi.h"
+#include "lib/stringinfo.h"
+#include "miscadmin.h"
+#include "regex/regex.h"
+#include "utils/builtins.h"
+#include "utils/datum.h"
+#include "utils/formatting.h"
+#include "utils/float.h"
+#include "utils/guc.h"
+#include "utils/json.h"
+#include "utils/jsonpath.h"
+#include "utils/date.h"
+#include "utils/timestamp.h"
+#include "utils/varlena.h"
+
+
+/* Standard error message for SQL/JSON errors */
+#define ERRMSG_JSON_ARRAY_NOT_FOUND			"SQL/JSON array not found"
+#define ERRMSG_JSON_OBJECT_NOT_FOUND		"SQL/JSON object not found"
+#define ERRMSG_JSON_MEMBER_NOT_FOUND		"SQL/JSON member not found"
+#define ERRMSG_JSON_NUMBER_NOT_FOUND		"SQL/JSON number not found"
+#define ERRMSG_JSON_SCALAR_REQUIRED			"SQL/JSON scalar required"
+#define ERRMSG_SINGLETON_JSON_ITEM_REQUIRED	"singleton SQL/JSON item required"
+#define ERRMSG_NON_NUMERIC_JSON_ITEM		"non-numeric SQL/JSON item"
+#define ERRMSG_INVALID_JSON_SUBSCRIPT		"invalid SQL/JSON subscript"
+
+/*
+ * Represents "base object" and it's "id" for .keyvalue() evaluation.
+ */
+typedef struct JsonBaseObjectInfo
+{
+	JsonbContainer *jbc;
+	int			id;
+} JsonBaseObjectInfo;
+
+/*
+ * Context of jsonpath execution.
+ */
+typedef struct JsonPathExecContext
+{
+	Jsonb	   *vars;			/* variables to substitute into jsonpath */
+	JsonbValue *root;			/* for $ evaluation */
+	JsonbValue *current;		/* for @ evaluation */
+	JsonBaseObjectInfo baseObject;	/* "base object" for .keyvalue()
+									 * evaluation */
+	int			lastGeneratedObjectId;	/* "id" counter for .keyvalue()
+										 * evaluation */
+	int			innermostArraySize; /* for LAST array index evaluation */
+	bool		laxMode;		/* true for "lax" mode, false for "strict"
+								 * mode */
+	bool		ignoreStructuralErrors; /* with "true" structural errors such
+										 * as absence of required json item or
+										 * unexpected json item type are
+										 * ignored */
+	bool		throwErrors;	/* with "false" all suppressible errors are
+								 * suppressed */
+} JsonPathExecContext;
+
+/* Context for LIKE_REGEX execution. */
+typedef struct JsonLikeRegexContext
+{
+	text	   *regex;
+	int			cflags;
+} JsonLikeRegexContext;
+
+/* Result of jsonpath predicate evaluation */
+typedef enum JsonPathBool
+{
+	jpbFalse = 0,
+	jpbTrue = 1,
+	jpbUnknown = 2
+} JsonPathBool;
+
+/* Result of jsonpath expression evaluation */
+typedef enum JsonPathExecResult
+{
+	jperOk = 0,
+	jperNotFound = 1,
+	jperError = 2
+} JsonPathExecResult;
+
+#define jperIsError(jper)			((jper) == jperError)
+
+/*
+ * List of jsonb values with shortcut for single-value list.
+ */
+typedef struct JsonValueList
+{
+	JsonbValue *singleton;
+	List	   *list;
+} JsonValueList;
+
+typedef struct JsonValueListIterator
+{
+	JsonbValue *value;
+	ListCell   *next;
+} JsonValueListIterator;
+
+/* strict/lax flags is decomposed into four [un]wrap/error flags */
+#define jspStrictAbsenseOfErrors(cxt)	(!(cxt)->laxMode)
+#define jspAutoUnwrap(cxt)				((cxt)->laxMode)
+#define jspAutoWrap(cxt)				((cxt)->laxMode)
+#define jspIgnoreStructuralErrors(cxt)	((cxt)->ignoreStructuralErrors)
+#define jspThrowErrors(cxt)				((cxt)->throwErrors)
+
+#define RETURN_ERROR(error) \
+do { \
+	if (jspThrowErrors(cxt)) \
+		error; \
+	else \
+		return jperError; \
+} while (0)
+
+typedef JsonPathBool (*JsonPathPredicateCallback) (JsonPathItem *jsp,
+												   JsonbValue *larg,
+												   JsonbValue *rarg,
+												   void *param);
+
+static JsonPathExecResult executeJsonPath(JsonPath *path, Jsonb *vars,
+				Jsonb *json, bool throwErrors, JsonValueList *result);
+static JsonPathExecResult recursiveExecute(JsonPathExecContext *cxt,
+				 JsonPathItem *jsp, JsonbValue *jb, JsonValueList *found);
+static JsonPathExecResult recursiveExecuteUnwrap(JsonPathExecContext *cxt,
+					   JsonPathItem *jsp, JsonbValue *jb, bool unwrap, JsonValueList *found);
+static JsonPathExecResult recursiveExecuteUnwrapArray(JsonPathExecContext *cxt,
+							JsonPathItem *jsp, JsonbValue *jb,
+							JsonValueList *found, bool unwrapElements);
+static JsonPathExecResult recursiveExecuteNext(JsonPathExecContext *cxt,
+					 JsonPathItem *cur, JsonPathItem *next,
+					 JsonbValue *v, JsonValueList *found, bool copy);
+static JsonPathExecResult recursiveExecuteAndUnwrap(JsonPathExecContext *cxt,
+						  JsonPathItem *jsp, JsonbValue *jb, bool unwrap, JsonValueList *found);
+static JsonPathExecResult recursiveExecuteAndUnwrapNoThrow(
+								 JsonPathExecContext *cxt, JsonPathItem *jsp,
+								 JsonbValue *jb, bool unwrap, JsonValueList *found);
+static JsonPathBool recursiveExecuteBool(JsonPathExecContext *cxt,
+					 JsonPathItem *jsp, JsonbValue *jb, bool canHaveNext);
+static JsonPathBool recursiveExecuteBoolNested(JsonPathExecContext *cxt,
+						   JsonPathItem *jsp, JsonbValue *jb);
+static JsonPathExecResult recursiveAny(JsonPathExecContext *cxt,
+			 JsonPathItem *jsp, JsonbContainer *jbc, JsonValueList *found,
+			 uint32 level, uint32 first, uint32 last,
+			 bool ignoreStructuralErrors, bool unwrapNext);
+static JsonPathBool executePredicate(JsonPathExecContext *cxt,
+				 JsonPathItem *pred, JsonPathItem *larg, JsonPathItem *rarg,
+				 JsonbValue *jb, bool unwrapRightArg,
+				 JsonPathPredicateCallback exec, void *param);
+static JsonPathExecResult executeBinaryArithmExpr(JsonPathExecContext *cxt,
+						JsonPathItem *jsp, JsonbValue *jb, PGFunction func,
+						JsonValueList *found);
+static JsonPathExecResult executeUnaryArithmExpr(JsonPathExecContext *cxt,
+					   JsonPathItem *jsp, JsonbValue *jb, PGFunction func,
+					   JsonValueList *found);
+static JsonPathBool executeStartsWith(JsonPathItem *jsp,
+				  JsonbValue *whole, JsonbValue *initial, void *param);
+static JsonPathBool executeLikeRegex(JsonPathItem *jsp, JsonbValue *str,
+				 JsonbValue *rarg, void *param);
+static JsonPathExecResult executeNumericItemMethod(JsonPathExecContext *cxt,
+						 JsonPathItem *jsp, JsonbValue *jb, bool unwrap, PGFunction func,
+						 JsonValueList *found);
+static JsonPathExecResult executeKeyValueMethod(JsonPathExecContext *cxt,
+					  JsonPathItem *jsp, JsonbValue *jb, JsonValueList *found);
+static JsonPathExecResult appendBoolResult(JsonPathExecContext *cxt,
+				 JsonPathItem *jsp, JsonValueList *found, JsonPathBool res);
+static void getJsonPathItem(JsonPathExecContext *cxt, JsonPathItem *item,
+				JsonbValue *value);
+static void getJsonPathVariable(JsonPathExecContext *cxt,
+					JsonPathItem *variable, Jsonb *vars, JsonbValue *value);
+static int	JsonbArraySize(JsonbValue *jb);
+static JsonPathBool executeComparison(JsonPathItem *cmp, JsonbValue *lv,
+				  JsonbValue *rv, void *p);
+static JsonPathBool compareItems(int32 op, JsonbValue *jb1, JsonbValue *jb2);
+static int	compareNumeric(Numeric a, Numeric b);
+static JsonbValue *copyJsonbValue(JsonbValue *src);
+static JsonPathExecResult getArrayIndex(JsonPathExecContext *cxt,
+			  JsonPathItem *jsp, JsonbValue *jb, int32 *index);
+static JsonBaseObjectInfo setBaseObject(JsonPathExecContext *cxt,
+			  JsonbValue *jbv, int32 id);
+static void JsonValueListAppend(JsonValueList *jvl, JsonbValue *jbv);
+static int	JsonValueListLength(const JsonValueList *jvl);
+static bool JsonValueListIsEmpty(JsonValueList *jvl);
+static JsonbValue *JsonValueListHead(JsonValueList *jvl);
+static List *JsonValueListGetList(JsonValueList *jvl);
+static void JsonValueListInitIterator(const JsonValueList *jvl,
+						  JsonValueListIterator *it);
+static JsonbValue *JsonValueListNext(const JsonValueList *jvl,
+				  JsonValueListIterator *it);
+static int	JsonbType(JsonbValue *jb);
+static JsonbValue *JsonbInitBinary(JsonbValue *jbv, Jsonb *jb);
+static int	JsonbType(JsonbValue *jb);
+static JsonbValue *getScalar(JsonbValue *scalar, enum jbvType type);
+static JsonbValue *wrapItemsInArray(const JsonValueList *items);
+
+/****************** User interface to JsonPath executor ********************/
+
+/*
+ * jsonb_path_exists
+ *		Returns true if jsonpath returns at least one item for the specified
+ *		jsonb value.  This function and jsonb_path_match() are used to
+ *		implement @? and @@ operators, which in turn are intended to have an
+ *		index support.  Thus, it's desirable to make it easier to achieve
+ *		consistency between index scan results and sequential scan results.
+ *		So, we throw as less errors as possible.  Regarding this function,
+ *		such behavior also matches behavior of JSON_EXISTS() clause of
+ *		SQL/JSON.  Regarding jsonb_path_match(), this function doesn't have
+ *		an analogy in SQL/JSON, so we define its behavior on our own.
+ */
+Datum
+jsonb_path_exists(PG_FUNCTION_ARGS)
+{
+	Jsonb	   *jb = PG_GETARG_JSONB_P(0);
+	JsonPath   *jp = PG_GETARG_JSONPATH_P(1);
+	JsonPathExecResult res;
+	Jsonb	   *vars = NULL;
+	bool		silent = true;
+
+	if (PG_NARGS() == 4)
+	{
+		vars = PG_GETARG_JSONB_P(2);
+		silent = !PG_GETARG_BOOL(3);
+	}
+
+	res = executeJsonPath(jp, vars, jb, !silent, NULL);
+
+	PG_FREE_IF_COPY(jb, 0);
+	PG_FREE_IF_COPY(jp, 1);
+
+	if (jperIsError(res))
+		PG_RETURN_NULL();
+
+	PG_RETURN_BOOL(res == jperOk);
+}
+
+/*
+ * jsonb_path_exists_novars
+ *		Implements the 2-argument version of jsonb_path_exists
+ */
+Datum
+jsonb_path_exists_opr(PG_FUNCTION_ARGS)
+{
+	/* just call the other one -- it can handle both cases */
+	return jsonb_path_exists(fcinfo);
+}
+
+/*
+ * jsonb_path_match
+ *		Returns jsonpath predicate result item for the specified jsonb value.
+ *		See jsonb_path_exists() comment for details regarding error handling.
+ */
+Datum
+jsonb_path_match(PG_FUNCTION_ARGS)
+{
+	Jsonb	   *jb = PG_GETARG_JSONB_P(0);
+	JsonPath   *jp = PG_GETARG_JSONPATH_P(1);
+	JsonbValue *jbv;
+	JsonValueList found = {0};
+	Jsonb	   *vars = NULL;
+	bool		silent = true;
+
+	if (PG_NARGS() == 4)
+	{
+		vars = PG_GETARG_JSONB_P(2);
+		silent = !PG_GETARG_BOOL(3);
+	}
+
+	(void) executeJsonPath(jp, vars, jb, !silent, &found);
+
+	if (JsonValueListLength(&found) < 1)
+		PG_RETURN_NULL();
+
+	jbv = JsonValueListHead(&found);
+
+	PG_FREE_IF_COPY(jb, 0);
+	PG_FREE_IF_COPY(jp, 1);
+
+	if (jbv->type != jbvBool)
+		PG_RETURN_NULL();
+
+	PG_RETURN_BOOL(jbv->val.boolean);
+}
+
+/*
+ * jsonb_path_match_novars
+ *		Implements the 2-argument version of jsonb_path_match
+ */
+Datum
+jsonb_path_match_opr(PG_FUNCTION_ARGS)
+{
+	/* just call the other one -- it can handle both cases */
+	return jsonb_path_match(fcinfo);
+}
+
+/*
+ * jsonb_path_query
+ *		Executes jsonpath for given jsonb document and returns result as
+ *		rowset.
+ */
+Datum
+jsonb_path_query(PG_FUNCTION_ARGS)
+{
+	FuncCallContext *funcctx;
+	List	   *found;
+	JsonbValue *v;
+	ListCell   *c;
+
+	if (SRF_IS_FIRSTCALL())
+	{
+		JsonPath   *jp;
+		Jsonb	   *jb;
+		MemoryContext oldcontext;
+		Jsonb	   *vars;
+		bool		silent;
+		JsonValueList found = {0};
+
+		funcctx = SRF_FIRSTCALL_INIT();
+		oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
+
+		jb = PG_GETARG_JSONB_P_COPY(0);
+		jp = PG_GETARG_JSONPATH_P_COPY(1);
+		vars = PG_GETARG_JSONB_P_COPY(2);
+		silent = PG_GETARG_BOOL(3);
+
+		(void) executeJsonPath(jp, vars, jb, !silent, &found);
+
+		funcctx->user_fctx = JsonValueListGetList(&found);
+
+		MemoryContextSwitchTo(oldcontext);
+	}
+
+	funcctx = SRF_PERCALL_SETUP();
+	found = funcctx->user_fctx;
+
+	c = list_head(found);
+
+	if (c == NULL)
+		SRF_RETURN_DONE(funcctx);
+
+	v = lfirst(c);
+	funcctx->user_fctx = list_delete_first(found);
+
+	SRF_RETURN_NEXT(funcctx, JsonbPGetDatum(JsonbValueToJsonb(v)));
+}
+
+/*
+ * jsonb_path_query_array
+ *		Executes jsonpath for given jsonb document and returns result as
+ *		jsonb array.
+ */
+Datum
+jsonb_path_query_array(FunctionCallInfo fcinfo)
+{
+	Jsonb	   *jb = PG_GETARG_JSONB_P(0);
+	JsonPath   *jp = PG_GETARG_JSONPATH_P(1);
+	JsonValueList found = {0};
+	Jsonb	   *vars = PG_GETARG_JSONB_P(2);
+	bool		silent = PG_GETARG_BOOL(3);
+
+	(void) executeJsonPath(jp, vars, jb, !silent, &found);
+
+	PG_RETURN_JSONB_P(JsonbValueToJsonb(wrapItemsInArray(&found)));
+}
+
+/*
+ * jsonb_path_query_first
+ *		Executes jsonpath for given jsonb document and returns first result
+ *		item.  If there are no items, NULL returned.
+ */
+Datum
+jsonb_path_query_first(FunctionCallInfo fcinfo)
+{
+	Jsonb	   *jb = PG_GETARG_JSONB_P(0);
+	JsonPath   *jp = PG_GETARG_JSONPATH_P(1);
+	JsonValueList found = {0};
+	Jsonb	   *vars = PG_GETARG_JSONB_P(2);
+	bool		silent = PG_GETARG_BOOL(3);
+
+	(void) executeJsonPath(jp, vars, jb, !silent, &found);
+
+	if (JsonValueListLength(&found) >= 1)
+		PG_RETURN_JSONB_P(JsonbValueToJsonb(JsonValueListHead(&found)));
+	else
+		PG_RETURN_NULL();
+}
+
+/********************Execute functions for JsonPath**************************/
+
+/*
+ * Interface to jsonpath executor
+ *
+ * 'path' - jsonpath to be executed
+ * 'vars' - variables to be substituted to jsonpath
+ * 'json' - target document for jsonpath evaluation
+ * 'throwErrors' - whether we should throw suppressible errors
+ * 'result' - list to store result items into
+ *
+ * Returns an error happens during processing or NULL on no error.
+ *
+ * Note, jsonb and jsonpath values should be avaliable and untoasted during
+ * work because JsonPathItem, JsonbValue and result item could have pointers
+ * into input values.  If caller needs to just check if document matches
+ * jsonpath, then it doesn't provide a result arg.  In this case executor
+ * works till first positive result and does not check the rest if possible.
+ * In other case it tries to find all the satisfied result items.
+ */
+static JsonPathExecResult
+executeJsonPath(JsonPath *path, Jsonb *vars, Jsonb *json, bool throwErrors,
+				JsonValueList *result)
+{
+	JsonPathExecContext cxt;
+	JsonPathExecResult res;
+	JsonPathItem jsp;
+	JsonbValue	jbv;
+
+	jspInit(&jsp, path);
+
+	if (!JsonbExtractScalar(&json->root, &jbv))
+		JsonbInitBinary(&jbv, json);
+
+	if (vars && !JsonContainerIsObject(&vars->root))
+	{
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+				 errmsg("jsonb containing jsonpath variables "
+						"is not an object")));
+	}
+
+	cxt.vars = vars;
+	cxt.laxMode = (path->header & JSONPATH_LAX) != 0;
+	cxt.ignoreStructuralErrors = cxt.laxMode;
+	cxt.root = &jbv;
+	cxt.current = &jbv;
+	cxt.baseObject.jbc = NULL;
+	cxt.baseObject.id = 0;
+	cxt.lastGeneratedObjectId = vars ? 2 : 1;
+	cxt.innermostArraySize = -1;
+	cxt.throwErrors = throwErrors;
+
+	if (jspStrictAbsenseOfErrors(&cxt) && !result)
+	{
+		/*
+		 * In strict mode we must get a complete list of values to check that
+		 * there are no errors at all.
+		 */
+		JsonValueList vals = {0};
+
+		Assert(!throwErrors);
+
+		res = recursiveExecute(&cxt, &jsp, &jbv, &vals);
+
+		if (jperIsError(res))
+			return res;
+
+		return JsonValueListIsEmpty(&vals) ? jperNotFound : jperOk;
+	}
+
+	res = recursiveExecute(&cxt, &jsp, &jbv, result);
+
+	Assert(!throwErrors || !jperIsError(res));
+
+	return res;
+}
+
+/*
+ * Execute jsonpath with automatic unwrapping of current item in lax mode.
+ */
+static JsonPathExecResult
+recursiveExecute(JsonPathExecContext *cxt, JsonPathItem *jsp,
+				 JsonbValue *jb, JsonValueList *found)
+{
+	return recursiveExecuteUnwrap(cxt, jsp, jb, jspAutoUnwrap(cxt), found);
+}
+
+/*
+ * Main jsonpath executor function: walks on jsonpath structure, finds
+ * relevant parts of jsonb and evaluates expressions over them.
+ * When 'unwrap' is true current SQL/JSON item is unwrapped if it is an array.
+ */
+static JsonPathExecResult
+recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
+					   JsonbValue *jb, bool unwrap, JsonValueList *found)
+{
+	JsonPathItem elem;
+	JsonPathExecResult res = jperNotFound;
+	JsonBaseObjectInfo baseObject;
+
+	check_stack_depth();
+	CHECK_FOR_INTERRUPTS();
+
+	switch (jsp->type)
+	{
+			/* all boolean item types: */
+		case jpiAnd:
+		case jpiOr:
+		case jpiNot:
+		case jpiIsUnknown:
+		case jpiEqual:
+		case jpiNotEqual:
+		case jpiLess:
+		case jpiGreater:
+		case jpiLessOrEqual:
+		case jpiGreaterOrEqual:
+		case jpiExists:
+		case jpiStartsWith:
+		case jpiLikeRegex:
+			{
+				JsonPathBool st = recursiveExecuteBool(cxt, jsp, jb, true);
+
+				res = appendBoolResult(cxt, jsp, found, st);
+				break;
+			}
+
+		case jpiKey:
+			if (JsonbType(jb) == jbvObject)
+			{
+				JsonbValue *v;
+				JsonbValue	key;
+
+				key.type = jbvString;
+				key.val.string.val = jspGetString(jsp, &key.val.string.len);
+
+				v = findJsonbValueFromContainer(jb->val.binary.data,
+												JB_FOBJECT, &key);
+
+				if (v != NULL)
+				{
+					res = recursiveExecuteNext(cxt, jsp, NULL,
+											   v, found, false);
+
+					/* free value if it was not added to found list */
+					if (jspHasNext(jsp) || !found)
+						pfree(v);
+				}
+				else if (!jspIgnoreStructuralErrors(cxt))
+				{
+					StringInfoData keybuf;
+					char	   *keystr;
+
+					Assert(found);
+
+					if (!jspThrowErrors(cxt))
+						return jperError;
+
+					initStringInfo(&keybuf);
+
+					keystr = pnstrdup(key.val.string.val, key.val.string.len);
+					escape_json(&keybuf, keystr);
+
+					ereport(ERROR,
+							(errcode(ERRCODE_JSON_MEMBER_NOT_FOUND), \
+							 errmsg(ERRMSG_JSON_MEMBER_NOT_FOUND),
+							 errdetail("JSON object does not contain key %s",
+									   keybuf.data)));
+				}
+			}
+			else if (unwrap && JsonbType(jb) == jbvArray)
+				return recursiveExecuteUnwrapArray(cxt, jsp, jb, found, false);
+			else if (!jspIgnoreStructuralErrors(cxt))
+			{
+				Assert(found);
+				RETURN_ERROR(ereport(ERROR,
+									 (errcode(ERRCODE_JSON_MEMBER_NOT_FOUND),
+									  errmsg(ERRMSG_JSON_MEMBER_NOT_FOUND),
+									  errdetail("jsonpath member accessor is applied to "
+												"not an object"))));
+			}
+			break;
+
+		case jpiRoot:
+			jb = cxt->root;
+			baseObject = setBaseObject(cxt, jb, 0);
+			res = recursiveExecuteNext(cxt, jsp, NULL, jb, found, true);
+			cxt->baseObject = baseObject;
+			break;
+
+		case jpiCurrent:
+			res = recursiveExecuteNext(cxt, jsp, NULL, cxt->current,
+									   found, true);
+			break;
+
+		case jpiAnyArray:
+			if (JsonbType(jb) == jbvArray)
+			{
+				bool		hasNext = jspGetNext(jsp, &elem);
+
+				res = recursiveExecuteUnwrapArray(cxt, hasNext ? &elem : NULL,
+												  jb, found, jspAutoUnwrap(cxt));
+			}
+			else if (jspAutoWrap(cxt))
+				res = recursiveExecuteNext(cxt, jsp, NULL, jb, found, true);
+			else if (!jspIgnoreStructuralErrors(cxt))
+				RETURN_ERROR(ereport(ERROR,
+									 (errcode(ERRCODE_JSON_ARRAY_NOT_FOUND),
+									  errmsg(ERRMSG_JSON_ARRAY_NOT_FOUND),
+									  errdetail("jsonpath wildcard array accessor is "
+												"applied to not an array"))));
+			break;
+
+		case jpiIndexArray:
+			if (JsonbType(jb) == jbvArray || jspAutoWrap(cxt))
+			{
+				int			innermostArraySize = cxt->innermostArraySize;
+				int			i;
+				int			size = JsonbArraySize(jb);
+				bool		singleton = size < 0;
+				bool		hasNext = jspGetNext(jsp, &elem);
+
+				if (singleton)
+					size = 1;
+
+				cxt->innermostArraySize = size; /* for LAST evaluation */
+
+				for (i = 0; i < jsp->content.array.nelems; i++)
+				{
+					JsonPathItem from;
+					JsonPathItem to;
+					int32		index;
+					int32		index_from;
+					int32		index_to;
+					bool		range = jspGetArraySubscript(jsp, &from,
+															 &to, i);
+
+					res = getArrayIndex(cxt, &from, jb, &index_from);
+
+					if (jperIsError(res))
+						break;
+
+					if (range)
+					{
+						res = getArrayIndex(cxt, &to, jb, &index_to);
+
+						if (jperIsError(res))
+							break;
+					}
+					else
+						index_to = index_from;
+
+					if (!jspIgnoreStructuralErrors(cxt) &&
+						(index_from < 0 ||
+						 index_from > index_to ||
+						 index_to >= size))
+						RETURN_ERROR(ereport(ERROR,
+											 (errcode(ERRCODE_INVALID_JSON_SUBSCRIPT),
+											  errmsg(ERRMSG_INVALID_JSON_SUBSCRIPT),
+											  errdetail("jsonpath array subscript is "
+														"out of bounds"))));
+
+					if (index_from < 0)
+						index_from = 0;
+
+					if (index_to >= size)
+						index_to = size - 1;
+
+					res = jperNotFound;
+
+					for (index = index_from; index <= index_to; index++)
+					{
+						JsonbValue *v;
+						bool		copy;
+
+						if (singleton)
+						{
+							v = jb;
+							copy = true;
+						}
+						else
+						{
+							v = getIthJsonbValueFromContainer(jb->val.binary.data,
+															  (uint32) index);
+
+							if (v == NULL)
+								continue;
+
+							copy = false;
+						}
+
+						if (!hasNext && !found)
+							return jperOk;
+
+						res = recursiveExecuteNext(cxt, jsp, &elem, v, found,
+												   copy);
+
+						if (jperIsError(res))
+							break;
+
+						if (res == jperOk && !found)
+							break;
+					}
+
+					if (jperIsError(res))
+						break;
+
+					if (res == jperOk && !found)
+						break;
+				}
+
+				cxt->innermostArraySize = innermostArraySize;
+			}
+			else if (!jspIgnoreStructuralErrors(cxt))
+			{
+				RETURN_ERROR(ereport(ERROR,
+									 (errcode(ERRCODE_JSON_ARRAY_NOT_FOUND),
+									  errmsg(ERRMSG_JSON_ARRAY_NOT_FOUND),
+									  errdetail("jsonpath array accessor is applied to "
+												"not an array"))));
+			}
+			break;
+
+		case jpiLast:
+			{
+				JsonbValue	tmpjbv;
+				JsonbValue *lastjbv;
+				int			last;
+				bool		hasNext = jspGetNext(jsp, &elem);
+
+				if (cxt->innermostArraySize < 0)
+					elog(ERROR, "evaluating jsonpath LAST outside of "
+						 "array subscript");
+
+				if (!hasNext && !found)
+				{
+					res = jperOk;
+					break;
+				}
+
+				last = cxt->innermostArraySize - 1;
+
+				lastjbv = hasNext ? &tmpjbv : palloc(sizeof(*lastjbv));
+
+				lastjbv->type = jbvNumeric;
+				lastjbv->val.numeric =
+					DatumGetNumeric(DirectFunctionCall1(int4_numeric,
+														Int32GetDatum(last)));
+
+				res = recursiveExecuteNext(cxt, jsp, &elem,
+										   lastjbv, found, hasNext);
+			}
+			break;
+
+		case jpiAnyKey:
+			if (JsonbType(jb) == jbvObject)
+			{
+				bool		hasNext = jspGetNext(jsp, &elem);
+
+				if (jb->type != jbvBinary)
+					elog(ERROR, "invalid jsonb object type: %d", jb->type);
+
+				return recursiveAny(cxt, hasNext ? &elem : NULL,
+									jb->val.binary.data, found, 1, 1, 1,
+									false, jspAutoUnwrap(cxt));
+			}
+			else if (unwrap && JsonbType(jb) == jbvArray)
+				return recursiveExecuteUnwrapArray(cxt, jsp, jb, found, false);
+			else if (!jspIgnoreStructuralErrors(cxt))
+			{
+				Assert(found);
+				RETURN_ERROR(ereport(ERROR,
+									 (errcode(ERRCODE_JSON_OBJECT_NOT_FOUND),
+									  errmsg(ERRMSG_JSON_OBJECT_NOT_FOUND),
+									  errdetail("jsonpath wildcard member accessor is "
+												"applied to not an object"))));
+			}
+			break;
+
+		case jpiAdd:
+			return executeBinaryArithmExpr(cxt, jsp, jb,
+										   numeric_add, found);
+
+		case jpiSub:
+			return executeBinaryArithmExpr(cxt, jsp, jb,
+										   numeric_sub, found);
+
+		case jpiMul:
+			return executeBinaryArithmExpr(cxt, jsp, jb,
+										   numeric_mul, found);
+
+		case jpiDiv:
+			return executeBinaryArithmExpr(cxt, jsp, jb,
+										   numeric_div, found);
+
+		case jpiMod:
+			return executeBinaryArithmExpr(cxt, jsp, jb,
+										   numeric_mod, found);
+
+		case jpiPlus:
+			return executeUnaryArithmExpr(cxt, jsp, jb, NULL, found);
+
+		case jpiMinus:
+			return executeUnaryArithmExpr(cxt, jsp, jb, numeric_uminus,
+										  found);
+
+		case jpiFilter:
+			{
+				JsonPathBool st;
+
+				if (unwrap && JsonbType(jb) == jbvArray)
+					return recursiveExecuteUnwrapArray(cxt, jsp, jb, found,
+													   false);
+
+				jspGetArg(jsp, &elem);
+				st = recursiveExecuteBoolNested(cxt, &elem, jb);
+				if (st != jpbTrue)
+					res = jperNotFound;
+				else
+					res = recursiveExecuteNext(cxt, jsp, NULL,
+											   jb, found, true);
+				break;
+			}
+
+		case jpiAny:
+			{
+				bool		hasNext = jspGetNext(jsp, &elem);
+
+				/* first try without any intermediate steps */
+				if (jsp->content.anybounds.first == 0)
+				{
+					bool		savedIgnoreStructuralErrors;
+
+					savedIgnoreStructuralErrors = cxt->ignoreStructuralErrors;
+					cxt->ignoreStructuralErrors = true;
+					res = recursiveExecuteNext(cxt, jsp, &elem,
+											   jb, found, true);
+					cxt->ignoreStructuralErrors = savedIgnoreStructuralErrors;
+
+					if (res == jperOk && !found)
+						break;
+				}
+
+				if (jb->type == jbvBinary)
+					res = recursiveAny(cxt, hasNext ? &elem : NULL,
+									   jb->val.binary.data, found,
+									   1,
+									   jsp->content.anybounds.first,
+									   jsp->content.anybounds.last,
+									   true, jspAutoUnwrap(cxt));
+				break;
+			}
+
+		case jpiNull:
+		case jpiBool:
+		case jpiNumeric:
+		case jpiString:
+		case jpiVariable:
+			{
+				JsonbValue	vbuf;
+				JsonbValue *v;
+				bool		hasNext = jspGetNext(jsp, &elem);
+
+				if (!hasNext && !found)
+				{
+					res = jperOk;	/* skip evaluation */
+					break;
+				}
+
+				v = hasNext ? &vbuf : palloc(sizeof(*v));
+
+				baseObject = cxt->baseObject;
+				getJsonPathItem(cxt, jsp, v);
+
+				res = recursiveExecuteNext(cxt, jsp, &elem,
+										   v, found, hasNext);
+				cxt->baseObject = baseObject;
+			}
+			break;
+
+		case jpiType:
+			{
+				JsonbValue *jbv = palloc(sizeof(*jbv));
+
+				jbv->type = jbvString;
+				jbv->val.string.val = pstrdup(JsonbTypeName(jb));
+				jbv->val.string.len = strlen(jbv->val.string.val);
+
+				res = recursiveExecuteNext(cxt, jsp, NULL, jbv,
+										   found, false);
+			}
+			break;
+
+		case jpiSize:
+			{
+				int			size = JsonbArraySize(jb);
+
+				if (size < 0)
+				{
+					if (!jspAutoWrap(cxt))
+					{
+						if (!jspIgnoreStructuralErrors(cxt))
+							RETURN_ERROR(ereport(ERROR,
+												 (errcode(ERRCODE_JSON_ARRAY_NOT_FOUND),
+												  errmsg(ERRMSG_JSON_ARRAY_NOT_FOUND),
+												  errdetail("jsonpath item method .%s() "
+															"is applied to not an array",
+															jspOperationName(jsp->type)))));
+						break;
+					}
+
+					size = 1;
+				}
+
+				jb = palloc(sizeof(*jb));
+
+				jb->type = jbvNumeric;
+				jb->val.numeric =
+					DatumGetNumeric(DirectFunctionCall1(int4_numeric,
+														Int32GetDatum(size)));
+
+				res = recursiveExecuteNext(cxt, jsp, NULL, jb, found, false);
+			}
+			break;
+
+		case jpiAbs:
+			return executeNumericItemMethod(cxt, jsp, jb, unwrap, numeric_abs,
+											found);
+
+		case jpiFloor:
+			return executeNumericItemMethod(cxt, jsp, jb, unwrap, numeric_floor,
+											found);
+
+		case jpiCeiling:
+			return executeNumericItemMethod(cxt, jsp, jb, unwrap, numeric_ceil,
+											found);
+
+		case jpiDouble:
+			{
+				JsonbValue	jbv;
+
+				if (unwrap && JsonbType(jb) == jbvArray)
+					return recursiveExecuteUnwrapArray(cxt, jsp, jb, found,
+													   false);
+
+				if (jb->type == jbvNumeric)
+				{
+					char	   *tmp = DatumGetCString(DirectFunctionCall1(numeric_out,
+																		  NumericGetDatum(jb->val.numeric)));
+
+					(void) float8in_internal(tmp,
+											 NULL,
+											 "double precision",
+											 tmp);
+
+					res = jperOk;
+				}
+				else if (jb->type == jbvString)
+				{
+					/* cast string as double */
+					double		val;
+					char	   *tmp = pnstrdup(jb->val.string.val,
+											   jb->val.string.len);
+
+					val = float8in_internal(tmp,
+											NULL,
+											"double precision",
+											tmp);
+
+					if (isinf(val))
+						RETURN_ERROR(ereport(ERROR,
+											 (errcode(ERRCODE_NON_NUMERIC_JSON_ITEM),
+											  errmsg(ERRMSG_NON_NUMERIC_JSON_ITEM),
+											  errdetail("jsonpath item method .%s() is "
+														"applied to not a numeric value",
+														jspOperationName(jsp->type)))));
+
+					jb = &jbv;
+					jb->type = jbvNumeric;
+					jb->val.numeric = DatumGetNumeric(DirectFunctionCall1(float8_numeric,
+																		  Float8GetDatum(val)));
+					res = jperOk;
+				}
+
+				if (res == jperNotFound)
+					RETURN_ERROR(ereport(ERROR,
+										 (errcode(ERRCODE_NON_NUMERIC_JSON_ITEM),
+										  errmsg(ERRMSG_NON_NUMERIC_JSON_ITEM),
+										  errdetail("jsonpath item method .%s() is "
+													"applied to neither a string nor "
+													"numeric value",
+													jspOperationName(jsp->type)))));
+
+				res = recursiveExecuteNext(cxt, jsp, NULL, jb, found, true);
+			}
+			break;
+
+		case jpiKeyValue:
+			if (unwrap && JsonbType(jb) == jbvArray)
+				return recursiveExecuteUnwrapArray(cxt, jsp, jb, found, false);
+
+			return executeKeyValueMethod(cxt, jsp, jb, found);
+
+		default:
+			elog(ERROR, "unrecognized jsonpath item type: %d", jsp->type);
+	}
+
+	return res;
+}
+
+/*
+ * Unwrap current array item and execute jsonpath for each of its elements.
+ */
+static JsonPathExecResult
+recursiveExecuteUnwrapArray(JsonPathExecContext *cxt, JsonPathItem *jsp,
+							JsonbValue *jb, JsonValueList *found,
+							bool unwrapElements)
+{
+	if (jb->type != jbvBinary)
+	{
+		Assert(jb->type != jbvArray);
+		elog(ERROR, "invalid jsonb array value type: %d", jb->type);
+	}
+
+	return recursiveAny(cxt, jsp, jb->val.binary.data, found, 1, 1, 1,
+						false, unwrapElements);
+}
+
+/*
+ * Execute next jsonpath item if exists.
+ */
+static JsonPathExecResult
+recursiveExecuteNext(JsonPathExecContext *cxt,
+					 JsonPathItem *cur, JsonPathItem *next,
+					 JsonbValue *v, JsonValueList *found, bool copy)
+{
+	JsonPathItem elem;
+	bool		hasNext;
+
+	if (!cur)
+		hasNext = next != NULL;
+	else if (next)
+		hasNext = jspHasNext(cur);
+	else
+	{
+		next = &elem;
+		hasNext = jspGetNext(cur, next);
+	}
+
+	if (hasNext)
+		return recursiveExecute(cxt, next, v, found);
+
+	if (found)
+		JsonValueListAppend(found, copy ? copyJsonbValue(v) : v);
+
+	return jperOk;
+}
+
+/*
+ * Execute jsonpath expression and automatically unwrap each array item from
+ * the resulting sequence in lax mode.
+ */
+static JsonPathExecResult
+recursiveExecuteAndUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
+						  JsonbValue *jb, bool unwrap, JsonValueList *found)
+{
+	if (unwrap && jspAutoUnwrap(cxt))
+	{
+		JsonValueList seq = {0};
+		JsonValueListIterator it;
+		JsonPathExecResult res = recursiveExecute(cxt, jsp, jb, &seq);
+		JsonbValue *item;
+
+		if (jperIsError(res))
+			return res;
+
+		JsonValueListInitIterator(&seq, &it);
+		while ((item = JsonValueListNext(&seq, &it)))
+		{
+			Assert(item->type != jbvArray);
+
+			if (JsonbType(item) == jbvArray)
+				recursiveExecuteUnwrapArray(cxt, NULL, item, found, false);
+			else
+				JsonValueListAppend(found, item);
+		}
+
+		return jperOk;
+	}
+
+	return recursiveExecute(cxt, jsp, jb, found);
+}
+
+static JsonPathExecResult
+recursiveExecuteAndUnwrapNoThrow(JsonPathExecContext *cxt, JsonPathItem *jsp,
+								 JsonbValue *jb, bool unwrap,
+								 JsonValueList *found)
+{
+	JsonPathExecResult res;
+	bool		throwErrors = cxt->throwErrors;
+
+	cxt->throwErrors = false;
+	res = recursiveExecuteAndUnwrap(cxt, jsp, jb, unwrap, found);
+	cxt->throwErrors = throwErrors;
+
+	return res;
+}
+
+/* Execute boolean-valued jsonpath expression. */
+static JsonPathBool
+recursiveExecuteBool(JsonPathExecContext *cxt, JsonPathItem *jsp,
+					 JsonbValue *jb, bool canHaveNext)
+{
+	JsonPathItem larg;
+	JsonPathItem rarg;
+	JsonPathBool res;
+	JsonPathBool res2;
+
+	if (!canHaveNext && jspHasNext(jsp))
+		elog(ERROR, "boolean jsonpath item cannot have next item");
+
+	switch (jsp->type)
+	{
+		case jpiAnd:
+			jspGetLeftArg(jsp, &larg);
+			res = recursiveExecuteBool(cxt, &larg, jb, false);
+
+			if (res == jpbFalse)
+				return jpbFalse;
+
+			/*
+			 * SQL/JSON says that we should check second arg in case of
+			 * jperError
+			 */
+
+			jspGetRightArg(jsp, &rarg);
+			res2 = recursiveExecuteBool(cxt, &rarg, jb, false);
+
+			return res2 == jpbTrue ? res : res2;
+
+		case jpiOr:
+			jspGetLeftArg(jsp, &larg);
+			res = recursiveExecuteBool(cxt, &larg, jb, false);
+
+			if (res == jpbTrue)
+				return jpbTrue;
+
+			jspGetRightArg(jsp, &rarg);
+			res2 = recursiveExecuteBool(cxt, &rarg, jb, false);
+
+			return res2 == jpbFalse ? res : res2;
+
+		case jpiNot:
+			jspGetArg(jsp, &larg);
+
+			res = recursiveExecuteBool(cxt, &larg, jb, false);
+
+			if (res == jpbUnknown)
+				return jpbUnknown;
+
+			return res == jpbTrue ? jpbFalse : jpbTrue;
+
+		case jpiIsUnknown:
+			jspGetArg(jsp, &larg);
+			res = recursiveExecuteBool(cxt, &larg, jb, false);
+			return res == jpbUnknown ? jpbTrue : jpbFalse;
+
+		case jpiEqual:
+		case jpiNotEqual:
+		case jpiLess:
+		case jpiGreater:
+		case jpiLessOrEqual:
+		case jpiGreaterOrEqual:
+			jspGetLeftArg(jsp, &larg);
+			jspGetRightArg(jsp, &rarg);
+			return executePredicate(cxt, jsp, &larg, &rarg, jb, true,
+									executeComparison, NULL);
+
+		case jpiStartsWith:		/* 'whole STARTS WITH initial' */
+			jspGetLeftArg(jsp, &larg);	/* 'whole' */
+			jspGetRightArg(jsp, &rarg); /* 'initial' */
+			return executePredicate(cxt, jsp, &larg, &rarg, jb, false,
+									executeStartsWith, NULL);
+
+		case jpiLikeRegex:		/* 'expr LIKE_REGEX pattern FLAGS flags' */
+			{
+				/*
+				 * 'expr' is a sequence-returning expression.  'pattern' is a
+				 * regex string literal.  SQL/JSON standard requires XQuery
+				 * regexes, but we use Postgres regexes here.  'flags' is a
+				 * string literal converted to integer flags at compile-time.
+				 */
+				JsonLikeRegexContext lrcxt = {0};
+
+				jspInitByBuffer(&larg, jsp->base,
+								jsp->content.like_regex.expr);
+
+				return executePredicate(cxt, jsp, &larg, NULL, jb, false,
+										executeLikeRegex, &lrcxt);
+			}
+
+		case jpiExists:
+			jspGetArg(jsp, &larg);
+
+			if (jspStrictAbsenseOfErrors(cxt))
+			{
+				/*
+				 * In strict mode we must get a complete list of values to
+				 * check that there are no errors at all.
+				 */
+				JsonValueList vals = {0};
+				JsonPathExecResult res =
+				recursiveExecuteAndUnwrapNoThrow(cxt, &larg, jb, false, &vals);
+
+				if (jperIsError(res))
+					return jpbUnknown;
+
+				return JsonValueListIsEmpty(&vals) ? jpbFalse : jpbTrue;
+			}
+			else
+			{
+				JsonPathExecResult res =
+				recursiveExecuteAndUnwrapNoThrow(cxt, &larg, jb, false, NULL);
+
+				if (jperIsError(res))
+					return jpbUnknown;
+
+				return res == jperOk ? jpbTrue : jpbFalse;
+			}
+
+		default:
+			elog(ERROR, "invalid boolean jsonpath item type: %d", jsp->type);
+			return jpbUnknown;
+	}
+}
+
+/*
+ * Execute nested (filters etc.) boolean expression pushing current SQL/JSON
+ * item onto the stack.
+ */
+static JsonPathBool
+recursiveExecuteBoolNested(JsonPathExecContext *cxt, JsonPathItem *jsp,
+						   JsonbValue *jb)
+{
+	JsonbValue *prev;
+	JsonPathBool res;
+
+	prev = cxt->current;
+	cxt->current = jb;
+	res = recursiveExecuteBool(cxt, jsp, jb, false);
+	cxt->current = prev;
+
+	return res;
+}
+
+/*
+ * Implementation of several jsonpath nodes:
+ *  - jpiAny (.** accessor),
+ *  - jpiAnyKey (.* accessor),
+ *  - jpiAnyArray ([*] accessor)
+ */
+static JsonPathExecResult
+recursiveAny(JsonPathExecContext *cxt, JsonPathItem *jsp, JsonbContainer *jbc,
+			 JsonValueList *found, uint32 level, uint32 first, uint32 last,
+			 bool ignoreStructuralErrors, bool unwrapNext)
+{
+	JsonPathExecResult res = jperNotFound;
+	JsonbIterator *it;
+	int32		r;
+	JsonbValue	v;
+
+	check_stack_depth();
+
+	if (level > last)
+		return res;
+
+	it = JsonbIteratorInit(jbc);
+
+	/*
+	 * Recursively iterate over jsonb objects/arrays
+	 */
+	while ((r = JsonbIteratorNext(&it, &v, true)) != WJB_DONE)
+	{
+		if (r == WJB_KEY)
+		{
+			r = JsonbIteratorNext(&it, &v, true);
+			Assert(r == WJB_VALUE);
+		}
+
+		if (r == WJB_VALUE || r == WJB_ELEM)
+		{
+
+			if (level >= first ||
+				(first == PG_UINT32_MAX && last == PG_UINT32_MAX &&
+				 v.type != jbvBinary))	/* leaves only requested */
+			{
+				/* check expression */
+				if (jsp)
+				{
+					if (ignoreStructuralErrors)
+					{
+						bool		savedIgnoreStructuralErrors;
+
+						savedIgnoreStructuralErrors = cxt->ignoreStructuralErrors;
+						cxt->ignoreStructuralErrors = true;
+						res = recursiveExecuteUnwrap(cxt, jsp, &v, unwrapNext, found);
+						cxt->ignoreStructuralErrors = savedIgnoreStructuralErrors;
+					}
+					else
+						res = recursiveExecuteUnwrap(cxt, jsp, &v, unwrapNext, found);
+
+					if (jperIsError(res))
+						break;
+
+					if (res == jperOk && !found)
+						break;
+				}
+				else if (found)
+					JsonValueListAppend(found, copyJsonbValue(&v));
+				else
+					return jperOk;
+			}
+
+			if (level < last && v.type == jbvBinary)
+			{
+				res = recursiveAny(cxt, jsp, v.val.binary.data, found,
+								   level + 1, first, last,
+								   ignoreStructuralErrors, unwrapNext);
+
+				if (jperIsError(res))
+					break;
+
+				if (res == jperOk && found == NULL)
+					break;
+			}
+		}
+	}
+
+	return res;
+}
+
+/*
+ * Execute unary or binary predicate.
+ *
+ * Predicates have existence semantics, because their operands are item
+ * sequences.  Pairs of items from the left and right operand's sequences are
+ * checked.  TRUE returned only if any pair satisfying the condition is found.
+ * In strict mode, even if the desired pair has already been found, all pairs
+ * still need to be examined to check the absence of errors.  If any error
+ * occurs, UNKNOWN (analogous to SQL NULL) is returned.
+ */
+static JsonPathBool
+executePredicate(JsonPathExecContext *cxt, JsonPathItem *pred,
+				 JsonPathItem *larg, JsonPathItem *rarg, JsonbValue *jb,
+				 bool unwrapRightArg, JsonPathPredicateCallback exec,
+				 void *param)
+{
+	JsonPathExecResult res;
+	JsonValueListIterator lseqit;
+	JsonValueList lseq = {0};
+	JsonValueList rseq = {0};
+	JsonbValue *lval;
+	bool		error = false;
+	bool		found = false;
+
+	/* Left argument is always auto-unwrapped. */
+	res = recursiveExecuteAndUnwrapNoThrow(cxt, larg, jb, true, &lseq);
+	if (jperIsError(res))
+		return jpbUnknown;
+
+	if (rarg)
+	{
+		/* Right argument is conditionally auto-unwrapped. */
+		res = recursiveExecuteAndUnwrapNoThrow(cxt, rarg, jb, unwrapRightArg,
+											   &rseq);
+		if (jperIsError(res))
+			return jpbUnknown;
+	}
+
+	JsonValueListInitIterator(&lseq, &lseqit);
+	while ((lval = JsonValueListNext(&lseq, &lseqit)))
+	{
+		JsonValueListIterator rseqit;
+		JsonbValue *rval;
+		bool		first = true;
+
+		if (rarg)
+		{
+			JsonValueListInitIterator(&rseq, &rseqit);
+			rval = JsonValueListNext(&rseq, &rseqit);
+		}
+		else
+		{
+			rval = NULL;
+		}
+
+		/* Loop over right arg sequence or do single pass otherwise */
+		while (rarg ? (rval != NULL) : first)
+		{
+			JsonPathBool res = exec(pred, lval, rval, param);
+
+			if (res == jpbUnknown)
+			{
+				if (jspStrictAbsenseOfErrors(cxt))
+					return jpbUnknown;
+
+				error = true;
+			}
+			else if (res == jpbTrue)
+			{
+				if (!jspStrictAbsenseOfErrors(cxt))
+					return jpbTrue;
+
+				found = true;
+			}
+
+			first = false;
+			if (rarg)
+				rval = JsonValueListNext(&rseq, &rseqit);
+		}
+	}
+
+	if (found)					/* possible only in strict mode */
+		return jpbTrue;
+
+	if (error)					/* possible only in lax mode */
+		return jpbUnknown;
+
+	return jpbFalse;
+}
+
+/*
+ * Execute binary arithmetic expression on singleton numeric operands.
+ * Array operands are automatically unwrapped in lax mode.
+ */
+static JsonPathExecResult
+executeBinaryArithmExpr(JsonPathExecContext *cxt, JsonPathItem *jsp,
+						JsonbValue *jb, PGFunction func,
+						JsonValueList *found)
+{
+	JsonPathExecResult jper;
+	JsonPathItem elem;
+	JsonValueList lseq = {0};
+	JsonValueList rseq = {0};
+	JsonbValue *lval;
+	JsonbValue *rval;
+	Datum		res;
+
+	jspGetLeftArg(jsp, &elem);
+
+	/*
+	 * XXX: By standard only operands of multiplicative expressions are
+	 * unwrapped.  We extend it to other binary arithmetics expressions too.
+	 */
+	jper = recursiveExecuteAndUnwrap(cxt, &elem, jb, true, &lseq);
+	if (jperIsError(jper))
+		return jper;
+
+	jspGetRightArg(jsp, &elem);
+
+	jper = recursiveExecuteAndUnwrap(cxt, &elem, jb, true, &rseq);
+	if (jperIsError(jper))
+		return jper;
+
+	if (JsonValueListLength(&lseq) != 1 ||
+		!(lval = getScalar(JsonValueListHead(&lseq), jbvNumeric)))
+		RETURN_ERROR(ereport(ERROR,
+							 (errcode(ERRCODE_SINGLETON_JSON_ITEM_REQUIRED),
+							  errmsg(ERRMSG_SINGLETON_JSON_ITEM_REQUIRED),
+							  errdetail("left operand of binary jsonpath operator %s "
+										"is not a singleton numeric value",
+										jspOperationName(jsp->type)))));
+
+	if (JsonValueListLength(&rseq) != 1 ||
+		!(rval = getScalar(JsonValueListHead(&rseq), jbvNumeric)))
+		RETURN_ERROR(ereport(ERROR,
+							 (errcode(ERRCODE_SINGLETON_JSON_ITEM_REQUIRED),
+							  errmsg(ERRMSG_SINGLETON_JSON_ITEM_REQUIRED),
+							  errdetail("right operand of binary jsonpath operator %s "
+										"is not a singleton numeric value",
+										jspOperationName(jsp->type)))));
+
+	res = DirectFunctionCall2(func,
+							  NumericGetDatum(lval->val.numeric),
+							  NumericGetDatum(rval->val.numeric));
+
+	if (!jspGetNext(jsp, &elem) && !found)
+		return jperOk;
+
+	lval = palloc(sizeof(*lval));
+	lval->type = jbvNumeric;
+	lval->val.numeric = DatumGetNumeric(res);
+
+	return recursiveExecuteNext(cxt, jsp, &elem, lval, found, false);
+}
+
+/*
+ * Execute unary arithmetic expression for each numeric item in its operand's
+ * sequence.  Array operand is automatically unwrapped in lax mode.
+ */
+static JsonPathExecResult
+executeUnaryArithmExpr(JsonPathExecContext *cxt, JsonPathItem *jsp,
+					   JsonbValue *jb, PGFunction func, JsonValueList *found)
+{
+	JsonPathExecResult jper;
+	JsonPathExecResult jper2;
+	JsonPathItem elem;
+	JsonValueList seq = {0};
+	JsonValueListIterator it;
+	JsonbValue *val;
+	bool		hasNext;
+
+	jspGetArg(jsp, &elem);
+	jper = recursiveExecuteAndUnwrap(cxt, &elem, jb, true, &seq);
+
+	if (jperIsError(jper))
+		return jper;
+
+	jper = jperNotFound;
+
+	hasNext = jspGetNext(jsp, &elem);
+
+	JsonValueListInitIterator(&seq, &it);
+	while ((val = JsonValueListNext(&seq, &it)))
+	{
+		if ((val = getScalar(val, jbvNumeric)))
+		{
+			if (!found && !hasNext)
+				return jperOk;
+		}
+		else
+		{
+			if (!found && !hasNext)
+				continue;		/* skip non-numerics processing */
+
+			RETURN_ERROR(ereport(ERROR,
+								 (errcode(ERRCODE_JSON_NUMBER_NOT_FOUND),
+								  errmsg(ERRMSG_JSON_NUMBER_NOT_FOUND),
+								  errdetail("operand of unary jsonpath operator %s "
+											"is not a numeric value",
+											jspOperationName(jsp->type)))));
+		}
+
+		if (func)
+			val->val.numeric =
+				DatumGetNumeric(DirectFunctionCall1(func,
+													NumericGetDatum(val->val.numeric)));
+
+		jper2 = recursiveExecuteNext(cxt, jsp, &elem, val, found, false);
+
+		if (jperIsError(jper2))
+			return jper2;
+
+		if (jper2 == jperOk)
+		{
+			if (!found)
+				return jperOk;
+			jper = jperOk;
+		}
+	}
+
+	return jper;
+}
+
+/*
+ * STARTS_WITH predicate callback.
+ *
+ * Check if the 'whole' string starts from 'initial' string.
+ */
+static JsonPathBool
+executeStartsWith(JsonPathItem *jsp, JsonbValue *whole, JsonbValue *initial,
+				  void *param)
+{
+	if (!(whole = getScalar(whole, jbvString)))
+		return jpbUnknown;		/* error */
+
+	if (!(initial = getScalar(initial, jbvString)))
+		return jpbUnknown;		/* error */
+
+	if (whole->val.string.len >= initial->val.string.len &&
+		!memcmp(whole->val.string.val,
+				initial->val.string.val,
+				initial->val.string.len))
+		return jpbTrue;
+
+	return jpbFalse;
+}
+
+/*
+ * LIKE_REGEX predicate callback.
+ *
+ * Check if the string matches regex pattern.
+ */
+static JsonPathBool
+executeLikeRegex(JsonPathItem *jsp, JsonbValue *str, JsonbValue *rarg,
+				 void *param)
+{
+	JsonLikeRegexContext *cxt = param;
+
+	if (!(str = getScalar(str, jbvString)))
+		return jpbUnknown;
+
+	/* Cache regex text and converted flags. */
+	if (!cxt->regex)
+	{
+		uint32		flags = jsp->content.like_regex.flags;
+
+		cxt->regex =
+			cstring_to_text_with_len(jsp->content.like_regex.pattern,
+									 jsp->content.like_regex.patternlen);
+
+		/* Convert regex flags. */
+		cxt->cflags = REG_ADVANCED;
+
+		if (flags & JSP_REGEX_ICASE)
+			cxt->cflags |= REG_ICASE;
+		if (flags & JSP_REGEX_MLINE)
+			cxt->cflags |= REG_NEWLINE;
+		if (flags & JSP_REGEX_SLINE)
+			cxt->cflags &= ~REG_NEWLINE;
+		if (flags & JSP_REGEX_WSPACE)
+			cxt->cflags |= REG_EXPANDED;
+	}
+
+	if (RE_compile_and_execute(cxt->regex, str->val.string.val,
+							   str->val.string.len,
+							   cxt->cflags, DEFAULT_COLLATION_OID, 0, NULL))
+		return jpbTrue;
+
+	return jpbFalse;
+}
+
+static JsonPathExecResult
+executeNumericItemMethod(JsonPathExecContext *cxt, JsonPathItem *jsp,
+						 JsonbValue *jb, bool unwrap, PGFunction func,
+						 JsonValueList *found)
+{
+	JsonPathItem next;
+	Datum		datum;
+
+	if (unwrap && JsonbType(jb) == jbvArray)
+		return recursiveExecuteUnwrapArray(cxt, jsp, jb, found, false);
+
+	if (!(jb = getScalar(jb, jbvNumeric)))
+		RETURN_ERROR(ereport(ERROR,
+							 (errcode(ERRCODE_NON_NUMERIC_JSON_ITEM),
+							  errmsg(ERRMSG_NON_NUMERIC_JSON_ITEM),
+							  errdetail("jsonpath item method .%s() is applied to "
+										"not a numeric value",
+										jspOperationName(jsp->type)))));
+
+	datum = NumericGetDatum(jb->val.numeric);
+	datum = DirectFunctionCall1(func, datum);
+
+	if (!jspGetNext(jsp, &next) && !found)
+		return jperOk;
+
+	jb = palloc(sizeof(*jb));
+	jb->type = jbvNumeric;
+	jb->val.numeric = DatumGetNumeric(datum);
+
+	return recursiveExecuteNext(cxt, jsp, &next, jb, found, false);
+}
+
+/*
+ * Implementation of .keyvalue() method.
+ *
+ * .keyvalue() method returns a sequence of object's key-value pairs in the
+ * following format: '{ "key": key, "value": value, "id": id }'.
+ *
+ * "id" field is an object identifier which is constructed from the two parts:
+ * base object id and its binary offset in base object's jsonb:
+ * id = 10000000000 * base_object_id + obj_offset_in_base_object
+ *
+ * 10000000000 (10^10) -- is a first round decimal number greater than 2^32
+ * (maximal offset in jsonb).  Decimal multiplier is used here to improve the
+ * readability of identifiers.
+ *
+ * Base object is usually a root object of the path: context item '$' or path
+ * variable '$var', literals can't produce objects for now.  But if the path
+ * contains generated objects (.keyvalue() itself, for example), then they
+ * become base object for the subsequent .keyvalue().
+ *
+ * Id of '$' is 0. Id of '$var' is its ordinal (positive) number in the list
+ * of variables (see getJsonPathVariable()).  Ids for generated objects
+ * are assigned using global counter JsonPathExecContext.lastGeneratedObjectId.
+ */
+static JsonPathExecResult
+executeKeyValueMethod(JsonPathExecContext *cxt, JsonPathItem *jsp,
+					  JsonbValue *jb, JsonValueList *found)
+{
+	JsonPathExecResult res = jperNotFound;
+	JsonPathItem next;
+	JsonbContainer *jbc;
+	JsonbValue	key;
+	JsonbValue	val;
+	JsonbValue	idval;
+	JsonbValue	keystr;
+	JsonbValue	valstr;
+	JsonbValue	idstr;
+	JsonbIterator *it;
+	JsonbIteratorToken tok;
+	int64		id;
+	bool		hasNext;
+
+	if (JsonbType(jb) != jbvObject || jb->type != jbvBinary)
+		RETURN_ERROR(ereport(ERROR,
+							 (errcode(ERRCODE_JSON_OBJECT_NOT_FOUND),
+							  errmsg(ERRMSG_JSON_OBJECT_NOT_FOUND),
+							  errdetail("jsonpath item method .%s() is applied "
+										"to not an object",
+										jspOperationName(jsp->type)))));
+
+	jbc = jb->val.binary.data;
+
+	if (!JsonContainerSize(jbc))
+		return jperNotFound;	/* no key-value pairs */
+
+	hasNext = jspGetNext(jsp, &next);
+
+	keystr.type = jbvString;
+	keystr.val.string.val = "key";
+	keystr.val.string.len = 3;
+
+	valstr.type = jbvString;
+	valstr.val.string.val = "value";
+	valstr.val.string.len = 5;
+
+	idstr.type = jbvString;
+	idstr.val.string.val = "id";
+	idstr.val.string.len = 2;
+
+	/* construct object id from its base object and offset inside that */
+	id = jb->type != jbvBinary ? 0 :
+		(int64) ((char *) jbc - (char *) cxt->baseObject.jbc);
+	id += (int64) cxt->baseObject.id * INT64CONST(10000000000);
+
+	idval.type = jbvNumeric;
+	idval.val.numeric = DatumGetNumeric(DirectFunctionCall1(int8_numeric,
+															Int64GetDatum(id)));
+
+	it = JsonbIteratorInit(jbc);
+
+	while ((tok = JsonbIteratorNext(&it, &key, true)) != WJB_DONE)
+	{
+		JsonBaseObjectInfo baseObject;
+		JsonbValue	obj;
+		JsonbParseState *ps;
+		JsonbValue *keyval;
+		Jsonb	   *jsonb;
+
+		if (tok != WJB_KEY)
+			continue;
+
+		res = jperOk;
+
+		if (!hasNext && !found)
+			break;
+
+		tok = JsonbIteratorNext(&it, &val, true);
+		Assert(tok == WJB_VALUE);
+
+		ps = NULL;
+		pushJsonbValue(&ps, WJB_BEGIN_OBJECT, NULL);
+
+		pushJsonbValue(&ps, WJB_KEY, &keystr);
+		pushJsonbValue(&ps, WJB_VALUE, &key);
+
+		pushJsonbValue(&ps, WJB_KEY, &valstr);
+		pushJsonbValue(&ps, WJB_VALUE, &val);
+
+		pushJsonbValue(&ps, WJB_KEY, &idstr);
+		pushJsonbValue(&ps, WJB_VALUE, &idval);
+
+		keyval = pushJsonbValue(&ps, WJB_END_OBJECT, NULL);
+
+		jsonb = JsonbValueToJsonb(keyval);
+
+		JsonbInitBinary(&obj, jsonb);
+
+		baseObject = setBaseObject(cxt, &obj, cxt->lastGeneratedObjectId++);
+
+		res = recursiveExecuteNext(cxt, jsp, &next, &obj, found, true);
+
+		cxt->baseObject = baseObject;
+
+		if (jperIsError(res))
+			return res;
+
+		if (res == jperOk && !found)
+			break;
+	}
+
+	return res;
+}
+
+/*
+ * Convert boolean execution status 'res' to a boolean JSON item and execute
+ * next jsonpath.
+ */
+static JsonPathExecResult
+appendBoolResult(JsonPathExecContext *cxt, JsonPathItem *jsp,
+				 JsonValueList *found, JsonPathBool res)
+{
+	JsonPathItem next;
+	JsonbValue	jbv;
+
+	if (!jspGetNext(jsp, &next) && !found)
+		return jperOk;			/* found singleton boolean value */
+
+	if (res == jpbUnknown)
+	{
+		jbv.type = jbvNull;
+	}
+	else
+	{
+		jbv.type = jbvBool;
+		jbv.val.boolean = res == jpbTrue;
+	}
+
+	return recursiveExecuteNext(cxt, jsp, &next, &jbv, found, true);
+}
+
+/*
+ * Convert jsonpath's scalar or variable node to actual jsonb value.
+ *
+ * If node is a variable then its id returned, otherwise 0 returned.
+ */
+static void
+getJsonPathItem(JsonPathExecContext *cxt, JsonPathItem *item,
+				JsonbValue *value)
+{
+	switch (item->type)
+	{
+		case jpiNull:
+			value->type = jbvNull;
+			break;
+		case jpiBool:
+			value->type = jbvBool;
+			value->val.boolean = jspGetBool(item);
+			break;
+		case jpiNumeric:
+			value->type = jbvNumeric;
+			value->val.numeric = jspGetNumeric(item);
+			break;
+		case jpiString:
+			value->type = jbvString;
+			value->val.string.val = jspGetString(item,
+												 &value->val.string.len);
+			break;
+		case jpiVariable:
+			getJsonPathVariable(cxt, item, cxt->vars, value);
+			return;
+		default:
+			elog(ERROR, "unexpected jsonpath item type");
+	}
+}
+
+/*
+ * Get the value of variable passed to jsonpath executor
+ */
+static void
+getJsonPathVariable(JsonPathExecContext *cxt, JsonPathItem *variable,
+					Jsonb *vars, JsonbValue *value)
+{
+	char	   *varName;
+	int			varNameLength;
+	JsonbValue	tmp;
+	JsonbValue *v;
+
+	if (!vars)
+	{
+		value->type = jbvNull;
+		return;
+	}
+
+	Assert(variable->type == jpiVariable);
+	varName = jspGetString(variable, &varNameLength);
+	tmp.type = jbvString;
+	tmp.val.string.val = varName;
+	tmp.val.string.len = varNameLength;
+
+	v = findJsonbValueFromContainer(&vars->root, JB_FOBJECT, &tmp);
+
+	if (v)
+	{
+		*value = *v;
+		pfree(v);
+	}
+	else
+	{
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("cannot find jsonpath variable '%s'",
+						pnstrdup(varName, varNameLength))));
+	}
+
+	JsonbInitBinary(&tmp, vars);
+	setBaseObject(cxt, &tmp, 1);
+}
+
+/**************** Support functions for JsonPath execution *****************/
+
+/*
+ * Returns the size of an array item, or -1 if item is not an array.
+ */
+static int
+JsonbArraySize(JsonbValue *jb)
+{
+	Assert(jb->type != jbvArray);
+
+	if (jb->type == jbvBinary)
+	{
+		JsonbContainer *jbc = jb->val.binary.data;
+
+		if (JsonContainerIsArray(jbc) && !JsonContainerIsScalar(jbc))
+			return JsonContainerSize(jbc);
+	}
+
+	return -1;
+}
+
+/* Comparison predicate callback. */
+static JsonPathBool
+executeComparison(JsonPathItem *cmp, JsonbValue *lv, JsonbValue *rv, void *p)
+{
+	return compareItems(cmp->type, lv, rv);
+}
+
+/*
+ * Compare two SQL/JSON items using comparison operation 'op'.
+ */
+static JsonPathBool
+compareItems(int32 op, JsonbValue *jb1, JsonbValue *jb2)
+{
+	int			cmp;
+	bool		res;
+
+	if (jb1->type != jb2->type)
+	{
+		if (jb1->type == jbvNull || jb2->type == jbvNull)
+
+			/*
+			 * Equality and order comparison of nulls to non-nulls returns
+			 * always false, but inequality comparison returns true.
+			 */
+			return op == jpiNotEqual ? jpbTrue : jpbFalse;
+
+		/* Non-null items of different types are not comparable. */
+		return jpbUnknown;
+	}
+
+	switch (jb1->type)
+	{
+		case jbvNull:
+			cmp = 0;
+			break;
+		case jbvBool:
+			cmp = jb1->val.boolean == jb2->val.boolean ? 0 :
+				jb1->val.boolean ? 1 : -1;
+			break;
+		case jbvNumeric:
+			cmp = compareNumeric(jb1->val.numeric, jb2->val.numeric);
+			break;
+		case jbvString:
+			if (op == jpiEqual)
+				return jb1->val.string.len != jb2->val.string.len ||
+					memcmp(jb1->val.string.val,
+						   jb2->val.string.val,
+						   jb1->val.string.len) ? jpbFalse : jpbTrue;
+
+			cmp = varstr_cmp(jb1->val.string.val, jb1->val.string.len,
+							 jb2->val.string.val, jb2->val.string.len,
+							 DEFAULT_COLLATION_OID);
+			break;
+
+		case jbvBinary:
+		case jbvArray:
+		case jbvObject:
+			return jpbUnknown;	/* non-scalars are not comparable */
+
+		default:
+			elog(ERROR, "invalid jsonb value type %d", jb1->type);
+	}
+
+	switch (op)
+	{
+		case jpiEqual:
+			res = (cmp == 0);
+			break;
+		case jpiNotEqual:
+			res = (cmp != 0);
+			break;
+		case jpiLess:
+			res = (cmp < 0);
+			break;
+		case jpiGreater:
+			res = (cmp > 0);
+			break;
+		case jpiLessOrEqual:
+			res = (cmp <= 0);
+			break;
+		case jpiGreaterOrEqual:
+			res = (cmp >= 0);
+			break;
+		default:
+			elog(ERROR, "unrecognized jsonpath operation: %d", op);
+			return jpbUnknown;
+	}
+
+	return res ? jpbTrue : jpbFalse;
+}
+
+/* Compare two numerics */
+static int
+compareNumeric(Numeric a, Numeric b)
+{
+	return DatumGetInt32(DirectFunctionCall2(numeric_cmp,
+											 PointerGetDatum(a),
+											 PointerGetDatum(b)));
+}
+
+static JsonbValue *
+copyJsonbValue(JsonbValue *src)
+{
+	JsonbValue *dst = palloc(sizeof(*dst));
+
+	*dst = *src;
+
+	return dst;
+}
+
+/*
+ * Execute array subscript expression and convert resulting numeric item to
+ * the integer type with truncation.
+ */
+static JsonPathExecResult
+getArrayIndex(JsonPathExecContext *cxt, JsonPathItem *jsp, JsonbValue *jb,
+			  int32 *index)
+{
+	JsonbValue *jbv;
+	JsonValueList found = {0};
+	JsonPathExecResult res = recursiveExecute(cxt, jsp, jb, &found);
+	Datum		numeric_index;
+
+	if (jperIsError(res))
+		return res;
+
+	if (JsonValueListLength(&found) != 1 ||
+		!(jbv = getScalar(JsonValueListHead(&found), jbvNumeric)))
+		RETURN_ERROR(ereport(ERROR,
+							 (errcode(ERRCODE_INVALID_JSON_SUBSCRIPT),
+							  errmsg(ERRMSG_INVALID_JSON_SUBSCRIPT),
+							  errdetail("jsonpath array subscript is not a "
+										"singleton numeric value"))));
+
+	numeric_index = DirectFunctionCall2(numeric_trunc,
+										NumericGetDatum(jbv->val.numeric),
+										Int32GetDatum(0));
+
+	*index = DatumGetInt32(DirectFunctionCall1(numeric_int4, numeric_index));
+
+	return jperOk;
+}
+
+/* Save base object and its id needed for the execution of .keyvalue(). */
+static JsonBaseObjectInfo
+setBaseObject(JsonPathExecContext *cxt, JsonbValue *jbv, int32 id)
+{
+	JsonBaseObjectInfo baseObject = cxt->baseObject;
+
+	cxt->baseObject.jbc = jbv->type != jbvBinary ? NULL :
+		(JsonbContainer *) jbv->val.binary.data;
+	cxt->baseObject.id = id;
+
+	return baseObject;
+}
+
+static void
+JsonValueListAppend(JsonValueList *jvl, JsonbValue *jbv)
+{
+	if (jvl->singleton)
+	{
+		jvl->list = list_make2(jvl->singleton, jbv);
+		jvl->singleton = NULL;
+	}
+	else if (!jvl->list)
+		jvl->singleton = jbv;
+	else
+		jvl->list = lappend(jvl->list, jbv);
+}
+
+static int
+JsonValueListLength(const JsonValueList *jvl)
+{
+	return jvl->singleton ? 1 : list_length(jvl->list);
+}
+
+static bool
+JsonValueListIsEmpty(JsonValueList *jvl)
+{
+	return !jvl->singleton && list_length(jvl->list) <= 0;
+}
+
+static JsonbValue *
+JsonValueListHead(JsonValueList *jvl)
+{
+	return jvl->singleton ? jvl->singleton : linitial(jvl->list);
+}
+
+static List *
+JsonValueListGetList(JsonValueList *jvl)
+{
+	if (jvl->singleton)
+		return list_make1(jvl->singleton);
+
+	return jvl->list;
+}
+
+static void
+JsonValueListInitIterator(const JsonValueList *jvl, JsonValueListIterator *it)
+{
+	if (jvl->singleton)
+	{
+		it->value = jvl->singleton;
+		it->next = NULL;
+	}
+	else if (list_head(jvl->list) != NULL)
+	{
+		it->value = (JsonbValue *) linitial(jvl->list);
+		it->next = lnext(list_head(jvl->list));
+	}
+	else
+	{
+		it->value = NULL;
+		it->next = NULL;
+	}
+}
+
+/*
+ * Get the next item from the sequence advancing iterator.
+ */
+static JsonbValue *
+JsonValueListNext(const JsonValueList *jvl, JsonValueListIterator *it)
+{
+	JsonbValue *result = it->value;
+
+	if (it->next)
+	{
+		it->value = lfirst(it->next);
+		it->next = lnext(it->next);
+	}
+	else
+	{
+		it->value = NULL;
+	}
+
+	return result;
+}
+
+/*
+ * Initialize a binary JsonbValue with the given jsonb container.
+ */
+static JsonbValue *
+JsonbInitBinary(JsonbValue *jbv, Jsonb *jb)
+{
+	jbv->type = jbvBinary;
+	jbv->val.binary.data = &jb->root;
+	jbv->val.binary.len = VARSIZE_ANY_EXHDR(jb);
+
+	return jbv;
+}
+
+/*
+ * Returns jbv* type of of JsonbValue. Note, it never returns jbvBinary as is.
+ */
+static int
+JsonbType(JsonbValue *jb)
+{
+	int			type = jb->type;
+
+	if (jb->type == jbvBinary)
+	{
+		JsonbContainer *jbc = (void *) jb->val.binary.data;
+
+		/* Scalars should be always extracted during jsonpath execution. */
+		Assert(!JsonContainerIsScalar(jbc));
+
+		if (JsonContainerIsObject(jbc))
+			type = jbvObject;
+		else if (JsonContainerIsArray(jbc))
+			type = jbvArray;
+		else
+			elog(ERROR, "invalid jsonb container type: 0x%08x", jbc->header);
+	}
+
+	return type;
+}
+
+/* Get scalar of given type or NULL on type mismatch */
+static JsonbValue *
+getScalar(JsonbValue *scalar, enum jbvType type)
+{
+	/* Scalars should be always extracted during jsonpath execution. */
+	Assert(scalar->type != jbvBinary ||
+		   !JsonContainerIsScalar(scalar->val.binary.data));
+
+	return scalar->type == type ? scalar : NULL;
+}
+
+/* Construct a JSON array from the item list */
+static JsonbValue *
+wrapItemsInArray(const JsonValueList *items)
+{
+	JsonbParseState *ps = NULL;
+	JsonValueListIterator it;
+	JsonbValue *jbv;
+
+	pushJsonbValue(&ps, WJB_BEGIN_ARRAY, NULL);
+
+	JsonValueListInitIterator(items, &it);
+	while ((jbv = JsonValueListNext(items, &it)))
+		pushJsonbValue(&ps, WJB_ELEM, jbv);
+
+	return pushJsonbValue(&ps, WJB_END_ARRAY, NULL);
+}
diff --git a/src/backend/utils/adt/jsonpath_gram.y b/src/backend/utils/adt/jsonpath_gram.y
new file mode 100644
index 0000000..183861f
--- /dev/null
+++ b/src/backend/utils/adt/jsonpath_gram.y
@@ -0,0 +1,480 @@
+/*-------------------------------------------------------------------------
+ *
+ * jsonpath_gram.y
+ *	 Grammar definitions for jsonpath datatype
+ *
+ * Copyright (c) 2019, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ *	src/backend/utils/adt/jsonpath_gram.y
+ *
+ *-------------------------------------------------------------------------
+ */
+
+%{
+#include "postgres.h"
+
+#include "catalog/pg_collation.h"
+#include "fmgr.h"
+#include "miscadmin.h"
+#include "nodes/pg_list.h"
+#include "regex/regex.h"
+#include "utils/builtins.h"
+#include "utils/jsonpath.h"
+#include "utils/jsonpath_scanner.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
+
+static JsonPathParseItem*
+makeItemType(int type)
+{
+	JsonPathParseItem* v = palloc(sizeof(*v));
+
+	CHECK_FOR_INTERRUPTS();
+
+	v->type = type;
+	v->next = NULL;
+
+	return v;
+}
+
+static JsonPathParseItem*
+makeItemString(string *s)
+{
+	JsonPathParseItem *v;
+
+	if (s == NULL)
+	{
+		v = makeItemType(jpiNull);
+	}
+	else
+	{
+		v = makeItemType(jpiString);
+		v->value.string.val = s->val;
+		v->value.string.len = s->len;
+	}
+
+	return v;
+}
+
+static JsonPathParseItem*
+makeItemVariable(string *s)
+{
+	JsonPathParseItem *v;
+
+	v = makeItemType(jpiVariable);
+	v->value.string.val = s->val;
+	v->value.string.len = s->len;
+
+	return v;
+}
+
+static JsonPathParseItem*
+makeItemKey(string *s)
+{
+	JsonPathParseItem *v;
+
+	v = makeItemString(s);
+	v->type = jpiKey;
+
+	return v;
+}
+
+static JsonPathParseItem*
+makeItemNumeric(string *s)
+{
+	JsonPathParseItem		*v;
+
+	v = makeItemType(jpiNumeric);
+	v->value.numeric =
+		DatumGetNumeric(DirectFunctionCall3(numeric_in,
+											CStringGetDatum(s->val), 0, -1));
+
+	return v;
+}
+
+static JsonPathParseItem*
+makeItemBool(bool val) {
+	JsonPathParseItem *v = makeItemType(jpiBool);
+
+	v->value.boolean = val;
+
+	return v;
+}
+
+static JsonPathParseItem*
+makeItemBinary(int type, JsonPathParseItem* la, JsonPathParseItem *ra)
+{
+	JsonPathParseItem  *v = makeItemType(type);
+
+	v->value.args.left = la;
+	v->value.args.right = ra;
+
+	return v;
+}
+
+static JsonPathParseItem*
+makeItemUnary(int type, JsonPathParseItem* a)
+{
+	JsonPathParseItem  *v;
+
+	if (type == jpiPlus && a->type == jpiNumeric && !a->next)
+		return a;
+
+	if (type == jpiMinus && a->type == jpiNumeric && !a->next)
+	{
+		v = makeItemType(jpiNumeric);
+		v->value.numeric =
+			DatumGetNumeric(DirectFunctionCall1(numeric_uminus,
+												NumericGetDatum(a->value.numeric)));
+		return v;
+	}
+
+	v = makeItemType(type);
+
+	v->value.arg = a;
+
+	return v;
+}
+
+static JsonPathParseItem*
+makeItemList(List *list)
+{
+	JsonPathParseItem *head, *end;
+	ListCell   *cell = list_head(list);
+
+	head = end = (JsonPathParseItem *) lfirst(cell);
+
+	if (!lnext(cell))
+		return head;
+
+	/* append items to the end of already existing list */
+	while (end->next)
+		end = end->next;
+
+	for_each_cell(cell, lnext(cell))
+	{
+		JsonPathParseItem *c = (JsonPathParseItem *) lfirst(cell);
+
+		end->next = c;
+		end = c;
+	}
+
+	return head;
+}
+
+static JsonPathParseItem*
+makeIndexArray(List *list)
+{
+	JsonPathParseItem	*v = makeItemType(jpiIndexArray);
+	ListCell			*cell;
+	int					i = 0;
+
+	Assert(list_length(list) > 0);
+	v->value.array.nelems = list_length(list);
+
+	v->value.array.elems = palloc(sizeof(v->value.array.elems[0]) *
+								  v->value.array.nelems);
+
+	foreach(cell, list)
+	{
+		JsonPathParseItem *jpi = lfirst(cell);
+
+		Assert(jpi->type == jpiSubscript);
+
+		v->value.array.elems[i].from = jpi->value.args.left;
+		v->value.array.elems[i++].to = jpi->value.args.right;
+	}
+
+	return v;
+}
+
+static JsonPathParseItem*
+makeAny(int first, int last)
+{
+	JsonPathParseItem *v = makeItemType(jpiAny);
+
+	v->value.anybounds.first = (first >= 0) ? first : PG_UINT32_MAX;
+	v->value.anybounds.last = (last >= 0) ? last : PG_UINT32_MAX;
+
+	return v;
+}
+
+static JsonPathParseItem *
+makeItemLikeRegex(JsonPathParseItem *expr, string *pattern, string *flags)
+{
+	JsonPathParseItem *v = makeItemType(jpiLikeRegex);
+	int			i;
+	int			cflags = REG_ADVANCED;
+
+	v->value.like_regex.expr = expr;
+	v->value.like_regex.pattern = pattern->val;
+	v->value.like_regex.patternlen = pattern->len;
+	v->value.like_regex.flags = 0;
+
+	for (i = 0; flags && i < flags->len; i++)
+	{
+		switch (flags->val[i])
+		{
+			case 'i':
+				v->value.like_regex.flags |= JSP_REGEX_ICASE;
+				cflags |= REG_ICASE;
+				break;
+			case 's':
+				v->value.like_regex.flags &= ~JSP_REGEX_MLINE;
+				v->value.like_regex.flags |= JSP_REGEX_SLINE;
+				cflags |= REG_NEWLINE;
+				break;
+			case 'm':
+				v->value.like_regex.flags &= ~JSP_REGEX_SLINE;
+				v->value.like_regex.flags |= JSP_REGEX_MLINE;
+				cflags &= ~REG_NEWLINE;
+				break;
+			case 'x':
+				v->value.like_regex.flags |= JSP_REGEX_WSPACE;
+				cflags |= REG_EXPANDED;
+				break;
+			default:
+				yyerror(NULL, "unrecognized flag of LIKE_REGEX predicate");
+				break;
+		}
+	}
+
+	/* check regex validity */
+	(void) RE_compile_and_cache(cstring_to_text_with_len(pattern->val,
+														 pattern->len),
+								cflags, DEFAULT_COLLATION_OID);
+
+	return v;
+}
+
+%}
+
+/* BISON Declarations */
+%pure-parser
+%expect 0
+%name-prefix="jsonpath_yy"
+%error-verbose
+%parse-param {JsonPathParseResult **result}
+
+%union {
+	string				str;
+	List				*elems;		/* list of JsonPathParseItem */
+	List				*indexs;	/* list of integers */
+	JsonPathParseItem	*value;
+	JsonPathParseResult *result;
+	JsonPathItemType	optype;
+	bool				boolean;
+	int					integer;
+}
+
+%token	<str>		TO_P NULL_P TRUE_P FALSE_P IS_P UNKNOWN_P EXISTS_P
+%token	<str>		IDENT_P STRING_P NUMERIC_P INT_P VARIABLE_P
+%token	<str>		OR_P AND_P NOT_P
+%token	<str>		LESS_P LESSEQUAL_P EQUAL_P NOTEQUAL_P GREATEREQUAL_P GREATER_P
+%token	<str>		ANY_P STRICT_P LAX_P LAST_P STARTS_P WITH_P LIKE_REGEX_P FLAG_P
+%token	<str>		ABS_P SIZE_P TYPE_P FLOOR_P DOUBLE_P CEILING_P KEYVALUE_P
+
+%type	<result>	result
+
+%type	<value>		scalar_value path_primary expr array_accessor
+					any_path accessor_op key predicate delimited_predicate
+					index_elem starts_with_initial expr_or_predicate
+
+%type	<elems>		accessor_expr
+
+%type	<indexs>	index_list
+
+%type	<optype>	comp_op method
+
+%type	<boolean>	mode
+
+%type	<str>		key_name
+
+%type	<integer>	any_level
+
+%left	OR_P
+%left	AND_P
+%right	NOT_P
+%left	'+' '-'
+%left	'*' '/' '%'
+%left	UMINUS
+%nonassoc '(' ')'
+
+/* Grammar follows */
+%%
+
+result:
+	mode expr_or_predicate			{
+										*result = palloc(sizeof(JsonPathParseResult));
+										(*result)->expr = $2;
+										(*result)->lax = $1;
+									}
+	| /* EMPTY */					{ *result = NULL; }
+	;
+
+expr_or_predicate:
+	expr							{ $$ = $1; }
+	| predicate						{ $$ = $1; }
+	;
+
+mode:
+	STRICT_P						{ $$ = false; }
+	| LAX_P							{ $$ = true; }
+	| /* EMPTY */					{ $$ = true; }
+	;
+
+scalar_value:
+	STRING_P						{ $$ = makeItemString(&$1); }
+	| NULL_P						{ $$ = makeItemString(NULL); }
+	| TRUE_P						{ $$ = makeItemBool(true); }
+	| FALSE_P						{ $$ = makeItemBool(false); }
+	| NUMERIC_P						{ $$ = makeItemNumeric(&$1); }
+	| INT_P							{ $$ = makeItemNumeric(&$1); }
+	| VARIABLE_P 					{ $$ = makeItemVariable(&$1); }
+	;
+
+comp_op:
+	EQUAL_P							{ $$ = jpiEqual; }
+	| NOTEQUAL_P					{ $$ = jpiNotEqual; }
+	| LESS_P						{ $$ = jpiLess; }
+	| GREATER_P						{ $$ = jpiGreater; }
+	| LESSEQUAL_P					{ $$ = jpiLessOrEqual; }
+	| GREATEREQUAL_P				{ $$ = jpiGreaterOrEqual; }
+	;
+
+delimited_predicate:
+	'(' predicate ')'						{ $$ = $2; }
+	| EXISTS_P '(' expr ')'			{ $$ = makeItemUnary(jpiExists, $3); }
+	;
+
+predicate:
+	delimited_predicate				{ $$ = $1; }
+	| expr comp_op expr				{ $$ = makeItemBinary($2, $1, $3); }
+	| predicate AND_P predicate		{ $$ = makeItemBinary(jpiAnd, $1, $3); }
+	| predicate OR_P predicate		{ $$ = makeItemBinary(jpiOr, $1, $3); }
+	| NOT_P delimited_predicate 	{ $$ = makeItemUnary(jpiNot, $2); }
+	| '(' predicate ')' IS_P UNKNOWN_P	{ $$ = makeItemUnary(jpiIsUnknown, $2); }
+	| expr STARTS_P WITH_P starts_with_initial
+		{ $$ = makeItemBinary(jpiStartsWith, $1, $4); }
+	| expr LIKE_REGEX_P STRING_P 	{ $$ = makeItemLikeRegex($1, &$3, NULL); }
+	| expr LIKE_REGEX_P STRING_P FLAG_P STRING_P
+									{ $$ = makeItemLikeRegex($1, &$3, &$5); }
+	;
+
+starts_with_initial:
+	STRING_P						{ $$ = makeItemString(&$1); }
+	| VARIABLE_P					{ $$ = makeItemVariable(&$1); }
+	;
+
+path_primary:
+	scalar_value					{ $$ = $1; }
+	| '$'							{ $$ = makeItemType(jpiRoot); }
+	| '@'							{ $$ = makeItemType(jpiCurrent); }
+	| LAST_P						{ $$ = makeItemType(jpiLast); }
+	;
+
+accessor_expr:
+	path_primary					{ $$ = list_make1($1); }
+	| '(' expr ')' accessor_op		{ $$ = list_make2($2, $4); }
+	| '(' predicate ')' accessor_op	{ $$ = list_make2($2, $4); }
+	| accessor_expr accessor_op		{ $$ = lappend($1, $2); }
+	;
+
+expr:
+	accessor_expr					{ $$ = makeItemList($1); }
+	| '(' expr ')'					{ $$ = $2; }
+	| '+' expr %prec UMINUS			{ $$ = makeItemUnary(jpiPlus, $2); }
+	| '-' expr %prec UMINUS			{ $$ = makeItemUnary(jpiMinus, $2); }
+	| expr '+' expr					{ $$ = makeItemBinary(jpiAdd, $1, $3); }
+	| expr '-' expr					{ $$ = makeItemBinary(jpiSub, $1, $3); }
+	| expr '*' expr					{ $$ = makeItemBinary(jpiMul, $1, $3); }
+	| expr '/' expr					{ $$ = makeItemBinary(jpiDiv, $1, $3); }
+	| expr '%' expr					{ $$ = makeItemBinary(jpiMod, $1, $3); }
+	;
+
+index_elem:
+	expr							{ $$ = makeItemBinary(jpiSubscript, $1, NULL); }
+	| expr TO_P expr				{ $$ = makeItemBinary(jpiSubscript, $1, $3); }
+	;
+
+index_list:
+	index_elem						{ $$ = list_make1($1); }
+	| index_list ',' index_elem		{ $$ = lappend($1, $3); }
+	;
+
+array_accessor:
+	'[' '*' ']'						{ $$ = makeItemType(jpiAnyArray); }
+	| '[' index_list ']'			{ $$ = makeIndexArray($2); }
+	;
+
+any_level:
+	INT_P							{ $$ = pg_atoi($1.val, 4, 0); }
+	| LAST_P						{ $$ = -1; }
+	;
+
+any_path:
+	ANY_P							{ $$ = makeAny(0, -1); }
+	| ANY_P '{' any_level '}'		{ $$ = makeAny($3, $3); }
+	| ANY_P '{' any_level TO_P any_level '}'	{ $$ = makeAny($3, $5); }
+	;
+
+accessor_op:
+	'.' key							{ $$ = $2; }
+	| '.' '*'						{ $$ = makeItemType(jpiAnyKey); }
+	| array_accessor				{ $$ = $1; }
+	| '.' any_path					{ $$ = $2; }
+	| '.' method '(' ')'			{ $$ = makeItemType($2); }
+	| '?' '(' predicate ')'			{ $$ = makeItemUnary(jpiFilter, $3); }
+	;
+
+key:
+	key_name						{ $$ = makeItemKey(&$1); }
+	;
+
+key_name:
+	IDENT_P
+	| STRING_P
+	| TO_P
+	| NULL_P
+	| TRUE_P
+	| FALSE_P
+	| IS_P
+	| UNKNOWN_P
+	| EXISTS_P
+	| STRICT_P
+	| LAX_P
+	| ABS_P
+	| SIZE_P
+	| TYPE_P
+	| FLOOR_P
+	| DOUBLE_P
+	| CEILING_P
+	| KEYVALUE_P
+	| LAST_P
+	| STARTS_P
+	| WITH_P
+	| LIKE_REGEX_P
+	| FLAG_P
+	;
+
+method:
+	ABS_P							{ $$ = jpiAbs; }
+	| SIZE_P						{ $$ = jpiSize; }
+	| TYPE_P						{ $$ = jpiType; }
+	| FLOOR_P						{ $$ = jpiFloor; }
+	| DOUBLE_P						{ $$ = jpiDouble; }
+	| CEILING_P						{ $$ = jpiCeiling; }
+	| KEYVALUE_P					{ $$ = jpiKeyValue; }
+	;
+%%
+
diff --git a/src/backend/utils/adt/jsonpath_scan.l b/src/backend/utils/adt/jsonpath_scan.l
new file mode 100644
index 0000000..110ea21
--- /dev/null
+++ b/src/backend/utils/adt/jsonpath_scan.l
@@ -0,0 +1,638 @@
+/*-------------------------------------------------------------------------
+ *
+ * jsonpath_scan.l
+ *	Lexical parser for jsonpath datatype
+ *
+ * Copyright (c) 2019, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ *	src/backend/utils/adt/jsonpath_scan.l
+ *
+ *-------------------------------------------------------------------------
+ */
+
+%{
+#include "postgres.h"
+
+#include "mb/pg_wchar.h"
+#include "nodes/pg_list.h"
+#include "utils/jsonpath_scanner.h"
+
+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 void parseUnicode(char *s, int l);
+static void parseHexChars(char *s, int l);
+
+/* 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)));
+}
+
+#define yyerror jsonpath_yyerror
+%}
+
+%option 8bit
+%option never-interactive
+%option nodefault
+%option noinput
+%option nounput
+%option noyywrap
+%option warn
+%option prefix="jsonpath_yy"
+%option bison-bridge
+%option noyyalloc
+%option noyyrealloc
+%option noyyfree
+
+%x xQUOTED
+%x xNONQUOTED
+%x xVARQUOTED
+%x xSINGLEQUOTED
+%x xCOMMENT
+
+special		 [\?\%\$\.\[\]\{\}\(\)\|\&\!\=\<\>\@\#\,\*:\-\+\/]
+any			[^\?\%\$\.\[\]\{\}\(\)\|\&\!\=\<\>\@\#\,\*:\-\+\/\\\"\' \t\n\r\f]
+blank		[ \t\n\r\f]
+hex_dig		[0-9A-Fa-f]
+unicode		\\u({hex_dig}{4}|\{{hex_dig}{1,6}\})
+hex_char	\\x{hex_dig}{2}
+
+
+%%
+
+<INITIAL>\&\&					{ return AND_P; }
+
+<INITIAL>\|\|					{ return OR_P; }
+
+<INITIAL>\!						{ return NOT_P; }
+
+<INITIAL>\*\*					{ return ANY_P; }
+
+<INITIAL>\<						{ return LESS_P; }
+
+<INITIAL>\<\=					{ return LESSEQUAL_P; }
+
+<INITIAL>\=\=					{ return EQUAL_P; }
+
+<INITIAL>\<\>					{ return NOTEQUAL_P; }
+
+<INITIAL>\!\=					{ return NOTEQUAL_P; }
+
+<INITIAL>\>\=					{ return GREATEREQUAL_P; }
+
+<INITIAL>\>						{ return GREATER_P; }
+
+<INITIAL>\${any}+				{
+									addstring(true, yytext + 1, yyleng - 1);
+									addchar(false, '\0');
+									yylval->str = scanstring;
+									return VARIABLE_P;
+								}
+
+<INITIAL>\$\"					{
+									addchar(true, '\0');
+									BEGIN xVARQUOTED;
+								}
+
+<INITIAL>{special}				{ return *yytext; }
+
+<INITIAL>{blank}+				{ /* ignore */ }
+
+<INITIAL>\/\*					{
+									addchar(true, '\0');
+									BEGIN xCOMMENT;
+								}
+
+<INITIAL>[0-9]+(\.[0-9]+)?[eE][+-]?[0-9]+  /* float */  {
+									addstring(true, yytext, yyleng);
+									addchar(false, '\0');
+									yylval->str = scanstring;
+									return NUMERIC_P;
+								}
+
+<INITIAL>\.[0-9]+[eE][+-]?[0-9]+  /* float */  {
+									addstring(true, yytext, yyleng);
+									addchar(false, '\0');
+									yylval->str = scanstring;
+									return NUMERIC_P;
+								}
+
+<INITIAL>([0-9]+)?\.[0-9]+		{
+									addstring(true, yytext, yyleng);
+									addchar(false, '\0');
+									yylval->str = scanstring;
+									return NUMERIC_P;
+								}
+
+<INITIAL>[0-9]+					{
+									addstring(true, yytext, yyleng);
+									addchar(false, '\0');
+									yylval->str = scanstring;
+									return INT_P;
+								}
+
+<INITIAL>{any}+					{
+									addstring(true, yytext, yyleng);
+									BEGIN xNONQUOTED;
+								}
+
+<INITIAL>\"						{
+									addchar(true, '\0');
+									BEGIN xQUOTED;
+								}
+
+<INITIAL>\'						{
+									addchar(true, '\0');
+									BEGIN xSINGLEQUOTED;
+								}
+
+<INITIAL>\\						{
+									yyless(0);
+									addchar(true, '\0');
+									BEGIN xNONQUOTED;
+								}
+
+<xNONQUOTED>{any}+				{
+									addstring(false, yytext, yyleng);
+								}
+
+<xNONQUOTED>{blank}+			{
+									yylval->str = scanstring;
+									BEGIN INITIAL;
+									return checkSpecialVal();
+								}
+
+
+<xNONQUOTED>\/\*				{
+									yylval->str = scanstring;
+									BEGIN xCOMMENT;
+								}
+
+<xNONQUOTED>({special}|\"|\')	{
+									yylval->str = scanstring;
+									yyless(0);
+									BEGIN INITIAL;
+									return checkSpecialVal();
+								}
+
+<xNONQUOTED><<EOF>>				{
+									yylval->str = scanstring;
+									BEGIN INITIAL;
+									return checkSpecialVal();
+								}
+
+<xNONQUOTED,xQUOTED,xVARQUOTED,xSINGLEQUOTED>\\[\"\'\\]	{ addchar(false, yytext[1]); }
+
+<xNONQUOTED,xQUOTED,xVARQUOTED,xSINGLEQUOTED>\\b	{ addchar(false, '\b'); }
+
+<xNONQUOTED,xQUOTED,xVARQUOTED,xSINGLEQUOTED>\\f	{ addchar(false, '\f'); }
+
+<xNONQUOTED,xQUOTED,xVARQUOTED,xSINGLEQUOTED>\\n	{ addchar(false, '\n'); }
+
+<xNONQUOTED,xQUOTED,xVARQUOTED,xSINGLEQUOTED>\\r	{ addchar(false, '\r'); }
+
+<xNONQUOTED,xQUOTED,xVARQUOTED,xSINGLEQUOTED>\\t	{ addchar(false, '\t'); }
+
+<xNONQUOTED,xQUOTED,xVARQUOTED,xSINGLEQUOTED>\\v	{ addchar(false, '\v'); }
+
+<xNONQUOTED,xQUOTED,xVARQUOTED,xSINGLEQUOTED>{unicode}+		{ parseUnicode(yytext, yyleng); }
+
+<xNONQUOTED,xQUOTED,xVARQUOTED,xSINGLEQUOTED>{hex_char}+	{ parseHexChars(yytext, yyleng); }
+
+<xNONQUOTED,xQUOTED,xVARQUOTED,xSINGLEQUOTED>\\x	{ yyerror(NULL, "Hex character sequence is invalid"); }
+
+<xNONQUOTED,xQUOTED,xVARQUOTED,xSINGLEQUOTED>\\u	{ yyerror(NULL, "Unicode sequence is invalid"); }
+
+<xNONQUOTED,xQUOTED,xVARQUOTED,xSINGLEQUOTED>\\.	{ yyerror(NULL, "Escape sequence is invalid"); }
+
+<xNONQUOTED,xQUOTED,xVARQUOTED,xSINGLEQUOTED>\\		{ yyerror(NULL, "Unexpected end after backslash"); }
+
+<xQUOTED,xVARQUOTED,xSINGLEQUOTED><<EOF>>			{ yyerror(NULL, "Unexpected end of quoted string"); }
+
+<xQUOTED>\"						{
+									yylval->str = scanstring;
+									BEGIN INITIAL;
+									return STRING_P;
+								}
+
+<xVARQUOTED>\"					{
+									yylval->str = scanstring;
+									BEGIN INITIAL;
+									return VARIABLE_P;
+								}
+
+<xSINGLEQUOTED>\'				{
+									yylval->str = scanstring;
+									BEGIN INITIAL;
+									return STRING_P;
+								}
+
+<xQUOTED,xVARQUOTED>[^\\\"]+	{ addstring(false, yytext, yyleng); }
+
+<xSINGLEQUOTED>[^\\\']+			{ addstring(false, yytext, yyleng); }
+
+<INITIAL><<EOF>>				{ yyterminate(); }
+
+<xCOMMENT>\*\/					{ BEGIN INITIAL; }
+
+<xCOMMENT>[^\*]+				{ }
+
+<xCOMMENT>\*					{ }
+
+<xCOMMENT><<EOF>>				{ yyerror(NULL, "Unexpected end of comment"); }
+
+%%
+
+void
+jsonpath_yyerror(JsonPathParseResult **result, const char *message)
+{
+	if (*yytext == YY_END_OF_BUFFER_CHAR)
+	{
+		ereport(ERROR,
+				(errcode(ERRCODE_SYNTAX_ERROR),
+				 errmsg("bad jsonpath representation"),
+				 /* translator: %s is typically "syntax error" */
+				 errdetail("%s at end of input", message)));
+	}
+	else
+	{
+		ereport(ERROR,
+				(errcode(ERRCODE_SYNTAX_ERROR),
+				 errmsg("bad jsonpath representation"),
+				 /* translator: first %s is typically "syntax error" */
+				 errdetail("%s at or near \"%s\"", message, yytext)));
+	}
+}
+
+typedef struct keyword
+{
+	int16	len;
+	bool	lowercase;
+	int		val;
+	char	*keyword;
+} keyword;
+
+/*
+ * Array of key words should be sorted by length and then
+ * alphabetical order
+ */
+
+static keyword keywords[] = {
+	{ 2, false,	IS_P,		"is"},
+	{ 2, false,	TO_P,		"to"},
+	{ 3, false,	ABS_P,		"abs"},
+	{ 3, false,	LAX_P,		"lax"},
+	{ 4, false,	FLAG_P,		"flag"},
+	{ 4, false,	LAST_P,		"last"},
+	{ 4, true,	NULL_P,		"null"},
+	{ 4, false,	SIZE_P,		"size"},
+	{ 4, true,	TRUE_P,		"true"},
+	{ 4, false,	TYPE_P,		"type"},
+	{ 4, false,	WITH_P,		"with"},
+	{ 5, true,	FALSE_P,	"false"},
+	{ 5, false,	FLOOR_P,	"floor"},
+	{ 6, false,	DOUBLE_P,	"double"},
+	{ 6, false,	EXISTS_P,	"exists"},
+	{ 6, false,	STARTS_P,	"starts"},
+	{ 6, false,	STRICT_P,	"strict"},
+	{ 7, false,	CEILING_P,	"ceiling"},
+	{ 7, false,	UNKNOWN_P,	"unknown"},
+	{ 8, false,	KEYVALUE_P,	"keyvalue"},
+	{ 10,false, LIKE_REGEX_P, "like_regex"},
+};
+
+static int
+checkSpecialVal()
+{
+	int			res = IDENT_P;
+	int			diff;
+	keyword		*StopLow = keywords,
+				*StopHigh = keywords + lengthof(keywords),
+				*StopMiddle;
+
+	if (scanstring.len > keywords[lengthof(keywords) - 1].len)
+		return res;
+
+	while(StopLow < StopHigh)
+	{
+		StopMiddle = StopLow + ((StopHigh - StopLow) >> 1);
+
+		if (StopMiddle->len == scanstring.len)
+			diff = pg_strncasecmp(StopMiddle->keyword, scanstring.val,
+								  scanstring.len);
+		else
+			diff = StopMiddle->len - scanstring.len;
+
+		if (diff < 0)
+			StopLow = StopMiddle + 1;
+		else if (diff > 0)
+			StopHigh = StopMiddle;
+		else
+		{
+			if (StopMiddle->lowercase)
+				diff = strncmp(StopMiddle->keyword, scanstring.val,
+							   scanstring.len);
+
+			if (diff == 0)
+				res = StopMiddle->val;
+
+			break;
+		}
+	}
+
+	return res;
+}
+
+/*
+ * Called before any actual parsing is done
+ */
+static void
+jsonpath_scanner_init(const char *str, int slen)
+{
+	if (slen <= 0)
+		slen = strlen(str);
+
+	/*
+	 * Might be left over after ereport()
+	 */
+	yy_init_globals();
+
+	/*
+	 * 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 jsonpath_scanner_init()
+ */
+static void
+jsonpath_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++;
+}
+
+JsonPathParseResult *
+parsejsonpath(const char *str, int len)
+{
+	JsonPathParseResult	*parseresult;
+
+	jsonpath_scanner_init(str, len);
+
+	if (jsonpath_yyparse((void*)&parseresult) != 0)
+		jsonpath_yyerror(NULL, "bugus input");
+
+	jsonpath_scanner_finish();
+
+	return parseresult;
+}
+
+static int
+hexval(char c)
+{
+	if (c >= '0' && c <= '9')
+		return c - '0';
+	if (c >= 'a' && c <= 'f')
+		return c - 'a' + 0xA;
+	if (c >= 'A' && c <= 'F')
+		return c - 'A' + 0xA;
+	elog(ERROR, "invalid hexadecimal digit");
+	return 0; /* not reached */
+}
+
+static void
+addUnicodeChar(int ch)
+{
+	/*
+	 * For UTF8, replace the escape sequence by the actual
+	 * utf8 character in lex->strval. Do this also for other
+	 * encodings if the escape designates an ASCII character,
+	 * otherwise raise an error.
+	 */
+
+	if (ch == 0)
+	{
+		/* We can't allow this, since our TEXT type doesn't */
+		ereport(ERROR,
+				(errcode(ERRCODE_UNTRANSLATABLE_CHARACTER),
+				 errmsg("unsupported Unicode escape sequence"),
+				  errdetail("\\u0000 cannot be converted to text.")));
+	}
+	else if (GetDatabaseEncoding() == PG_UTF8)
+	{
+		char utf8str[5];
+		int utf8len;
+
+		unicode_to_utf8(ch, (unsigned char *) utf8str);
+		utf8len = pg_utf_mblen((unsigned char *) utf8str);
+		addstring(false, utf8str, utf8len);
+	}
+	else if (ch <= 0x007f)
+	{
+		/*
+		 * This is the only way to designate things like a
+		 * form feed character in JSON, so it's useful in all
+		 * encodings.
+		 */
+		addchar(false, (char) ch);
+	}
+	else
+	{
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
+				 errmsg("invalid input syntax for type jsonpath"),
+				 errdetail("Unicode escape values cannot be used for code "
+						   "point values above 007F when the server encoding "
+						   "is not UTF8.")));
+	}
+}
+
+static void
+addUnicode(int ch, int *hi_surrogate)
+{
+	if (ch >= 0xd800 && ch <= 0xdbff)
+	{
+		if (*hi_surrogate != -1)
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
+					 errmsg("invalid input syntax for type jsonpath"),
+					 errdetail("Unicode high surrogate must not follow "
+							   "a high surrogate.")));
+		*hi_surrogate = (ch & 0x3ff) << 10;
+		return;
+	}
+	else if (ch >= 0xdc00 && ch <= 0xdfff)
+	{
+		if (*hi_surrogate == -1)
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
+					 errmsg("invalid input syntax for type jsonpath"),
+					 errdetail("Unicode low surrogate must follow a high "
+							   "surrogate.")));
+		ch = 0x10000 + *hi_surrogate + (ch & 0x3ff);
+		*hi_surrogate = -1;
+	}
+	else if (*hi_surrogate != -1)
+	{
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
+				 errmsg("invalid input syntax for type jsonpath"),
+				 errdetail("Unicode low surrogate must follow a high "
+						   "surrogate.")));
+	}
+
+	addUnicodeChar(ch);
+}
+
+/*
+ * parseUnicode was adopted from json_lex_string() in
+ * src/backend/utils/adt/json.c
+ */
+static void
+parseUnicode(char *s, int l)
+{
+	int			i;
+	int			hi_surrogate = -1;
+
+	for (i = 2; i < l; i += 2)	/* skip '\u' */
+	{
+		int			ch = 0;
+		int			j;
+
+		if (s[i] == '{')	/* parse '\u{XX...}' */
+		{
+			while (s[++i] != '}' && i < l)
+				ch = (ch << 4) | hexval(s[i]);
+			i++;	/* ski p '}' */
+		}
+		else		/* parse '\uXXXX' */
+		{
+			for (j = 0; j < 4 && i < l; j++)
+				ch = (ch << 4) | hexval(s[i++]);
+		}
+
+		addUnicode(ch, &hi_surrogate);
+	}
+
+	if (hi_surrogate != -1)
+	{
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
+				 errmsg("invalid input syntax for type jsonpath"),
+				 errdetail("Unicode low surrogate must follow a high "
+						   "surrogate.")));
+	}
+}
+
+static void
+parseHexChars(char *s, int l)
+{
+	int i;
+
+	Assert(l % 4 /* \xXX */ == 0);
+
+	for (i = 0; i < l / 4; i++)
+	{
+		int			ch = (hexval(s[i * 4 + 2]) << 4) | hexval(s[i * 4 + 3]);
+
+		addUnicodeChar(ch);
+	}
+}
+
+/*
+ * Interface functions to make flex use palloc() instead of malloc().
+ * It'd be better to make these static, but flex insists otherwise.
+ */
+
+void *
+jsonpath_yyalloc(yy_size_t bytes)
+{
+	return palloc(bytes);
+}
+
+void *
+jsonpath_yyrealloc(void *ptr, yy_size_t bytes)
+{
+	if (ptr)
+		return repalloc(ptr, bytes);
+	else
+		return palloc(bytes);
+}
+
+void
+jsonpath_yyfree(void *ptr)
+{
+	if (ptr)
+		pfree(ptr);
+}
+
diff --git a/src/backend/utils/adt/regexp.c b/src/backend/utils/adt/regexp.c
index 4ef8a92..da13a87 100644
--- a/src/backend/utils/adt/regexp.c
+++ b/src/backend/utils/adt/regexp.c
@@ -133,7 +133,7 @@ static Datum build_regexp_split_result(regexp_matches_ctx *splitctx);
  * Pattern is given in the database encoding.  We internally convert to
  * an array of pg_wchar, which is what Spencer's regex package wants.
  */
-static regex_t *
+regex_t *
 RE_compile_and_cache(text *text_re, int cflags, Oid collation)
 {
 	int			text_re_len = VARSIZE_ANY_EXHDR(text_re);
@@ -339,7 +339,7 @@ RE_execute(regex_t *re, char *dat, int dat_len,
  * Both pattern and data are given in the database encoding.  We internally
  * convert to array of pg_wchar which is what Spencer's regex package wants.
  */
-static bool
+bool
 RE_compile_and_execute(text *text_re, char *dat, int dat_len,
 					   int cflags, Oid collation,
 					   int nmatch, regmatch_t *pmatch)
diff --git a/src/backend/utils/errcodes.txt b/src/backend/utils/errcodes.txt
index 4f7b9b6..16f5ca2 100644
--- a/src/backend/utils/errcodes.txt
+++ b/src/backend/utils/errcodes.txt
@@ -206,6 +206,21 @@ Section: Class 22 - Data Exception
 2200N    E    ERRCODE_INVALID_XML_CONTENT                                    invalid_xml_content
 2200S    E    ERRCODE_INVALID_XML_COMMENT                                    invalid_xml_comment
 2200T    E    ERRCODE_INVALID_XML_PROCESSING_INSTRUCTION                     invalid_xml_processing_instruction
+22030    E    ERRCODE_DUPLICATE_JSON_OBJECT_KEY_VALUE                        duplicate_json_object_key_value
+22032    E    ERRCODE_INVALID_JSON_TEXT                                      invalid_json_text
+22033    E    ERRCODE_INVALID_JSON_SUBSCRIPT                                 invalid_json_subscript
+22034    E    ERRCODE_MORE_THAN_ONE_JSON_ITEM                                more_than_one_json_item
+22035    E    ERRCODE_NO_JSON_ITEM                                           no_json_item
+22036    E    ERRCODE_NON_NUMERIC_JSON_ITEM                                  non_numeric_json_item
+22037    E    ERRCODE_NON_UNIQUE_KEYS_IN_JSON_OBJECT                         non_unique_keys_in_json_object
+22038    E    ERRCODE_SINGLETON_JSON_ITEM_REQUIRED                           singleton_json_item_required
+22039    E    ERRCODE_JSON_ARRAY_NOT_FOUND                                   json_array_not_found
+2203A    E    ERRCODE_JSON_MEMBER_NOT_FOUND                                  json_member_not_found
+2203B    E    ERRCODE_JSON_NUMBER_NOT_FOUND                                  json_number_not_found
+2203C    E    ERRCODE_JSON_OBJECT_NOT_FOUND                                  object_not_found
+2203F    E    ERRCODE_JSON_SCALAR_REQUIRED                                   json_scalar_required
+2203D    E    ERRCODE_TOO_MANY_JSON_ARRAY_ELEMENTS                           too_many_json_array_elements
+2203E    E    ERRCODE_TOO_MANY_JSON_OBJECT_MEMBERS                           too_many_json_object_members
 
 Section: Class 23 - Integrity Constraint Violation
 
diff --git a/src/include/catalog/pg_operator.dat b/src/include/catalog/pg_operator.dat
index 06aec07..1c7af92 100644
--- a/src/include/catalog/pg_operator.dat
+++ b/src/include/catalog/pg_operator.dat
@@ -3255,5 +3255,13 @@
 { oid => '3287', descr => 'delete path',
   oprname => '#-', oprleft => 'jsonb', oprright => '_text',
   oprresult => 'jsonb', oprcode => 'jsonb_delete_path' },
+{ oid => '6076', descr => 'jsonpath exists',
+  oprname => '@?', oprleft => 'jsonb', oprright => 'jsonpath',
+  oprresult => 'bool', oprcode => 'jsonb_path_exists(jsonb,jsonpath)',
+  oprrest => 'contsel', oprjoin => 'contjoinsel' },
+{ oid => '6107', descr => 'jsonpath match',
+  oprname => '@@', oprleft => 'jsonb', oprright => 'jsonpath',
+  oprresult => 'bool', oprcode => 'jsonb_path_match(jsonb,jsonpath)',
+  oprrest => 'contsel', oprjoin => 'contjoinsel' },
 
 ]
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index a4e173b..9a7a5db 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -9185,6 +9185,45 @@
   proname => 'jsonb_insert', prorettype => 'jsonb',
   proargtypes => 'jsonb _text jsonb bool', prosrc => 'jsonb_insert' },
 
+# jsonpath
+{ oid => '6048', descr => 'I/O',
+  proname => 'jsonpath_in', prorettype => 'jsonpath', proargtypes => 'cstring',
+  prosrc => 'jsonpath_in' },
+{ oid => '6049', descr => 'I/O',
+  proname => 'jsonpath_recv', prorettype => 'jsonpath', proargtypes => 'internal',
+  prosrc => 'jsonpath_recv' },
+{ oid => '6052', descr => 'I/O',
+  proname => 'jsonpath_out', prorettype => 'cstring', proargtypes => 'jsonpath',
+  prosrc => 'jsonpath_out' },
+{ oid => '6053', descr => 'I/O',
+  proname => 'jsonpath_send', prorettype => 'bytea', proargtypes => 'jsonpath',
+  prosrc => 'jsonpath_send' },
+
+{ oid => '6054', descr => 'jsonpath exists test',
+  proname => 'jsonb_path_exists', prorettype => 'bool',
+  proargtypes => 'jsonb jsonpath jsonb bool', prosrc => 'jsonb_path_exists' },
+{ oid => '6055', descr => 'jsonpath query',
+  proname => 'jsonb_path_query', prorows => '1000', proretset => 't',
+  prorettype => 'jsonb', proargtypes => 'jsonb jsonpath jsonb bool',
+  prosrc => 'jsonb_path_query' },
+{ oid => '6056', descr => 'jsonpath query wrapped into array',
+  proname => 'jsonb_path_query_array', prorettype => 'jsonb',
+  proargtypes => 'jsonb jsonpath jsonb bool',
+  prosrc => 'jsonb_path_query_array' },
+{ oid => '6057', descr => 'jsonpath query first item',
+  proname => 'jsonb_path_query_first', prorettype => 'jsonb',
+  proargtypes => 'jsonb jsonpath jsonb bool', prosrc => 'jsonb_path_query_first' },
+{ oid => '6058', descr => 'jsonpath match', proname => 'jsonb_path_match',
+  prorettype => 'bool', proargtypes => 'jsonb jsonpath jsonb bool',
+  prosrc => 'jsonb_path_match' },
+
+{ oid => '6059', descr => 'implementation of @? operator',
+  proname => 'jsonb_path_exists', prorettype => 'bool',
+  proargtypes => 'jsonb jsonpath', prosrc => 'jsonb_path_exists_opr' },
+{ oid => '6060', descr => 'implementation of @@ operator',
+  proname => 'jsonb_path_match', prorettype => 'bool',
+  proargtypes => 'jsonb jsonpath', prosrc => 'jsonb_path_match_opr' },
+
 # txid
 { oid => '2939', descr => 'I/O',
   proname => 'txid_snapshot_in', prorettype => 'txid_snapshot',
diff --git a/src/include/catalog/pg_type.dat b/src/include/catalog/pg_type.dat
index 4b7750d..e44c562 100644
--- a/src/include/catalog/pg_type.dat
+++ b/src/include/catalog/pg_type.dat
@@ -441,6 +441,11 @@
   typname => 'jsonb', typlen => '-1', typbyval => 'f', typcategory => 'U',
   typinput => 'jsonb_in', typoutput => 'jsonb_out', typreceive => 'jsonb_recv',
   typsend => 'jsonb_send', typalign => 'i', typstorage => 'x' },
+{ oid =>  '6050', array_type_oid => '6051', descr => 'JSON path',
+  typname => 'jsonpath', typlen => '-1', typbyval => 'f', typcategory => 'U',
+  typarray => '_jsonpath', typinput => 'jsonpath_in',
+  typoutput => 'jsonpath_out', typreceive => '-', typsend => '-',
+  typalign => 'i', typstorage => 'x' },
 
 { oid => '2970', array_type_oid => '2949', descr => 'txid snapshot',
   typname => 'txid_snapshot', typlen => '-1', typbyval => 'f',
diff --git a/src/include/regex/regex.h b/src/include/regex/regex.h
index 27fdc09..23ad03d 100644
--- a/src/include/regex/regex.h
+++ b/src/include/regex/regex.h
@@ -167,10 +167,18 @@ typedef struct
 /*
  * the prototypes for exported functions
  */
+
+/* regcomp.c */
 extern int	pg_regcomp(regex_t *, const pg_wchar *, size_t, int, Oid);
 extern int	pg_regexec(regex_t *, const pg_wchar *, size_t, size_t, rm_detail_t *, size_t, regmatch_t[], int);
 extern int	pg_regprefix(regex_t *, pg_wchar **, size_t *);
 extern void pg_regfree(regex_t *);
 extern size_t pg_regerror(int, const regex_t *, char *, size_t);
 
+/* regexp.c */
+extern regex_t *RE_compile_and_cache(text *text_re, int cflags, Oid collation);
+extern bool RE_compile_and_execute(text *text_re, char *dat, int dat_len,
+					   int cflags, Oid collation,
+					   int nmatch, regmatch_t *pmatch);
+
 #endif							/* _REGEX_H_ */
diff --git a/src/include/utils/.gitignore b/src/include/utils/.gitignore
index 05cfa7a..e0705e1 100644
--- a/src/include/utils/.gitignore
+++ b/src/include/utils/.gitignore
@@ -3,3 +3,4 @@
 /probes.h
 /errcodes.h
 /header-stamp
+/jsonpath_gram.h
diff --git a/src/include/utils/jsonb.h b/src/include/utils/jsonb.h
index 6ccacf5..ec0355f 100644
--- a/src/include/utils/jsonb.h
+++ b/src/include/utils/jsonb.h
@@ -66,8 +66,10 @@ typedef enum
 
 /* Convenience macros */
 #define DatumGetJsonbP(d)	((Jsonb *) PG_DETOAST_DATUM(d))
+#define DatumGetJsonbPCopy(d)	((Jsonb *) PG_DETOAST_DATUM_COPY(d))
 #define JsonbPGetDatum(p)	PointerGetDatum(p)
 #define PG_GETARG_JSONB_P(x)	DatumGetJsonbP(PG_GETARG_DATUM(x))
+#define PG_GETARG_JSONB_P_COPY(x)	DatumGetJsonbPCopy(PG_GETARG_DATUM(x))
 #define PG_RETURN_JSONB_P(x)	PG_RETURN_POINTER(x)
 
 typedef struct JsonbPair JsonbPair;
@@ -378,6 +380,8 @@ extern char *JsonbToCString(StringInfo out, JsonbContainer *in,
 			   int estimated_len);
 extern char *JsonbToCStringIndent(StringInfo out, JsonbContainer *in,
 					 int estimated_len);
+extern bool JsonbExtractScalar(JsonbContainer *jbc, JsonbValue *res);
+extern const char *JsonbTypeName(JsonbValue *jb);
 
 
 #endif							/* __JSONB_H__ */
diff --git a/src/include/utils/jsonpath.h b/src/include/utils/jsonpath.h
new file mode 100644
index 0000000..14f837e
--- /dev/null
+++ b/src/include/utils/jsonpath.h
@@ -0,0 +1,245 @@
+/*-------------------------------------------------------------------------
+ *
+ * jsonpath.h
+ *	Definitions for jsonpath datatype
+ *
+ * Copyright (c) 2019, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ *	src/include/utils/jsonpath.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef JSONPATH_H
+#define JSONPATH_H
+
+#include "fmgr.h"
+#include "utils/jsonb.h"
+#include "nodes/pg_list.h"
+
+typedef struct
+{
+	int32		vl_len_;		/* varlena header (do not touch directly!) */
+	uint32		header;			/* version and flags (see below) */
+	char		data[FLEXIBLE_ARRAY_MEMBER];
+} JsonPath;
+
+#define JSONPATH_VERSION	(0x01)
+#define JSONPATH_LAX		(0x80000000)
+#define JSONPATH_HDRSZ		(offsetof(JsonPath, data))
+
+#define DatumGetJsonPathP(d)			((JsonPath *) DatumGetPointer(PG_DETOAST_DATUM(d)))
+#define DatumGetJsonPathPCopy(d)		((JsonPath *) DatumGetPointer(PG_DETOAST_DATUM_COPY(d)))
+#define PG_GETARG_JSONPATH_P(x)			DatumGetJsonPathP(PG_GETARG_DATUM(x))
+#define PG_GETARG_JSONPATH_P_COPY(x)	DatumGetJsonPathPCopy(PG_GETARG_DATUM(x))
+#define PG_RETURN_JSONPATH_P(p)			PG_RETURN_POINTER(p)
+
+/*
+ * All node's type of jsonpath expression
+ */
+typedef enum JsonPathItemType
+{
+	jpiNull = jbvNull,			/* NULL literal */
+	jpiString = jbvString,		/* string literal */
+	jpiNumeric = jbvNumeric,	/* numeric literal */
+	jpiBool = jbvBool,			/* boolean literal: TRUE or FALSE */
+	jpiAnd,						/* predicate && predicate */
+	jpiOr,						/* predicate || predicate */
+	jpiNot,						/* ! predicate */
+	jpiIsUnknown,				/* (predicate) IS UNKNOWN */
+	jpiEqual,					/* expr == expr */
+	jpiNotEqual,				/* expr != expr */
+	jpiLess,					/* expr < expr */
+	jpiGreater,					/* expr > expr */
+	jpiLessOrEqual,				/* expr <= expr */
+	jpiGreaterOrEqual,			/* expr >= expr */
+	jpiAdd,						/* expr + expr */
+	jpiSub,						/* expr - expr */
+	jpiMul,						/* expr * expr */
+	jpiDiv,						/* expr / expr */
+	jpiMod,						/* expr % expr */
+	jpiPlus,					/* + expr */
+	jpiMinus,					/* - expr */
+	jpiAnyArray,				/* [*] */
+	jpiAnyKey,					/* .* */
+	jpiIndexArray,				/* [subscript, ...] */
+	jpiAny,						/* .** */
+	jpiKey,						/* .key */
+	jpiCurrent,					/* @ */
+	jpiRoot,					/* $ */
+	jpiVariable,				/* $variable */
+	jpiFilter,					/* ? (predicate) */
+	jpiExists,					/* EXISTS (expr) predicate */
+	jpiType,					/* .type() item method */
+	jpiSize,					/* .size() item method */
+	jpiAbs,						/* .abs() item method */
+	jpiFloor,					/* .floor() item method */
+	jpiCeiling,					/* .ceiling() item method */
+	jpiDouble,					/* .double() item method */
+	jpiKeyValue,				/* .keyvalue() item method */
+	jpiSubscript,				/* array subscript: 'expr' or 'expr TO expr' */
+	jpiLast,					/* LAST array subscript */
+	jpiStartsWith,				/* STARTS WITH predicate */
+	jpiLikeRegex,				/* LIKE_REGEX predicate */
+} JsonPathItemType;
+
+/* XQuery regex mode flags for LIKE_REGEX predicate */
+#define JSP_REGEX_ICASE		0x01	/* i flag, case insensitive */
+#define JSP_REGEX_SLINE		0x02	/* s flag, single-line mode */
+#define JSP_REGEX_MLINE		0x04	/* m flag, multi-line mode */
+#define JSP_REGEX_WSPACE	0x08	/* x flag, expanded syntax */
+
+/*
+ * Support functions to parse/construct binary value.
+ * Unlike many other representation of expression the first/main
+ * node is not an operation but left operand of expression. That
+ * allows to implement cheep follow-path descending in jsonb
+ * structure and then execute operator with right operand
+ */
+
+typedef struct JsonPathItem
+{
+	JsonPathItemType type;
+
+	/* position form base to next node */
+	int32		nextPos;
+
+	/*
+	 * pointer into JsonPath value to current node, all positions of current
+	 * are relative to this base
+	 */
+	char	   *base;
+
+	union
+	{
+		/* classic operator with two operands: and, or etc */
+		struct
+		{
+			int32		left;
+			int32		right;
+		}			args;
+
+		/* any unary operation */
+		int32		arg;
+
+		/* storage for jpiIndexArray: indexes of array */
+		struct
+		{
+			int32		nelems;
+			struct
+			{
+				int32		from;
+				int32		to;
+			}		   *elems;
+		}			array;
+
+		/* jpiAny: levels */
+		struct
+		{
+			uint32		first;
+			uint32		last;
+		}			anybounds;
+
+		struct
+		{
+			char	   *data;	/* for bool, numeric and string/key */
+			int32		datalen;	/* filled only for string/key */
+		}			value;
+
+		struct
+		{
+			int32		expr;
+			char	   *pattern;
+			int32		patternlen;
+			uint32		flags;
+		}			like_regex;
+	}			content;
+} JsonPathItem;
+
+#define jspHasNext(jsp) ((jsp)->nextPos > 0)
+
+extern void jspInit(JsonPathItem *v, JsonPath *js);
+extern void jspInitByBuffer(JsonPathItem *v, char *base, int32 pos);
+extern bool jspGetNext(JsonPathItem *v, JsonPathItem *a);
+extern void jspGetArg(JsonPathItem *v, JsonPathItem *a);
+extern void jspGetLeftArg(JsonPathItem *v, JsonPathItem *a);
+extern void jspGetRightArg(JsonPathItem *v, JsonPathItem *a);
+extern Numeric jspGetNumeric(JsonPathItem *v);
+extern bool jspGetBool(JsonPathItem *v);
+extern char *jspGetString(JsonPathItem *v, int32 *len);
+extern bool jspGetArraySubscript(JsonPathItem *v, JsonPathItem *from,
+					 JsonPathItem *to, int i);
+
+extern const char *jspOperationName(JsonPathItemType type);
+
+/*
+ * Parsing support data structures.
+ */
+
+typedef struct JsonPathParseItem JsonPathParseItem;
+
+struct JsonPathParseItem
+{
+	JsonPathItemType type;
+	JsonPathParseItem *next;	/* next in path */
+
+	union
+	{
+
+		/* classic operator with two operands: and, or etc */
+		struct
+		{
+			JsonPathParseItem *left;
+			JsonPathParseItem *right;
+		}			args;
+
+		/* any unary operation */
+		JsonPathParseItem *arg;
+
+		/* storage for jpiIndexArray: indexes of array */
+		struct
+		{
+			int			nelems;
+			struct
+			{
+				JsonPathParseItem *from;
+				JsonPathParseItem *to;
+			}		   *elems;
+		}			array;
+
+		/* jpiAny: levels */
+		struct
+		{
+			uint32		first;
+			uint32		last;
+		}			anybounds;
+
+		struct
+		{
+			JsonPathParseItem *expr;
+			char	   *pattern;	/* could not be not null-terminated */
+			uint32		patternlen;
+			uint32		flags;
+		}			like_regex;
+
+		/* scalars */
+		Numeric numeric;
+		bool		boolean;
+		struct
+		{
+			uint32		len;
+			char	   *val;	/* could not be not null-terminated */
+		}			string;
+	}			value;
+};
+
+typedef struct JsonPathParseResult
+{
+	JsonPathParseItem *expr;
+	bool		lax;
+} JsonPathParseResult;
+
+extern JsonPathParseResult *parsejsonpath(const char *str, int len);
+
+#endif
diff --git a/src/include/utils/jsonpath_scanner.h b/src/include/utils/jsonpath_scanner.h
new file mode 100644
index 0000000..bbdd984
--- /dev/null
+++ b/src/include/utils/jsonpath_scanner.h
@@ -0,0 +1,32 @@
+/*-------------------------------------------------------------------------
+ *
+ * jsonpath_scanner.h
+ *	Definitions for jsonpath scanner & parser
+ *
+ * Portions Copyright (c) 2019, PostgreSQL Global Development Group
+ *
+ * src/include/utils/jsonpath_scanner.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef JSONPATH_SCANNER_H
+#define JSONPATH_SCANNER_H
+
+/* struct string is shared between scan and gram */
+typedef struct string
+{
+	char	   *val;
+	int			len;
+	int			total;
+}			string;
+
+#include "utils/jsonpath.h"
+#include "utils/jsonpath_gram.h"
+
+/* flex 2.5.4 doesn't bother with a decl for this */
+extern int	jsonpath_yylex(YYSTYPE *yylval_param);
+extern int	jsonpath_yyparse(JsonPathParseResult **result);
+extern void jsonpath_yyerror(JsonPathParseResult **result, const char *message);
+
+#endif
diff --git a/src/test/regress/expected/jsonb_jsonpath.out b/src/test/regress/expected/jsonb_jsonpath.out
new file mode 100644
index 0000000..f295b92
--- /dev/null
+++ b/src/test/regress/expected/jsonb_jsonpath.out
@@ -0,0 +1,1564 @@
+select jsonb '{"a": 12}' @? '$';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"a": 12}' @? '1';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"a": 12}' @? '$.a.b';
+ ?column? 
+----------
+ f
+(1 row)
+
+select jsonb '{"a": 12}' @? '$.b';
+ ?column? 
+----------
+ f
+(1 row)
+
+select jsonb '{"a": 12}' @? '$.a + 2';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"a": 12}' @? '$.b + 2';
+ ?column? 
+----------
+ 
+(1 row)
+
+select jsonb '{"a": {"a": 12}}' @? '$.a.a';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"a": {"a": 12}}' @? '$.*.a';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"b": {"a": 12}}' @? '$.*.a';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"b": {"a": 12}}' @? '$.*.b';
+ ?column? 
+----------
+ f
+(1 row)
+
+select jsonb '{"b": {"a": 12}}' @? 'strict $.*.b';
+ ?column? 
+----------
+ 
+(1 row)
+
+select jsonb '{}' @? '$.*';
+ ?column? 
+----------
+ f
+(1 row)
+
+select jsonb '{"a": 1}' @? '$.*';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"a": {"b": 1}}' @? 'lax $.**{1}';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"a": {"b": 1}}' @? 'lax $.**{2}';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"a": {"b": 1}}' @? 'lax $.**{3}';
+ ?column? 
+----------
+ f
+(1 row)
+
+select jsonb '[]' @? '$[*]';
+ ?column? 
+----------
+ f
+(1 row)
+
+select jsonb '[1]' @? '$[*]';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '[1]' @? '$[1]';
+ ?column? 
+----------
+ f
+(1 row)
+
+select jsonb '[1]' @? 'strict $[1]';
+ ?column? 
+----------
+ 
+(1 row)
+
+select jsonb_path_query('[1]', 'strict $[1]');
+ERROR:  invalid SQL/JSON subscript
+DETAIL:  jsonpath array subscript is out of bounds
+select jsonb '[1]' @? 'lax $[10000000000000000]';
+ERROR:  integer out of range
+select jsonb '[1]' @? 'strict $[10000000000000000]';
+ERROR:  integer out of range
+select jsonb_path_query('[1]', 'lax $[10000000000000000]');
+ERROR:  integer out of range
+select jsonb_path_query('[1]', 'strict $[10000000000000000]');
+ERROR:  integer out of range
+select jsonb '[1]' @? '$[0]';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '[1]' @? '$[0.3]';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '[1]' @? '$[0.5]';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '[1]' @? '$[0.9]';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '[1]' @? '$[1.2]';
+ ?column? 
+----------
+ f
+(1 row)
+
+select jsonb '[1]' @? 'strict $[1.2]';
+ ?column? 
+----------
+ 
+(1 row)
+
+select jsonb '{"a": [1,2,3], "b": [3,4,5]}' @? '$ ? (@.a[*] >  @.b[*])';
+ ?column? 
+----------
+ f
+(1 row)
+
+select jsonb '{"a": [1,2,3], "b": [3,4,5]}' @? '$ ? (@.a[*] >= @.b[*])';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"a": [1,2,3], "b": [3,4,"5"]}' @? '$ ? (@.a[*] >= @.b[*])';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"a": [1,2,3], "b": [3,4,"5"]}' @? 'strict $ ? (@.a[*] >= @.b[*])';
+ ?column? 
+----------
+ f
+(1 row)
+
+select jsonb '{"a": [1,2,3], "b": [3,4,null]}' @? '$ ? (@.a[*] >= @.b[*])';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '1' @? '$ ? ((@ == "1") is unknown)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '1' @? '$ ? ((@ == 1) is unknown)';
+ ?column? 
+----------
+ f
+(1 row)
+
+select jsonb '[{"a": 1}, {"a": 2}]' @? '$[0 to 1] ? (@.a > 1)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb_path_query('1', 'lax $.a');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select jsonb_path_query('1', 'strict $.a');
+ERROR:  SQL/JSON member not found
+DETAIL:  jsonpath member accessor is applied to not an object
+select jsonb_path_query('1', 'strict $.*');
+ERROR:  SQL/JSON object not found
+DETAIL:  jsonpath wildcard member accessor is applied to not an object
+select jsonb_path_query('[]', 'lax $.a');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select jsonb_path_query('[]', 'strict $.a');
+ERROR:  SQL/JSON member not found
+DETAIL:  jsonpath member accessor is applied to not an object
+select jsonb_path_query('{}', 'lax $.a');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select jsonb_path_query('{}', 'strict $.a');
+ERROR:  SQL/JSON member not found
+DETAIL:  JSON object does not contain key "a"
+select jsonb_path_query('1', 'strict $[1]');
+ERROR:  SQL/JSON array not found
+DETAIL:  jsonpath array accessor is applied to not an array
+select jsonb_path_query('1', 'strict $[*]');
+ERROR:  SQL/JSON array not found
+DETAIL:  jsonpath wildcard array accessor is applied to not an array
+select jsonb_path_query('[]', 'strict $[1]');
+ERROR:  invalid SQL/JSON subscript
+DETAIL:  jsonpath array subscript is out of bounds
+select jsonb_path_query('[]', 'strict $["a"]');
+ERROR:  invalid SQL/JSON subscript
+DETAIL:  jsonpath array subscript is not a singleton numeric value
+select jsonb_path_query('{"a": 12, "b": {"a": 13}}', '$.a');
+ jsonb_path_query 
+------------------
+ 12
+(1 row)
+
+select jsonb_path_query('{"a": 12, "b": {"a": 13}}', '$.b');
+ jsonb_path_query 
+------------------
+ {"a": 13}
+(1 row)
+
+select jsonb_path_query('{"a": 12, "b": {"a": 13}}', '$.*');
+ jsonb_path_query 
+------------------
+ 12
+ {"a": 13}
+(2 rows)
+
+select jsonb_path_query('{"a": 12, "b": {"a": 13}}', 'lax $.*.a');
+ jsonb_path_query 
+------------------
+ 13
+(1 row)
+
+select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[*].a');
+ jsonb_path_query 
+------------------
+ 13
+(1 row)
+
+select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[*].*');
+ jsonb_path_query 
+------------------
+ 13
+ 14
+(2 rows)
+
+select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[0].a');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[1].a');
+ jsonb_path_query 
+------------------
+ 13
+(1 row)
+
+select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[2].a');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[0,1].a');
+ jsonb_path_query 
+------------------
+ 13
+(1 row)
+
+select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[0 to 10].a');
+ jsonb_path_query 
+------------------
+ 13
+(1 row)
+
+select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[0 to 10 / 0].a');
+ERROR:  division by zero
+select jsonb_path_query('[12, {"a": 13}, {"b": 14}, "ccc", true]', '$[2.5 - 1 to $.size() - 2]');
+ jsonb_path_query 
+------------------
+ {"a": 13}
+ {"b": 14}
+ "ccc"
+(3 rows)
+
+select jsonb_path_query('1', 'lax $[0]');
+ jsonb_path_query 
+------------------
+ 1
+(1 row)
+
+select jsonb_path_query('1', 'lax $[*]');
+ jsonb_path_query 
+------------------
+ 1
+(1 row)
+
+select jsonb_path_query('[1]', 'lax $[0]');
+ jsonb_path_query 
+------------------
+ 1
+(1 row)
+
+select jsonb_path_query('[1]', 'lax $[*]');
+ jsonb_path_query 
+------------------
+ 1
+(1 row)
+
+select jsonb_path_query('[1,2,3]', 'lax $[*]');
+ jsonb_path_query 
+------------------
+ 1
+ 2
+ 3
+(3 rows)
+
+select jsonb_path_query('[1,2,3]', 'strict $[*].a');
+ERROR:  SQL/JSON member not found
+DETAIL:  jsonpath member accessor is applied to not an object
+select jsonb_path_query('[]', '$[last]');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select jsonb_path_query('[]', '$[last ? (exists(last))]');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select jsonb_path_query('[]', 'strict $[last]');
+ERROR:  invalid SQL/JSON subscript
+DETAIL:  jsonpath array subscript is out of bounds
+select jsonb_path_query('[1]', '$[last]');
+ jsonb_path_query 
+------------------
+ 1
+(1 row)
+
+select jsonb_path_query('[1,2,3]', '$[last]');
+ jsonb_path_query 
+------------------
+ 3
+(1 row)
+
+select jsonb_path_query('[1,2,3]', '$[last - 1]');
+ jsonb_path_query 
+------------------
+ 2
+(1 row)
+
+select jsonb_path_query('[1,2,3]', '$[last ? (@.type() == "number")]');
+ jsonb_path_query 
+------------------
+ 3
+(1 row)
+
+select jsonb_path_query('[1,2,3]', '$[last ? (@.type() == "string")]');
+ERROR:  invalid SQL/JSON subscript
+DETAIL:  jsonpath array subscript is not a singleton numeric value
+select * from jsonb_path_query('{"a": 10}', '$');
+ jsonb_path_query 
+------------------
+ {"a": 10}
+(1 row)
+
+select * from jsonb_path_query('{"a": 10}', '$ ? (@.a < $value)');
+ERROR:  cannot find jsonpath variable 'value'
+select * from jsonb_path_query('{"a": 10}', '$ ? (@.a < $value)', '1');
+ERROR:  jsonb containing jsonpath variables is not an object
+select * from jsonb_path_query('{"a": 10}', '$ ? (@.a < $value)', '[{"value" : 13}]');
+ERROR:  jsonb containing jsonpath variables is not an object
+select * from jsonb_path_query('{"a": 10}', '$ ? (@.a < $value)', '{"value" : 13}');
+ jsonb_path_query 
+------------------
+ {"a": 10}
+(1 row)
+
+select * from jsonb_path_query('{"a": 10}', '$ ? (@.a < $value)', '{"value" : 8}');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select * from jsonb_path_query('{"a": 10}', '$.a ? (@ < $value)', '{"value" : 13}');
+ jsonb_path_query 
+------------------
+ 10
+(1 row)
+
+select * from jsonb_path_query('[10,11,12,13,14,15]', '$[*] ? (@ < $value)', '{"value" : 13}');
+ jsonb_path_query 
+------------------
+ 10
+ 11
+ 12
+(3 rows)
+
+select * from jsonb_path_query('[10,11,12,13,14,15]', '$[0,1] ? (@ < $x.value)', '{"x": {"value" : 13}}');
+ jsonb_path_query 
+------------------
+ 10
+ 11
+(2 rows)
+
+select * from jsonb_path_query('[10,11,12,13,14,15]', '$[0 to 2] ? (@ < $value)', '{"value" : 15}');
+ jsonb_path_query 
+------------------
+ 10
+ 11
+ 12
+(3 rows)
+
+select * from jsonb_path_query('[1,"1",2,"2",null]', '$[*] ? (@ == "1")');
+ jsonb_path_query 
+------------------
+ "1"
+(1 row)
+
+select * from jsonb_path_query('[1,"1",2,"2",null]', '$[*] ? (@ == $value)', '{"value" : "1"}');
+ jsonb_path_query 
+------------------
+ "1"
+(1 row)
+
+select * from jsonb_path_query('[1,"1",2,"2",null]', '$[*] ? (@ == $value)', '{"value" : null}');
+ jsonb_path_query 
+------------------
+ null
+(1 row)
+
+select * from jsonb_path_query('[1, "2", null]', '$[*] ? (@ != null)');
+ jsonb_path_query 
+------------------
+ 1
+ "2"
+(2 rows)
+
+select * from jsonb_path_query('[1, "2", null]', '$[*] ? (@ == null)');
+ jsonb_path_query 
+------------------
+ null
+(1 row)
+
+select * from jsonb_path_query('{}', '$ ? (@ == @)');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select * from jsonb_path_query('[]', 'strict $ ? (@ == @)');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**');
+ jsonb_path_query 
+------------------
+ {"a": {"b": 1}}
+ {"b": 1}
+ 1
+(3 rows)
+
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{0}');
+ jsonb_path_query 
+------------------
+ {"a": {"b": 1}}
+(1 row)
+
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{0 to last}');
+ jsonb_path_query 
+------------------
+ {"a": {"b": 1}}
+ {"b": 1}
+ 1
+(3 rows)
+
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{1}');
+ jsonb_path_query 
+------------------
+ {"b": 1}
+(1 row)
+
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{1 to last}');
+ jsonb_path_query 
+------------------
+ {"b": 1}
+ 1
+(2 rows)
+
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{2}');
+ jsonb_path_query 
+------------------
+ 1
+(1 row)
+
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{2 to last}');
+ jsonb_path_query 
+------------------
+ 1
+(1 row)
+
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{3 to last}');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{last}');
+ jsonb_path_query 
+------------------
+ 1
+(1 row)
+
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**.b ? (@ > 0)');
+ jsonb_path_query 
+------------------
+ 1
+(1 row)
+
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{0}.b ? (@ > 0)');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{1}.b ? (@ > 0)');
+ jsonb_path_query 
+------------------
+ 1
+(1 row)
+
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{0 to last}.b ? (@ > 0)');
+ jsonb_path_query 
+------------------
+ 1
+(1 row)
+
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{1 to last}.b ? (@ > 0)');
+ jsonb_path_query 
+------------------
+ 1
+(1 row)
+
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{1 to 2}.b ? (@ > 0)');
+ jsonb_path_query 
+------------------
+ 1
+(1 row)
+
+select jsonb_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**.b ? (@ > 0)');
+ jsonb_path_query 
+------------------
+ 1
+(1 row)
+
+select jsonb_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{0}.b ? (@ > 0)');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select jsonb_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{1}.b ? (@ > 0)');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select jsonb_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{0 to last}.b ? (@ > 0)');
+ jsonb_path_query 
+------------------
+ 1
+(1 row)
+
+select jsonb_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{1 to last}.b ? (@ > 0)');
+ jsonb_path_query 
+------------------
+ 1
+(1 row)
+
+select jsonb_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{1 to 2}.b ? (@ > 0)');
+ jsonb_path_query 
+------------------
+ 1
+(1 row)
+
+select jsonb_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{2 to 3}.b ? (@ > 0)');
+ jsonb_path_query 
+------------------
+ 1
+(1 row)
+
+select jsonb '{"a": {"b": 1}}' @? '$.**.b ? ( @ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"a": {"b": 1}}' @? '$.**{0}.b ? ( @ > 0)';
+ ?column? 
+----------
+ f
+(1 row)
+
+select jsonb '{"a": {"b": 1}}' @? '$.**{1}.b ? ( @ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"a": {"b": 1}}' @? '$.**{0 to last}.b ? ( @ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"a": {"b": 1}}' @? '$.**{1 to last}.b ? ( @ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"a": {"b": 1}}' @? '$.**{1 to 2}.b ? ( @ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"a": {"c": {"b": 1}}}' @? '$.**.b ? ( @ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"a": {"c": {"b": 1}}}' @? '$.**{0}.b ? ( @ > 0)';
+ ?column? 
+----------
+ f
+(1 row)
+
+select jsonb '{"a": {"c": {"b": 1}}}' @? '$.**{1}.b ? ( @ > 0)';
+ ?column? 
+----------
+ f
+(1 row)
+
+select jsonb '{"a": {"c": {"b": 1}}}' @? '$.**{0 to last}.b ? ( @ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"a": {"c": {"b": 1}}}' @? '$.**{1 to last}.b ? ( @ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"a": {"c": {"b": 1}}}' @? '$.**{1 to 2}.b ? ( @ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"a": {"c": {"b": 1}}}' @? '$.**{2 to 3}.b ? ( @ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb_path_query('{"g": {"x": 2}}', '$.g ? (exists (@.x))');
+ jsonb_path_query 
+------------------
+ {"x": 2}
+(1 row)
+
+select jsonb_path_query('{"g": {"x": 2}}', '$.g ? (exists (@.y))');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select jsonb_path_query('{"g": {"x": 2}}', '$.g ? (exists (@.x ? (@ >= 2) ))');
+ jsonb_path_query 
+------------------
+ {"x": 2}
+(1 row)
+
+select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'lax $.g ? (exists (@.x))');
+ jsonb_path_query 
+------------------
+ {"x": 2}
+(1 row)
+
+select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'lax $.g ? (exists (@.x + "3"))');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'lax $.g ? ((exists (@.x + "3")) is unknown)');
+ jsonb_path_query 
+------------------
+ {"x": 2}
+ {"y": 3}
+(2 rows)
+
+select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'strict $.g[*] ? (exists (@.x))');
+ jsonb_path_query 
+------------------
+ {"x": 2}
+(1 row)
+
+select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'strict $.g[*] ? ((exists (@.x)) is unknown)');
+ jsonb_path_query 
+------------------
+ {"y": 3}
+(1 row)
+
+select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'strict $.g ? (exists (@[*].x))');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'strict $.g ? ((exists (@[*].x)) is unknown)');
+   jsonb_path_query   
+----------------------
+ [{"x": 2}, {"y": 3}]
+(1 row)
+
+--test ternary logic
+select
+	x, y,
+	jsonb_path_query(
+		'[true, false, null]',
+		'$[*] ? (@ == true  &&  ($x == true && $y == true) ||
+				 @ == false && !($x == true && $y == true) ||
+				 @ == null  &&  ($x == true && $y == true) is unknown)',
+		jsonb_build_object('x', x, 'y', y)
+	) as "x && y"
+from
+	(values (jsonb 'true'), ('false'), ('"null"')) x(x),
+	(values (jsonb 'true'), ('false'), ('"null"')) y(y);
+   x    |   y    | x && y 
+--------+--------+--------
+ true   | true   | true
+ true   | false  | false
+ true   | "null" | null
+ false  | true   | false
+ false  | false  | false
+ false  | "null" | false
+ "null" | true   | null
+ "null" | false  | false
+ "null" | "null" | null
+(9 rows)
+
+select
+	x, y,
+	jsonb_path_query(
+		'[true, false, null]',
+		'$[*] ? (@ == true  &&  ($x == true || $y == true) ||
+				 @ == false && !($x == true || $y == true) ||
+				 @ == null  &&  ($x == true || $y == true) is unknown)',
+		jsonb_build_object('x', x, 'y', y)
+	) as "x || y"
+from
+	(values (jsonb 'true'), ('false'), ('"null"')) x(x),
+	(values (jsonb 'true'), ('false'), ('"null"')) y(y);
+   x    |   y    | x || y 
+--------+--------+--------
+ true   | true   | true
+ true   | false  | true
+ true   | "null" | true
+ false  | true   | true
+ false  | false  | false
+ false  | "null" | null
+ "null" | true   | true
+ "null" | false  | null
+ "null" | "null" | null
+(9 rows)
+
+select jsonb '{"a": 1, "b":1}' @? '$ ? (@.a == @.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"c": {"a": 1, "b":1}}' @? '$ ? (@.a == @.b)';
+ ?column? 
+----------
+ f
+(1 row)
+
+select jsonb '{"c": {"a": 1, "b":1}}' @? '$.c ? (@.a == @.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"c": {"a": 1, "b":1}}' @? '$.c ? ($.c.a == @.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"c": {"a": 1, "b":1}}' @? '$.* ? (@.a == @.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"a": 1, "b":1}' @? '$.** ? (@.a == @.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"c": {"a": 1, "b":1}}' @? '$.** ? (@.a == @.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb_path_query('{"c": {"a": 2, "b":1}}', '$.** ? (@.a == 1 + 1)');
+ jsonb_path_query 
+------------------
+ {"a": 2, "b": 1}
+(1 row)
+
+select jsonb_path_query('{"c": {"a": 2, "b":1}}', '$.** ? (@.a == (1 + 1))');
+ jsonb_path_query 
+------------------
+ {"a": 2, "b": 1}
+(1 row)
+
+select jsonb_path_query('{"c": {"a": 2, "b":1}}', '$.** ? (@.a == @.b + 1)');
+ jsonb_path_query 
+------------------
+ {"a": 2, "b": 1}
+(1 row)
+
+select jsonb_path_query('{"c": {"a": 2, "b":1}}', '$.** ? (@.a == (@.b + 1))');
+ jsonb_path_query 
+------------------
+ {"a": 2, "b": 1}
+(1 row)
+
+select jsonb '{"c": {"a": -1, "b":1}}' @? '$.** ? (@.a == - 1)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"c": {"a": -1, "b":1}}' @? '$.** ? (@.a == -1)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"c": {"a": -1, "b":1}}' @? '$.** ? (@.a == -@.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"c": {"a": -1, "b":1}}' @? '$.** ? (@.a == - @.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"c": {"a": 0, "b":1}}' @? '$.** ? (@.a == 1 - @.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"c": {"a": 2, "b":1}}' @? '$.** ? (@.a == 1 - - @.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"c": {"a": 0, "b":1}}' @? '$.** ? (@.a == 1 - +@.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '[1,2,3]' @? '$ ? (+@[*] > +2)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '[1,2,3]' @? '$ ? (+@[*] > +3)';
+ ?column? 
+----------
+ f
+(1 row)
+
+select jsonb '[1,2,3]' @? '$ ? (-@[*] < -2)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '[1,2,3]' @? '$ ? (-@[*] < -3)';
+ ?column? 
+----------
+ f
+(1 row)
+
+select jsonb '1' @? '$ ? ($ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+-- arithmetic errors
+select jsonb_path_query('[1,2,0,3]', '$[*] ? (2 / @ > 0)');
+ERROR:  division by zero
+select jsonb_path_query('[1,2,0,3]', '$[*] ? ((2 / @ > 0) is unknown)');
+ERROR:  division by zero
+select jsonb_path_query('0', '1 / $');
+ERROR:  division by zero
+select jsonb_path_query('0', '1 / $ + 2');
+ERROR:  division by zero
+select jsonb_path_query('0', '-(3 + 1 % $)');
+ERROR:  division by zero
+select jsonb_path_query('1', '$ + "2"');
+ERROR:  singleton SQL/JSON item required
+DETAIL:  right operand of binary jsonpath operator + is not a singleton numeric value
+select jsonb_path_query('[1, 2]', '3 * $');
+ERROR:  singleton SQL/JSON item required
+DETAIL:  right operand of binary jsonpath operator * is not a singleton numeric value
+select jsonb_path_query('"a"', '-$');
+ERROR:  SQL/JSON number not found
+DETAIL:  operand of unary jsonpath operator - is not a numeric value
+select jsonb_path_query('[1,"2",3]', '+$');
+ERROR:  SQL/JSON number not found
+DETAIL:  operand of unary jsonpath operator + is not a numeric value
+select jsonb '["1",2,0,3]' @? '-$[*]';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '[1,"2",0,3]' @? '-$[*]';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '["1",2,0,3]' @? 'strict -$[*]';
+ ?column? 
+----------
+ 
+(1 row)
+
+select jsonb '[1,"2",0,3]' @? 'strict -$[*]';
+ ?column? 
+----------
+ 
+(1 row)
+
+-- unwrapping of operator arguments in lax mode
+select jsonb_path_query('{"a": [2]}', 'lax $.a * 3');
+ jsonb_path_query 
+------------------
+ 6
+(1 row)
+
+select jsonb_path_query('{"a": [2]}', 'lax $.a + 3');
+ jsonb_path_query 
+------------------
+ 5
+(1 row)
+
+select jsonb_path_query('{"a": [2, 3, 4]}', 'lax -$.a');
+ jsonb_path_query 
+------------------
+ -2
+ -3
+ -4
+(3 rows)
+
+-- should fail
+select jsonb_path_query('{"a": [1, 2]}', 'lax $.a * 3');
+ERROR:  singleton SQL/JSON item required
+DETAIL:  left operand of binary jsonpath operator * is not a singleton numeric value
+-- extension: boolean expressions
+select jsonb_path_query('2', '$ > 1');
+ jsonb_path_query 
+------------------
+ true
+(1 row)
+
+select jsonb_path_query('2', '$ <= 1');
+ jsonb_path_query 
+------------------
+ false
+(1 row)
+
+select jsonb_path_query('2', '$ == "2"');
+ jsonb_path_query 
+------------------
+ null
+(1 row)
+
+select jsonb '2' @? '$ == "2"';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '2' @@ '$ > 1';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '2' @@ '$ <= 1';
+ ?column? 
+----------
+ f
+(1 row)
+
+select jsonb '2' @@ '$ == "2"';
+ ?column? 
+----------
+ 
+(1 row)
+
+select jsonb '2' @@ '1';
+ ?column? 
+----------
+ 
+(1 row)
+
+select jsonb '{}' @@ '$';
+ ?column? 
+----------
+ 
+(1 row)
+
+select jsonb '[]' @@ '$';
+ ?column? 
+----------
+ 
+(1 row)
+
+select jsonb '[1,2,3]' @@ '$[*]';
+ ?column? 
+----------
+ 
+(1 row)
+
+select jsonb '[]' @@ '$[*]';
+ ?column? 
+----------
+ 
+(1 row)
+
+select jsonb_path_match('[[1, true], [2, false]]', 'strict $[*] ? (@[0] > $x) [1]', '{"x": 1}');
+ jsonb_path_match 
+------------------
+ f
+(1 row)
+
+select jsonb_path_match('[[1, true], [2, false]]', 'strict $[*] ? (@[0] < $x) [1]', '{"x": 2}');
+ jsonb_path_match 
+------------------
+ t
+(1 row)
+
+select jsonb_path_query('[null,1,true,"a",[],{}]', '$.type()');
+ jsonb_path_query 
+------------------
+ "array"
+(1 row)
+
+select jsonb_path_query('[null,1,true,"a",[],{}]', 'lax $.type()');
+ jsonb_path_query 
+------------------
+ "array"
+(1 row)
+
+select jsonb_path_query('[null,1,true,"a",[],{}]', '$[*].type()');
+ jsonb_path_query 
+------------------
+ "null"
+ "number"
+ "boolean"
+ "string"
+ "array"
+ "object"
+(6 rows)
+
+select jsonb_path_query('null', 'null.type()');
+ jsonb_path_query 
+------------------
+ "null"
+(1 row)
+
+select jsonb_path_query('null', 'true.type()');
+ jsonb_path_query 
+------------------
+ "boolean"
+(1 row)
+
+select jsonb_path_query('null', '123.type()');
+ jsonb_path_query 
+------------------
+ "number"
+(1 row)
+
+select jsonb_path_query('null', '"123".type()');
+ jsonb_path_query 
+------------------
+ "string"
+(1 row)
+
+select jsonb_path_query('{"a": 2}', '($.a - 5).abs() + 10');
+ jsonb_path_query 
+------------------
+ 13
+(1 row)
+
+select jsonb_path_query('{"a": 2.5}', '-($.a * $.a).floor() % 4.3');
+ jsonb_path_query 
+------------------
+ -1.7
+(1 row)
+
+select jsonb_path_query('[1, 2, 3]', '($[*] > 2) ? (@ == true)');
+ jsonb_path_query 
+------------------
+ true
+(1 row)
+
+select jsonb_path_query('[1, 2, 3]', '($[*] > 3).type()');
+ jsonb_path_query 
+------------------
+ "boolean"
+(1 row)
+
+select jsonb_path_query('[1, 2, 3]', '($[*].a > 3).type()');
+ jsonb_path_query 
+------------------
+ "boolean"
+(1 row)
+
+select jsonb_path_query('[1, 2, 3]', 'strict ($[*].a > 3).type()');
+ jsonb_path_query 
+------------------
+ "null"
+(1 row)
+
+select jsonb_path_query('[1,null,true,"11",[],[1],[1,2,3],{},{"a":1,"b":2}]', 'strict $[*].size()');
+ERROR:  SQL/JSON array not found
+DETAIL:  jsonpath item method .size() is applied to not an array
+select jsonb_path_query('[1,null,true,"11",[],[1],[1,2,3],{},{"a":1,"b":2}]', 'lax $[*].size()');
+ jsonb_path_query 
+------------------
+ 1
+ 1
+ 1
+ 1
+ 0
+ 1
+ 3
+ 1
+ 1
+(9 rows)
+
+select jsonb_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].abs()');
+ jsonb_path_query 
+------------------
+ 0
+ 1
+ 2
+ 3.4
+ 5.6
+(5 rows)
+
+select jsonb_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].floor()');
+ jsonb_path_query 
+------------------
+ 0
+ 1
+ -2
+ -4
+ 5
+(5 rows)
+
+select jsonb_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].ceiling()');
+ jsonb_path_query 
+------------------
+ 0
+ 1
+ -2
+ -3
+ 6
+(5 rows)
+
+select jsonb_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].ceiling().abs()');
+ jsonb_path_query 
+------------------
+ 0
+ 1
+ 2
+ 3
+ 6
+(5 rows)
+
+select jsonb_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].ceiling().abs().type()');
+ jsonb_path_query 
+------------------
+ "number"
+ "number"
+ "number"
+ "number"
+ "number"
+(5 rows)
+
+select jsonb_path_query('[{},1]', '$[*].keyvalue()');
+ERROR:  SQL/JSON object not found
+DETAIL:  jsonpath item method .keyvalue() is applied to not an object
+select jsonb_path_query('{}', '$.keyvalue()');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select jsonb_path_query('{"a": 1, "b": [1, 2], "c": {"a": "bbb"}}', '$.keyvalue()');
+               jsonb_path_query               
+----------------------------------------------
+ {"id": 0, "key": "a", "value": 1}
+ {"id": 0, "key": "b", "value": [1, 2]}
+ {"id": 0, "key": "c", "value": {"a": "bbb"}}
+(3 rows)
+
+select jsonb_path_query('[{"a": 1, "b": [1, 2]}, {"c": {"a": "bbb"}}]', '$[*].keyvalue()');
+               jsonb_path_query                
+-----------------------------------------------
+ {"id": 12, "key": "a", "value": 1}
+ {"id": 12, "key": "b", "value": [1, 2]}
+ {"id": 72, "key": "c", "value": {"a": "bbb"}}
+(3 rows)
+
+select jsonb_path_query('[{"a": 1, "b": [1, 2]}, {"c": {"a": "bbb"}}]', 'strict $.keyvalue()');
+ERROR:  SQL/JSON object not found
+DETAIL:  jsonpath item method .keyvalue() is applied to not an object
+select jsonb_path_query('[{"a": 1, "b": [1, 2]}, {"c": {"a": "bbb"}}]', 'lax $.keyvalue()');
+               jsonb_path_query                
+-----------------------------------------------
+ {"id": 12, "key": "a", "value": 1}
+ {"id": 12, "key": "b", "value": [1, 2]}
+ {"id": 72, "key": "c", "value": {"a": "bbb"}}
+(3 rows)
+
+select jsonb_path_query('[{"a": 1, "b": [1, 2]}, {"c": {"a": "bbb"}}]', 'strict $.keyvalue().a');
+ERROR:  SQL/JSON object not found
+DETAIL:  jsonpath item method .keyvalue() is applied to not an object
+select jsonb '{"a": 1, "b": [1, 2]}' @? 'lax $.keyvalue()';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb '{"a": 1, "b": [1, 2]}' @? 'lax $.keyvalue().key';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb_path_query('null', '$.double()');
+ERROR:  non-numeric SQL/JSON item
+DETAIL:  jsonpath item method .double() is applied to neither a string nor numeric value
+select jsonb_path_query('true', '$.double()');
+ERROR:  non-numeric SQL/JSON item
+DETAIL:  jsonpath item method .double() is applied to neither a string nor numeric value
+select jsonb_path_query('[]', '$.double()');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select jsonb_path_query('[]', 'strict $.double()');
+ERROR:  non-numeric SQL/JSON item
+DETAIL:  jsonpath item method .double() is applied to neither a string nor numeric value
+select jsonb_path_query('{}', '$.double()');
+ERROR:  non-numeric SQL/JSON item
+DETAIL:  jsonpath item method .double() is applied to neither a string nor numeric value
+select jsonb_path_query('1.23', '$.double()');
+ jsonb_path_query 
+------------------
+ 1.23
+(1 row)
+
+select jsonb_path_query('"1.23"', '$.double()');
+ jsonb_path_query 
+------------------
+ 1.23
+(1 row)
+
+select jsonb_path_query('"1.23aaa"', '$.double()');
+ERROR:  invalid input syntax for type double precision: "1.23aaa"
+select jsonb_path_query('"nan"', '$.double()');
+ jsonb_path_query 
+------------------
+ "NaN"
+(1 row)
+
+select jsonb_path_query('"NaN"', '$.double()');
+ jsonb_path_query 
+------------------
+ "NaN"
+(1 row)
+
+select jsonb_path_query('"inf"', '$.double()');
+ERROR:  non-numeric SQL/JSON item
+DETAIL:  jsonpath item method .double() is applied to not a numeric value
+select jsonb_path_query('"-inf"', '$.double()');
+ERROR:  non-numeric SQL/JSON item
+DETAIL:  jsonpath item method .double() is applied to not a numeric value
+select jsonb_path_query('{}', '$.abs()');
+ERROR:  non-numeric SQL/JSON item
+DETAIL:  jsonpath item method .abs() is applied to not a numeric value
+select jsonb_path_query('true', '$.floor()');
+ERROR:  non-numeric SQL/JSON item
+DETAIL:  jsonpath item method .floor() is applied to not a numeric value
+select jsonb_path_query('"1.2"', '$.ceiling()');
+ERROR:  non-numeric SQL/JSON item
+DETAIL:  jsonpath item method .ceiling() is applied to not a numeric value
+select jsonb_path_query('["", "a", "abc", "abcabc"]', '$[*] ? (@ starts with "abc")');
+ jsonb_path_query 
+------------------
+ "abc"
+ "abcabc"
+(2 rows)
+
+select jsonb_path_query('["", "a", "abc", "abcabc"]', 'strict $ ? (@[*] starts with "abc")');
+      jsonb_path_query      
+----------------------------
+ ["", "a", "abc", "abcabc"]
+(1 row)
+
+select jsonb_path_query('["", "a", "abd", "abdabc"]', 'strict $ ? (@[*] starts with "abc")');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select jsonb_path_query('["abc", "abcabc", null, 1]', 'strict $ ? (@[*] starts with "abc")');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select jsonb_path_query('["abc", "abcabc", null, 1]', 'strict $ ? ((@[*] starts with "abc") is unknown)');
+      jsonb_path_query      
+----------------------------
+ ["abc", "abcabc", null, 1]
+(1 row)
+
+select jsonb_path_query('[[null, 1, "abc", "abcabc"]]', 'lax $ ? (@[*] starts with "abc")');
+      jsonb_path_query      
+----------------------------
+ [null, 1, "abc", "abcabc"]
+(1 row)
+
+select jsonb_path_query('[[null, 1, "abd", "abdabc"]]', 'lax $ ? ((@[*] starts with "abc") is unknown)');
+      jsonb_path_query      
+----------------------------
+ [null, 1, "abd", "abdabc"]
+(1 row)
+
+select jsonb_path_query('[null, 1, "abd", "abdabc"]', 'lax $[*] ? ((@ starts with "abc") is unknown)');
+ jsonb_path_query 
+------------------
+ null
+ 1
+(2 rows)
+
+select jsonb_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "adc\nabc", "babc"]', 'lax $[*] ? (@ like_regex "^ab.*c")');
+ jsonb_path_query 
+------------------
+ "abc"
+ "abdacb"
+(2 rows)
+
+select jsonb_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "adc\nabc", "babc"]', 'lax $[*] ? (@ like_regex "^a  b.*  c " flag "ix")');
+ jsonb_path_query 
+------------------
+ "abc"
+ "aBdC"
+ "abdacb"
+(3 rows)
+
+select jsonb_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "adc\nabc", "babc"]', 'lax $[*] ? (@ like_regex "^ab.*c" flag "m")');
+ jsonb_path_query 
+------------------
+ "abc"
+ "abdacb"
+ "adc\nabc"
+(3 rows)
+
+select jsonb_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "adc\nabc", "babc"]', 'lax $[*] ? (@ like_regex "^ab.*c" flag "s")');
+ jsonb_path_query 
+------------------
+ "abc"
+ "abdacb"
+(2 rows)
+
+-- jsonpath operators
+SELECT jsonb_path_query('[{"a": 1}, {"a": 2}]', '$[*]');
+ jsonb_path_query 
+------------------
+ {"a": 1}
+ {"a": 2}
+(2 rows)
+
+SELECT jsonb_path_query('[{"a": 1}, {"a": 2}]', '$[*] ? (@.a > 10)');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+SELECT jsonb_path_query_array('[{"a": 1}, {"a": 2}, {}]', 'strict $[*].a');
+ERROR:  SQL/JSON member not found
+DETAIL:  JSON object does not contain key "a"
+SELECT jsonb_path_query_array('[{"a": 1}, {"a": 2}]', '$[*].a');
+ jsonb_path_query_array 
+------------------------
+ [1, 2]
+(1 row)
+
+SELECT jsonb_path_query_array('[{"a": 1}, {"a": 2}]', '$[*].a ? (@ == 1)');
+ jsonb_path_query_array 
+------------------------
+ [1]
+(1 row)
+
+SELECT jsonb_path_query_array('[{"a": 1}, {"a": 2}]', '$[*].a ? (@ > 10)');
+ jsonb_path_query_array 
+------------------------
+ []
+(1 row)
+
+SELECT jsonb_path_query_array('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*].a ? (@ > $min && @ < $max)', '{"min": 1, "max": 4}');
+ jsonb_path_query_array 
+------------------------
+ [2, 3]
+(1 row)
+
+SELECT jsonb_path_query_array('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*].a ? (@ > $min && @ < $max)', '{"min": 3, "max": 4}');
+ jsonb_path_query_array 
+------------------------
+ []
+(1 row)
+
+SELECT jsonb_path_query_first('[{"a": 1}, {"a": 2}, {}]', 'strict $[*].a');
+ERROR:  SQL/JSON member not found
+DETAIL:  JSON object does not contain key "a"
+SELECT jsonb_path_query_first('[{"a": 1}, {"a": 2}]', '$[*].a');
+ jsonb_path_query_first 
+------------------------
+ 1
+(1 row)
+
+SELECT jsonb_path_query_first('[{"a": 1}, {"a": 2}]', '$[*].a ? (@ == 1)');
+ jsonb_path_query_first 
+------------------------
+ 1
+(1 row)
+
+SELECT jsonb_path_query_first('[{"a": 1}, {"a": 2}]', '$[*].a ? (@ > 10)');
+ jsonb_path_query_first 
+------------------------
+ 
+(1 row)
+
+SELECT jsonb_path_query_first('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*].a ? (@ > $min && @ < $max)', '{"min": 1, "max": 4}');
+ jsonb_path_query_first 
+------------------------
+ 2
+(1 row)
+
+SELECT jsonb_path_query_first('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*].a ? (@ > $min && @ < $max)', '{"min": 3, "max": 4}');
+ jsonb_path_query_first 
+------------------------
+ 
+(1 row)
+
+SELECT jsonb '[{"a": 1}, {"a": 2}]' @? '$[*].a ? (@ > 1)';
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT jsonb '[{"a": 1}, {"a": 2}]' @? '$[*] ? (@.a > 2)';
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT jsonb_path_exists('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*] ? (@.a > $min && @.a < $max)', '{"min": 1, "max": 4}');
+ jsonb_path_exists 
+-------------------
+ t
+(1 row)
+
+SELECT jsonb_path_exists('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*] ? (@.a > $min && @.a < $max)', '{"min": 3, "max": 4}');
+ jsonb_path_exists 
+-------------------
+ f
+(1 row)
+
+SELECT jsonb '[{"a": 1}, {"a": 2}]' @@ '$[*].a > 1';
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT jsonb '[{"a": 1}, {"a": 2}]' @@ '$[*].a > 2';
+ ?column? 
+----------
+ f
+(1 row)
+
diff --git a/src/test/regress/expected/jsonpath.out b/src/test/regress/expected/jsonpath.out
new file mode 100644
index 0000000..baaf9e3
--- /dev/null
+++ b/src/test/regress/expected/jsonpath.out
@@ -0,0 +1,806 @@
+--jsonpath io
+select ''::jsonpath;
+ERROR:  invalid input syntax for jsonpath: ""
+LINE 1: select ''::jsonpath;
+               ^
+select '$'::jsonpath;
+ jsonpath 
+----------
+ $
+(1 row)
+
+select 'strict $'::jsonpath;
+ jsonpath 
+----------
+ strict $
+(1 row)
+
+select 'lax $'::jsonpath;
+ jsonpath 
+----------
+ $
+(1 row)
+
+select '$.a'::jsonpath;
+ jsonpath 
+----------
+ $."a"
+(1 row)
+
+select '$.a.v'::jsonpath;
+ jsonpath  
+-----------
+ $."a"."v"
+(1 row)
+
+select '$.a.*'::jsonpath;
+ jsonpath 
+----------
+ $."a".*
+(1 row)
+
+select '$.*[*]'::jsonpath;
+ jsonpath 
+----------
+ $.*[*]
+(1 row)
+
+select '$.a[*]'::jsonpath;
+ jsonpath 
+----------
+ $."a"[*]
+(1 row)
+
+select '$.a[*][*]'::jsonpath;
+  jsonpath   
+-------------
+ $."a"[*][*]
+(1 row)
+
+select '$[*]'::jsonpath;
+ jsonpath 
+----------
+ $[*]
+(1 row)
+
+select '$[0]'::jsonpath;
+ jsonpath 
+----------
+ $[0]
+(1 row)
+
+select '$[*][0]'::jsonpath;
+ jsonpath 
+----------
+ $[*][0]
+(1 row)
+
+select '$[*].a'::jsonpath;
+ jsonpath 
+----------
+ $[*]."a"
+(1 row)
+
+select '$[*][0].a.b'::jsonpath;
+    jsonpath     
+-----------------
+ $[*][0]."a"."b"
+(1 row)
+
+select '$.a.**.b'::jsonpath;
+   jsonpath   
+--------------
+ $."a".**."b"
+(1 row)
+
+select '$.a.**{2}.b'::jsonpath;
+    jsonpath     
+-----------------
+ $."a".**{2}."b"
+(1 row)
+
+select '$.a.**{2 to 2}.b'::jsonpath;
+    jsonpath     
+-----------------
+ $."a".**{2}."b"
+(1 row)
+
+select '$.a.**{2 to 5}.b'::jsonpath;
+       jsonpath       
+----------------------
+ $."a".**{2 to 5}."b"
+(1 row)
+
+select '$.a.**{0 to 5}.b'::jsonpath;
+       jsonpath       
+----------------------
+ $."a".**{0 to 5}."b"
+(1 row)
+
+select '$.a.**{5 to last}.b'::jsonpath;
+        jsonpath         
+-------------------------
+ $."a".**{5 to last}."b"
+(1 row)
+
+select '$.a.**{last}.b'::jsonpath;
+      jsonpath      
+--------------------
+ $."a".**{last}."b"
+(1 row)
+
+select '$.a.**{last to 5}.b'::jsonpath;
+        jsonpath         
+-------------------------
+ $."a".**{last to 5}."b"
+(1 row)
+
+select '$+1'::jsonpath;
+ jsonpath 
+----------
+ ($ + 1)
+(1 row)
+
+select '$-1'::jsonpath;
+ jsonpath 
+----------
+ ($ - 1)
+(1 row)
+
+select '$--+1'::jsonpath;
+ jsonpath 
+----------
+ ($ - -1)
+(1 row)
+
+select '$.a/+-1'::jsonpath;
+   jsonpath   
+--------------
+ ($."a" / -1)
+(1 row)
+
+select '1 * 2 + 4 % -3 != false'::jsonpath;
+         jsonpath          
+---------------------------
+ (1 * 2 + 4 % -3 != false)
+(1 row)
+
+select '"\b\f\r\n\t\v\"\''\\"'::jsonpath;
+        jsonpath         
+-------------------------
+ "\b\f\r\n\t\u000b\"'\\"
+(1 row)
+
+select '''\b\f\r\n\t\v\"\''\\'''::jsonpath;
+        jsonpath         
+-------------------------
+ "\b\f\r\n\t\u000b\"'\\"
+(1 row)
+
+select '"\x50\u0067\u{53}\u{051}\u{00004C}"'::jsonpath;
+ jsonpath 
+----------
+ "PgSQL"
+(1 row)
+
+select '''\x50\u0067\u{53}\u{051}\u{00004C}'''::jsonpath;
+ jsonpath 
+----------
+ "PgSQL"
+(1 row)
+
+select '$.foo\x50\u0067\u{53}\u{051}\u{00004C}\t\"bar'::jsonpath;
+      jsonpath       
+---------------------
+ $."fooPgSQL\t\"bar"
+(1 row)
+
+select '$.g ? ($.a == 1)'::jsonpath;
+      jsonpath      
+--------------------
+ $."g"?($."a" == 1)
+(1 row)
+
+select '$.g ? (@ == 1)'::jsonpath;
+    jsonpath    
+----------------
+ $."g"?(@ == 1)
+(1 row)
+
+select '$.g ? (@.a == 1)'::jsonpath;
+      jsonpath      
+--------------------
+ $."g"?(@."a" == 1)
+(1 row)
+
+select '$.g ? (@.a == 1 || @.a == 4)'::jsonpath;
+             jsonpath             
+----------------------------------
+ $."g"?(@."a" == 1 || @."a" == 4)
+(1 row)
+
+select '$.g ? (@.a == 1 && @.a == 4)'::jsonpath;
+             jsonpath             
+----------------------------------
+ $."g"?(@."a" == 1 && @."a" == 4)
+(1 row)
+
+select '$.g ? (@.a == 1 || @.a == 4 && @.b == 7)'::jsonpath;
+                    jsonpath                    
+------------------------------------------------
+ $."g"?(@."a" == 1 || @."a" == 4 && @."b" == 7)
+(1 row)
+
+select '$.g ? (@.a == 1 || !(@.a == 4) && @.b == 7)'::jsonpath;
+                     jsonpath                      
+---------------------------------------------------
+ $."g"?(@."a" == 1 || !(@."a" == 4) && @."b" == 7)
+(1 row)
+
+select '$.g ? (@.a == 1 || !(@.x >= 123 || @.a == 4) && @.b == 7)'::jsonpath;
+                             jsonpath                              
+-------------------------------------------------------------------
+ $."g"?(@."a" == 1 || !(@."x" >= 123 || @."a" == 4) && @."b" == 7)
+(1 row)
+
+select '$.g ? (@.x >= @[*]?(@.a > "abc"))'::jsonpath;
+               jsonpath                
+---------------------------------------
+ $."g"?(@."x" >= @[*]?(@."a" > "abc"))
+(1 row)
+
+select '$.g ? ((@.x >= 123 || @.a == 4) is unknown)'::jsonpath;
+                    jsonpath                     
+-------------------------------------------------
+ $."g"?((@."x" >= 123 || @."a" == 4) is unknown)
+(1 row)
+
+select '$.g ? (exists (@.x))'::jsonpath;
+        jsonpath        
+------------------------
+ $."g"?(exists (@."x"))
+(1 row)
+
+select '$.g ? (exists (@.x ? (@ == 14)))'::jsonpath;
+             jsonpath             
+----------------------------------
+ $."g"?(exists (@."x"?(@ == 14)))
+(1 row)
+
+select '$.g ? ((@.x >= 123 || @.a == 4) && exists (@.x ? (@ == 14)))'::jsonpath;
+                             jsonpath                             
+------------------------------------------------------------------
+ $."g"?((@."x" >= 123 || @."a" == 4) && exists (@."x"?(@ == 14)))
+(1 row)
+
+select '$.g ? (+@.x >= +-(+@.a + 2))'::jsonpath;
+              jsonpath              
+------------------------------------
+ $."g"?(+@."x" >= +(-(+@."a" + 2)))
+(1 row)
+
+select '$a'::jsonpath;
+ jsonpath 
+----------
+ $"a"
+(1 row)
+
+select '$a.b'::jsonpath;
+ jsonpath 
+----------
+ $"a"."b"
+(1 row)
+
+select '$a[*]'::jsonpath;
+ jsonpath 
+----------
+ $"a"[*]
+(1 row)
+
+select '$.g ? (@.zip == $zip)'::jsonpath;
+         jsonpath          
+---------------------------
+ $."g"?(@."zip" == $"zip")
+(1 row)
+
+select '$.a[1,2, 3 to 16]'::jsonpath;
+      jsonpath      
+--------------------
+ $."a"[1,2,3 to 16]
+(1 row)
+
+select '$.a[$a + 1, ($b[*]) to -($[0] * 2)]'::jsonpath;
+                jsonpath                
+----------------------------------------
+ $."a"[$"a" + 1,$"b"[*] to -($[0] * 2)]
+(1 row)
+
+select '$.a[$.a.size() - 3]'::jsonpath;
+        jsonpath         
+-------------------------
+ $."a"[$."a".size() - 3]
+(1 row)
+
+select 'last'::jsonpath;
+ERROR:  LAST is allowed only in array subscripts
+LINE 1: select 'last'::jsonpath;
+               ^
+select '"last"'::jsonpath;
+ jsonpath 
+----------
+ "last"
+(1 row)
+
+select '$.last'::jsonpath;
+ jsonpath 
+----------
+ $."last"
+(1 row)
+
+select '$ ? (last > 0)'::jsonpath;
+ERROR:  LAST is allowed only in array subscripts
+LINE 1: select '$ ? (last > 0)'::jsonpath;
+               ^
+select '$[last]'::jsonpath;
+ jsonpath 
+----------
+ $[last]
+(1 row)
+
+select '$[$[0] ? (last > 0)]'::jsonpath;
+      jsonpath      
+--------------------
+ $[$[0]?(last > 0)]
+(1 row)
+
+select 'null.type()'::jsonpath;
+  jsonpath   
+-------------
+ null.type()
+(1 row)
+
+select '1.type()'::jsonpath;
+ jsonpath 
+----------
+ 1.type()
+(1 row)
+
+select '"aaa".type()'::jsonpath;
+   jsonpath   
+--------------
+ "aaa".type()
+(1 row)
+
+select 'true.type()'::jsonpath;
+  jsonpath   
+-------------
+ true.type()
+(1 row)
+
+select '$.double().floor().ceiling().abs()'::jsonpath;
+              jsonpath              
+------------------------------------
+ $.double().floor().ceiling().abs()
+(1 row)
+
+select '$.keyvalue().key'::jsonpath;
+      jsonpath      
+--------------------
+ $.keyvalue()."key"
+(1 row)
+
+select '$ ? (@ starts with "abc")'::jsonpath;
+        jsonpath         
+-------------------------
+ $?(@ starts with "abc")
+(1 row)
+
+select '$ ? (@ starts with $var)'::jsonpath;
+         jsonpath         
+--------------------------
+ $?(@ starts with $"var")
+(1 row)
+
+select '$ ? (@ like_regex "(invalid pattern")'::jsonpath;
+ERROR:  invalid regular expression: parentheses () not balanced
+LINE 1: select '$ ? (@ like_regex "(invalid pattern")'::jsonpath;
+               ^
+select '$ ? (@ like_regex "pattern")'::jsonpath;
+          jsonpath          
+----------------------------
+ $?(@ like_regex "pattern")
+(1 row)
+
+select '$ ? (@ like_regex "pattern" flag "")'::jsonpath;
+          jsonpath          
+----------------------------
+ $?(@ like_regex "pattern")
+(1 row)
+
+select '$ ? (@ like_regex "pattern" flag "i")'::jsonpath;
+              jsonpath               
+-------------------------------------
+ $?(@ like_regex "pattern" flag "i")
+(1 row)
+
+select '$ ? (@ like_regex "pattern" flag "is")'::jsonpath;
+               jsonpath               
+--------------------------------------
+ $?(@ like_regex "pattern" flag "is")
+(1 row)
+
+select '$ ? (@ like_regex "pattern" flag "isim")'::jsonpath;
+               jsonpath               
+--------------------------------------
+ $?(@ like_regex "pattern" flag "im")
+(1 row)
+
+select '$ ? (@ like_regex "pattern" flag "xsms")'::jsonpath;
+               jsonpath               
+--------------------------------------
+ $?(@ like_regex "pattern" flag "sx")
+(1 row)
+
+select '$ ? (@ like_regex "pattern" flag "a")'::jsonpath;
+ERROR:  bad jsonpath representation
+LINE 1: select '$ ? (@ like_regex "pattern" flag "a")'::jsonpath;
+               ^
+DETAIL:  unrecognized flag of LIKE_REGEX predicate at or near """
+select '$ < 1'::jsonpath;
+ jsonpath 
+----------
+ ($ < 1)
+(1 row)
+
+select '($ < 1) || $.a.b <= $x'::jsonpath;
+           jsonpath           
+------------------------------
+ ($ < 1 || $."a"."b" <= $"x")
+(1 row)
+
+select '@ + 1'::jsonpath;
+ERROR:  @ is not allowed in root expressions
+LINE 1: select '@ + 1'::jsonpath;
+               ^
+select '($).a.b'::jsonpath;
+ jsonpath  
+-----------
+ $."a"."b"
+(1 row)
+
+select '($.a.b).c.d'::jsonpath;
+     jsonpath      
+-------------------
+ $."a"."b"."c"."d"
+(1 row)
+
+select '($.a.b + -$.x.y).c.d'::jsonpath;
+             jsonpath             
+----------------------------------
+ ($."a"."b" + -$."x"."y")."c"."d"
+(1 row)
+
+select '(-+$.a.b).c.d'::jsonpath;
+        jsonpath         
+-------------------------
+ (-(+$."a"."b"))."c"."d"
+(1 row)
+
+select '1 + ($.a.b + 2).c.d'::jsonpath;
+           jsonpath            
+-------------------------------
+ (1 + ($."a"."b" + 2)."c"."d")
+(1 row)
+
+select '1 + ($.a.b > 2).c.d'::jsonpath;
+           jsonpath            
+-------------------------------
+ (1 + ($."a"."b" > 2)."c"."d")
+(1 row)
+
+select '($)'::jsonpath;
+ jsonpath 
+----------
+ $
+(1 row)
+
+select '(($))'::jsonpath;
+ jsonpath 
+----------
+ $
+(1 row)
+
+select '((($ + 1)).a + ((2)).b ? ((((@ > 1)) || (exists(@.c)))))'::jsonpath;
+                    jsonpath                     
+-------------------------------------------------
+ (($ + 1)."a" + 2."b"?(@ > 1 || exists (@."c")))
+(1 row)
+
+select '$ ? (@.a < 1)'::jsonpath;
+   jsonpath    
+---------------
+ $?(@."a" < 1)
+(1 row)
+
+select '$ ? (@.a < -1)'::jsonpath;
+    jsonpath    
+----------------
+ $?(@."a" < -1)
+(1 row)
+
+select '$ ? (@.a < +1)'::jsonpath;
+   jsonpath    
+---------------
+ $?(@."a" < 1)
+(1 row)
+
+select '$ ? (@.a < .1)'::jsonpath;
+    jsonpath     
+-----------------
+ $?(@."a" < 0.1)
+(1 row)
+
+select '$ ? (@.a < -.1)'::jsonpath;
+     jsonpath     
+------------------
+ $?(@."a" < -0.1)
+(1 row)
+
+select '$ ? (@.a < +.1)'::jsonpath;
+    jsonpath     
+-----------------
+ $?(@."a" < 0.1)
+(1 row)
+
+select '$ ? (@.a < 0.1)'::jsonpath;
+    jsonpath     
+-----------------
+ $?(@."a" < 0.1)
+(1 row)
+
+select '$ ? (@.a < -0.1)'::jsonpath;
+     jsonpath     
+------------------
+ $?(@."a" < -0.1)
+(1 row)
+
+select '$ ? (@.a < +0.1)'::jsonpath;
+    jsonpath     
+-----------------
+ $?(@."a" < 0.1)
+(1 row)
+
+select '$ ? (@.a < 10.1)'::jsonpath;
+     jsonpath     
+------------------
+ $?(@."a" < 10.1)
+(1 row)
+
+select '$ ? (@.a < -10.1)'::jsonpath;
+     jsonpath      
+-------------------
+ $?(@."a" < -10.1)
+(1 row)
+
+select '$ ? (@.a < +10.1)'::jsonpath;
+     jsonpath     
+------------------
+ $?(@."a" < 10.1)
+(1 row)
+
+select '$ ? (@.a < 1e1)'::jsonpath;
+    jsonpath    
+----------------
+ $?(@."a" < 10)
+(1 row)
+
+select '$ ? (@.a < -1e1)'::jsonpath;
+    jsonpath     
+-----------------
+ $?(@."a" < -10)
+(1 row)
+
+select '$ ? (@.a < +1e1)'::jsonpath;
+    jsonpath    
+----------------
+ $?(@."a" < 10)
+(1 row)
+
+select '$ ? (@.a < .1e1)'::jsonpath;
+   jsonpath    
+---------------
+ $?(@."a" < 1)
+(1 row)
+
+select '$ ? (@.a < -.1e1)'::jsonpath;
+    jsonpath    
+----------------
+ $?(@."a" < -1)
+(1 row)
+
+select '$ ? (@.a < +.1e1)'::jsonpath;
+   jsonpath    
+---------------
+ $?(@."a" < 1)
+(1 row)
+
+select '$ ? (@.a < 0.1e1)'::jsonpath;
+   jsonpath    
+---------------
+ $?(@."a" < 1)
+(1 row)
+
+select '$ ? (@.a < -0.1e1)'::jsonpath;
+    jsonpath    
+----------------
+ $?(@."a" < -1)
+(1 row)
+
+select '$ ? (@.a < +0.1e1)'::jsonpath;
+   jsonpath    
+---------------
+ $?(@."a" < 1)
+(1 row)
+
+select '$ ? (@.a < 10.1e1)'::jsonpath;
+    jsonpath     
+-----------------
+ $?(@."a" < 101)
+(1 row)
+
+select '$ ? (@.a < -10.1e1)'::jsonpath;
+     jsonpath     
+------------------
+ $?(@."a" < -101)
+(1 row)
+
+select '$ ? (@.a < +10.1e1)'::jsonpath;
+    jsonpath     
+-----------------
+ $?(@."a" < 101)
+(1 row)
+
+select '$ ? (@.a < 1e-1)'::jsonpath;
+    jsonpath     
+-----------------
+ $?(@."a" < 0.1)
+(1 row)
+
+select '$ ? (@.a < -1e-1)'::jsonpath;
+     jsonpath     
+------------------
+ $?(@."a" < -0.1)
+(1 row)
+
+select '$ ? (@.a < +1e-1)'::jsonpath;
+    jsonpath     
+-----------------
+ $?(@."a" < 0.1)
+(1 row)
+
+select '$ ? (@.a < .1e-1)'::jsonpath;
+     jsonpath     
+------------------
+ $?(@."a" < 0.01)
+(1 row)
+
+select '$ ? (@.a < -.1e-1)'::jsonpath;
+     jsonpath      
+-------------------
+ $?(@."a" < -0.01)
+(1 row)
+
+select '$ ? (@.a < +.1e-1)'::jsonpath;
+     jsonpath     
+------------------
+ $?(@."a" < 0.01)
+(1 row)
+
+select '$ ? (@.a < 0.1e-1)'::jsonpath;
+     jsonpath     
+------------------
+ $?(@."a" < 0.01)
+(1 row)
+
+select '$ ? (@.a < -0.1e-1)'::jsonpath;
+     jsonpath      
+-------------------
+ $?(@."a" < -0.01)
+(1 row)
+
+select '$ ? (@.a < +0.1e-1)'::jsonpath;
+     jsonpath     
+------------------
+ $?(@."a" < 0.01)
+(1 row)
+
+select '$ ? (@.a < 10.1e-1)'::jsonpath;
+     jsonpath     
+------------------
+ $?(@."a" < 1.01)
+(1 row)
+
+select '$ ? (@.a < -10.1e-1)'::jsonpath;
+     jsonpath      
+-------------------
+ $?(@."a" < -1.01)
+(1 row)
+
+select '$ ? (@.a < +10.1e-1)'::jsonpath;
+     jsonpath     
+------------------
+ $?(@."a" < 1.01)
+(1 row)
+
+select '$ ? (@.a < 1e+1)'::jsonpath;
+    jsonpath    
+----------------
+ $?(@."a" < 10)
+(1 row)
+
+select '$ ? (@.a < -1e+1)'::jsonpath;
+    jsonpath     
+-----------------
+ $?(@."a" < -10)
+(1 row)
+
+select '$ ? (@.a < +1e+1)'::jsonpath;
+    jsonpath    
+----------------
+ $?(@."a" < 10)
+(1 row)
+
+select '$ ? (@.a < .1e+1)'::jsonpath;
+   jsonpath    
+---------------
+ $?(@."a" < 1)
+(1 row)
+
+select '$ ? (@.a < -.1e+1)'::jsonpath;
+    jsonpath    
+----------------
+ $?(@."a" < -1)
+(1 row)
+
+select '$ ? (@.a < +.1e+1)'::jsonpath;
+   jsonpath    
+---------------
+ $?(@."a" < 1)
+(1 row)
+
+select '$ ? (@.a < 0.1e+1)'::jsonpath;
+   jsonpath    
+---------------
+ $?(@."a" < 1)
+(1 row)
+
+select '$ ? (@.a < -0.1e+1)'::jsonpath;
+    jsonpath    
+----------------
+ $?(@."a" < -1)
+(1 row)
+
+select '$ ? (@.a < +0.1e+1)'::jsonpath;
+   jsonpath    
+---------------
+ $?(@."a" < 1)
+(1 row)
+
+select '$ ? (@.a < 10.1e+1)'::jsonpath;
+    jsonpath     
+-----------------
+ $?(@."a" < 101)
+(1 row)
+
+select '$ ? (@.a < -10.1e+1)'::jsonpath;
+     jsonpath     
+------------------
+ $?(@."a" < -101)
+(1 row)
+
+select '$ ? (@.a < +10.1e+1)'::jsonpath;
+    jsonpath     
+-----------------
+ $?(@."a" < 101)
+(1 row)
+
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index 4051a4a..c10d909 100644
--- a/src/test/regress/parallel_schedule
+++ b/src/test/regress/parallel_schedule
@@ -110,7 +110,12 @@ test: publication subscription
 # ----------
 # Another group of parallel tests
 # ----------
-test: select_views portals_p2 foreign_key cluster dependency guc bitmapops combocid tsearch tsdicts foreign_data window xmlmap functional_deps advisory_lock json jsonb json_encoding indirect_toast equivclass
+test: select_views portals_p2 foreign_key cluster dependency guc bitmapops combocid tsearch tsdicts foreign_data window xmlmap functional_deps advisory_lock indirect_toast equivclass
+
+# ----------
+# Another group of parallel tests (JSON related)
+# ----------
+test: json jsonb json_encoding jsonpath jsonb_jsonpath
 
 # ----------
 # Another group of parallel tests
diff --git a/src/test/regress/serial_schedule b/src/test/regress/serial_schedule
index ac1ea62..d2bf88b 100644
--- a/src/test/regress/serial_schedule
+++ b/src/test/regress/serial_schedule
@@ -157,6 +157,8 @@ test: advisory_lock
 test: json
 test: jsonb
 test: json_encoding
+test: jsonpath
+test: jsonb_jsonpath
 test: indirect_toast
 test: equivclass
 test: plancache
diff --git a/src/test/regress/sql/jsonb_jsonpath.sql b/src/test/regress/sql/jsonb_jsonpath.sql
new file mode 100644
index 0000000..bb5f97b
--- /dev/null
+++ b/src/test/regress/sql/jsonb_jsonpath.sql
@@ -0,0 +1,329 @@
+select jsonb '{"a": 12}' @? '$';
+select jsonb '{"a": 12}' @? '1';
+select jsonb '{"a": 12}' @? '$.a.b';
+select jsonb '{"a": 12}' @? '$.b';
+select jsonb '{"a": 12}' @? '$.a + 2';
+select jsonb '{"a": 12}' @? '$.b + 2';
+select jsonb '{"a": {"a": 12}}' @? '$.a.a';
+select jsonb '{"a": {"a": 12}}' @? '$.*.a';
+select jsonb '{"b": {"a": 12}}' @? '$.*.a';
+select jsonb '{"b": {"a": 12}}' @? '$.*.b';
+select jsonb '{"b": {"a": 12}}' @? 'strict $.*.b';
+select jsonb '{}' @? '$.*';
+select jsonb '{"a": 1}' @? '$.*';
+select jsonb '{"a": {"b": 1}}' @? 'lax $.**{1}';
+select jsonb '{"a": {"b": 1}}' @? 'lax $.**{2}';
+select jsonb '{"a": {"b": 1}}' @? 'lax $.**{3}';
+select jsonb '[]' @? '$[*]';
+select jsonb '[1]' @? '$[*]';
+select jsonb '[1]' @? '$[1]';
+select jsonb '[1]' @? 'strict $[1]';
+select jsonb_path_query('[1]', 'strict $[1]');
+select jsonb '[1]' @? 'lax $[10000000000000000]';
+select jsonb '[1]' @? 'strict $[10000000000000000]';
+select jsonb_path_query('[1]', 'lax $[10000000000000000]');
+select jsonb_path_query('[1]', 'strict $[10000000000000000]');
+select jsonb '[1]' @? '$[0]';
+select jsonb '[1]' @? '$[0.3]';
+select jsonb '[1]' @? '$[0.5]';
+select jsonb '[1]' @? '$[0.9]';
+select jsonb '[1]' @? '$[1.2]';
+select jsonb '[1]' @? 'strict $[1.2]';
+select jsonb '{"a": [1,2,3], "b": [3,4,5]}' @? '$ ? (@.a[*] >  @.b[*])';
+select jsonb '{"a": [1,2,3], "b": [3,4,5]}' @? '$ ? (@.a[*] >= @.b[*])';
+select jsonb '{"a": [1,2,3], "b": [3,4,"5"]}' @? '$ ? (@.a[*] >= @.b[*])';
+select jsonb '{"a": [1,2,3], "b": [3,4,"5"]}' @? 'strict $ ? (@.a[*] >= @.b[*])';
+select jsonb '{"a": [1,2,3], "b": [3,4,null]}' @? '$ ? (@.a[*] >= @.b[*])';
+select jsonb '1' @? '$ ? ((@ == "1") is unknown)';
+select jsonb '1' @? '$ ? ((@ == 1) is unknown)';
+select jsonb '[{"a": 1}, {"a": 2}]' @? '$[0 to 1] ? (@.a > 1)';
+
+select jsonb_path_query('1', 'lax $.a');
+select jsonb_path_query('1', 'strict $.a');
+select jsonb_path_query('1', 'strict $.*');
+select jsonb_path_query('[]', 'lax $.a');
+select jsonb_path_query('[]', 'strict $.a');
+select jsonb_path_query('{}', 'lax $.a');
+select jsonb_path_query('{}', 'strict $.a');
+
+select jsonb_path_query('1', 'strict $[1]');
+select jsonb_path_query('1', 'strict $[*]');
+select jsonb_path_query('[]', 'strict $[1]');
+select jsonb_path_query('[]', 'strict $["a"]');
+
+select jsonb_path_query('{"a": 12, "b": {"a": 13}}', '$.a');
+select jsonb_path_query('{"a": 12, "b": {"a": 13}}', '$.b');
+select jsonb_path_query('{"a": 12, "b": {"a": 13}}', '$.*');
+select jsonb_path_query('{"a": 12, "b": {"a": 13}}', 'lax $.*.a');
+select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[*].a');
+select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[*].*');
+select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[0].a');
+select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[1].a');
+select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[2].a');
+select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[0,1].a');
+select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[0 to 10].a');
+select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[0 to 10 / 0].a');
+select jsonb_path_query('[12, {"a": 13}, {"b": 14}, "ccc", true]', '$[2.5 - 1 to $.size() - 2]');
+select jsonb_path_query('1', 'lax $[0]');
+select jsonb_path_query('1', 'lax $[*]');
+select jsonb_path_query('[1]', 'lax $[0]');
+select jsonb_path_query('[1]', 'lax $[*]');
+select jsonb_path_query('[1,2,3]', 'lax $[*]');
+select jsonb_path_query('[1,2,3]', 'strict $[*].a');
+select jsonb_path_query('[]', '$[last]');
+select jsonb_path_query('[]', '$[last ? (exists(last))]');
+select jsonb_path_query('[]', 'strict $[last]');
+select jsonb_path_query('[1]', '$[last]');
+select jsonb_path_query('[1,2,3]', '$[last]');
+select jsonb_path_query('[1,2,3]', '$[last - 1]');
+select jsonb_path_query('[1,2,3]', '$[last ? (@.type() == "number")]');
+select jsonb_path_query('[1,2,3]', '$[last ? (@.type() == "string")]');
+
+select * from jsonb_path_query('{"a": 10}', '$');
+select * from jsonb_path_query('{"a": 10}', '$ ? (@.a < $value)');
+select * from jsonb_path_query('{"a": 10}', '$ ? (@.a < $value)', '1');
+select * from jsonb_path_query('{"a": 10}', '$ ? (@.a < $value)', '[{"value" : 13}]');
+select * from jsonb_path_query('{"a": 10}', '$ ? (@.a < $value)', '{"value" : 13}');
+select * from jsonb_path_query('{"a": 10}', '$ ? (@.a < $value)', '{"value" : 8}');
+select * from jsonb_path_query('{"a": 10}', '$.a ? (@ < $value)', '{"value" : 13}');
+select * from jsonb_path_query('[10,11,12,13,14,15]', '$[*] ? (@ < $value)', '{"value" : 13}');
+select * from jsonb_path_query('[10,11,12,13,14,15]', '$[0,1] ? (@ < $x.value)', '{"x": {"value" : 13}}');
+select * from jsonb_path_query('[10,11,12,13,14,15]', '$[0 to 2] ? (@ < $value)', '{"value" : 15}');
+select * from jsonb_path_query('[1,"1",2,"2",null]', '$[*] ? (@ == "1")');
+select * from jsonb_path_query('[1,"1",2,"2",null]', '$[*] ? (@ == $value)', '{"value" : "1"}');
+select * from jsonb_path_query('[1,"1",2,"2",null]', '$[*] ? (@ == $value)', '{"value" : null}');
+select * from jsonb_path_query('[1, "2", null]', '$[*] ? (@ != null)');
+select * from jsonb_path_query('[1, "2", null]', '$[*] ? (@ == null)');
+select * from jsonb_path_query('{}', '$ ? (@ == @)');
+select * from jsonb_path_query('[]', 'strict $ ? (@ == @)');
+
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**');
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{0}');
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{0 to last}');
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{1}');
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{1 to last}');
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{2}');
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{2 to last}');
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{3 to last}');
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{last}');
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**.b ? (@ > 0)');
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{0}.b ? (@ > 0)');
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{1}.b ? (@ > 0)');
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{0 to last}.b ? (@ > 0)');
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{1 to last}.b ? (@ > 0)');
+select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{1 to 2}.b ? (@ > 0)');
+select jsonb_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**.b ? (@ > 0)');
+select jsonb_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{0}.b ? (@ > 0)');
+select jsonb_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{1}.b ? (@ > 0)');
+select jsonb_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{0 to last}.b ? (@ > 0)');
+select jsonb_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{1 to last}.b ? (@ > 0)');
+select jsonb_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{1 to 2}.b ? (@ > 0)');
+select jsonb_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{2 to 3}.b ? (@ > 0)');
+
+select jsonb '{"a": {"b": 1}}' @? '$.**.b ? ( @ > 0)';
+select jsonb '{"a": {"b": 1}}' @? '$.**{0}.b ? ( @ > 0)';
+select jsonb '{"a": {"b": 1}}' @? '$.**{1}.b ? ( @ > 0)';
+select jsonb '{"a": {"b": 1}}' @? '$.**{0 to last}.b ? ( @ > 0)';
+select jsonb '{"a": {"b": 1}}' @? '$.**{1 to last}.b ? ( @ > 0)';
+select jsonb '{"a": {"b": 1}}' @? '$.**{1 to 2}.b ? ( @ > 0)';
+select jsonb '{"a": {"c": {"b": 1}}}' @? '$.**.b ? ( @ > 0)';
+select jsonb '{"a": {"c": {"b": 1}}}' @? '$.**{0}.b ? ( @ > 0)';
+select jsonb '{"a": {"c": {"b": 1}}}' @? '$.**{1}.b ? ( @ > 0)';
+select jsonb '{"a": {"c": {"b": 1}}}' @? '$.**{0 to last}.b ? ( @ > 0)';
+select jsonb '{"a": {"c": {"b": 1}}}' @? '$.**{1 to last}.b ? ( @ > 0)';
+select jsonb '{"a": {"c": {"b": 1}}}' @? '$.**{1 to 2}.b ? ( @ > 0)';
+select jsonb '{"a": {"c": {"b": 1}}}' @? '$.**{2 to 3}.b ? ( @ > 0)';
+
+select jsonb_path_query('{"g": {"x": 2}}', '$.g ? (exists (@.x))');
+select jsonb_path_query('{"g": {"x": 2}}', '$.g ? (exists (@.y))');
+select jsonb_path_query('{"g": {"x": 2}}', '$.g ? (exists (@.x ? (@ >= 2) ))');
+select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'lax $.g ? (exists (@.x))');
+select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'lax $.g ? (exists (@.x + "3"))');
+select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'lax $.g ? ((exists (@.x + "3")) is unknown)');
+select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'strict $.g[*] ? (exists (@.x))');
+select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'strict $.g[*] ? ((exists (@.x)) is unknown)');
+select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'strict $.g ? (exists (@[*].x))');
+select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'strict $.g ? ((exists (@[*].x)) is unknown)');
+
+--test ternary logic
+select
+	x, y,
+	jsonb_path_query(
+		'[true, false, null]',
+		'$[*] ? (@ == true  &&  ($x == true && $y == true) ||
+				 @ == false && !($x == true && $y == true) ||
+				 @ == null  &&  ($x == true && $y == true) is unknown)',
+		jsonb_build_object('x', x, 'y', y)
+	) as "x && y"
+from
+	(values (jsonb 'true'), ('false'), ('"null"')) x(x),
+	(values (jsonb 'true'), ('false'), ('"null"')) y(y);
+
+select
+	x, y,
+	jsonb_path_query(
+		'[true, false, null]',
+		'$[*] ? (@ == true  &&  ($x == true || $y == true) ||
+				 @ == false && !($x == true || $y == true) ||
+				 @ == null  &&  ($x == true || $y == true) is unknown)',
+		jsonb_build_object('x', x, 'y', y)
+	) as "x || y"
+from
+	(values (jsonb 'true'), ('false'), ('"null"')) x(x),
+	(values (jsonb 'true'), ('false'), ('"null"')) y(y);
+
+select jsonb '{"a": 1, "b":1}' @? '$ ? (@.a == @.b)';
+select jsonb '{"c": {"a": 1, "b":1}}' @? '$ ? (@.a == @.b)';
+select jsonb '{"c": {"a": 1, "b":1}}' @? '$.c ? (@.a == @.b)';
+select jsonb '{"c": {"a": 1, "b":1}}' @? '$.c ? ($.c.a == @.b)';
+select jsonb '{"c": {"a": 1, "b":1}}' @? '$.* ? (@.a == @.b)';
+select jsonb '{"a": 1, "b":1}' @? '$.** ? (@.a == @.b)';
+select jsonb '{"c": {"a": 1, "b":1}}' @? '$.** ? (@.a == @.b)';
+
+select jsonb_path_query('{"c": {"a": 2, "b":1}}', '$.** ? (@.a == 1 + 1)');
+select jsonb_path_query('{"c": {"a": 2, "b":1}}', '$.** ? (@.a == (1 + 1))');
+select jsonb_path_query('{"c": {"a": 2, "b":1}}', '$.** ? (@.a == @.b + 1)');
+select jsonb_path_query('{"c": {"a": 2, "b":1}}', '$.** ? (@.a == (@.b + 1))');
+select jsonb '{"c": {"a": -1, "b":1}}' @? '$.** ? (@.a == - 1)';
+select jsonb '{"c": {"a": -1, "b":1}}' @? '$.** ? (@.a == -1)';
+select jsonb '{"c": {"a": -1, "b":1}}' @? '$.** ? (@.a == -@.b)';
+select jsonb '{"c": {"a": -1, "b":1}}' @? '$.** ? (@.a == - @.b)';
+select jsonb '{"c": {"a": 0, "b":1}}' @? '$.** ? (@.a == 1 - @.b)';
+select jsonb '{"c": {"a": 2, "b":1}}' @? '$.** ? (@.a == 1 - - @.b)';
+select jsonb '{"c": {"a": 0, "b":1}}' @? '$.** ? (@.a == 1 - +@.b)';
+select jsonb '[1,2,3]' @? '$ ? (+@[*] > +2)';
+select jsonb '[1,2,3]' @? '$ ? (+@[*] > +3)';
+select jsonb '[1,2,3]' @? '$ ? (-@[*] < -2)';
+select jsonb '[1,2,3]' @? '$ ? (-@[*] < -3)';
+select jsonb '1' @? '$ ? ($ > 0)';
+
+-- arithmetic errors
+select jsonb_path_query('[1,2,0,3]', '$[*] ? (2 / @ > 0)');
+select jsonb_path_query('[1,2,0,3]', '$[*] ? ((2 / @ > 0) is unknown)');
+select jsonb_path_query('0', '1 / $');
+select jsonb_path_query('0', '1 / $ + 2');
+select jsonb_path_query('0', '-(3 + 1 % $)');
+select jsonb_path_query('1', '$ + "2"');
+select jsonb_path_query('[1, 2]', '3 * $');
+select jsonb_path_query('"a"', '-$');
+select jsonb_path_query('[1,"2",3]', '+$');
+select jsonb '["1",2,0,3]' @? '-$[*]';
+select jsonb '[1,"2",0,3]' @? '-$[*]';
+select jsonb '["1",2,0,3]' @? 'strict -$[*]';
+select jsonb '[1,"2",0,3]' @? 'strict -$[*]';
+
+-- unwrapping of operator arguments in lax mode
+select jsonb_path_query('{"a": [2]}', 'lax $.a * 3');
+select jsonb_path_query('{"a": [2]}', 'lax $.a + 3');
+select jsonb_path_query('{"a": [2, 3, 4]}', 'lax -$.a');
+-- should fail
+select jsonb_path_query('{"a": [1, 2]}', 'lax $.a * 3');
+
+-- extension: boolean expressions
+select jsonb_path_query('2', '$ > 1');
+select jsonb_path_query('2', '$ <= 1');
+select jsonb_path_query('2', '$ == "2"');
+select jsonb '2' @? '$ == "2"';
+
+select jsonb '2' @@ '$ > 1';
+select jsonb '2' @@ '$ <= 1';
+select jsonb '2' @@ '$ == "2"';
+select jsonb '2' @@ '1';
+select jsonb '{}' @@ '$';
+select jsonb '[]' @@ '$';
+select jsonb '[1,2,3]' @@ '$[*]';
+select jsonb '[]' @@ '$[*]';
+select jsonb_path_match('[[1, true], [2, false]]', 'strict $[*] ? (@[0] > $x) [1]', '{"x": 1}');
+select jsonb_path_match('[[1, true], [2, false]]', 'strict $[*] ? (@[0] < $x) [1]', '{"x": 2}');
+
+select jsonb_path_query('[null,1,true,"a",[],{}]', '$.type()');
+select jsonb_path_query('[null,1,true,"a",[],{}]', 'lax $.type()');
+select jsonb_path_query('[null,1,true,"a",[],{}]', '$[*].type()');
+select jsonb_path_query('null', 'null.type()');
+select jsonb_path_query('null', 'true.type()');
+select jsonb_path_query('null', '123.type()');
+select jsonb_path_query('null', '"123".type()');
+
+select jsonb_path_query('{"a": 2}', '($.a - 5).abs() + 10');
+select jsonb_path_query('{"a": 2.5}', '-($.a * $.a).floor() % 4.3');
+select jsonb_path_query('[1, 2, 3]', '($[*] > 2) ? (@ == true)');
+select jsonb_path_query('[1, 2, 3]', '($[*] > 3).type()');
+select jsonb_path_query('[1, 2, 3]', '($[*].a > 3).type()');
+select jsonb_path_query('[1, 2, 3]', 'strict ($[*].a > 3).type()');
+
+select jsonb_path_query('[1,null,true,"11",[],[1],[1,2,3],{},{"a":1,"b":2}]', 'strict $[*].size()');
+select jsonb_path_query('[1,null,true,"11",[],[1],[1,2,3],{},{"a":1,"b":2}]', 'lax $[*].size()');
+
+select jsonb_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].abs()');
+select jsonb_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].floor()');
+select jsonb_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].ceiling()');
+select jsonb_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].ceiling().abs()');
+select jsonb_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].ceiling().abs().type()');
+
+select jsonb_path_query('[{},1]', '$[*].keyvalue()');
+select jsonb_path_query('{}', '$.keyvalue()');
+select jsonb_path_query('{"a": 1, "b": [1, 2], "c": {"a": "bbb"}}', '$.keyvalue()');
+select jsonb_path_query('[{"a": 1, "b": [1, 2]}, {"c": {"a": "bbb"}}]', '$[*].keyvalue()');
+select jsonb_path_query('[{"a": 1, "b": [1, 2]}, {"c": {"a": "bbb"}}]', 'strict $.keyvalue()');
+select jsonb_path_query('[{"a": 1, "b": [1, 2]}, {"c": {"a": "bbb"}}]', 'lax $.keyvalue()');
+select jsonb_path_query('[{"a": 1, "b": [1, 2]}, {"c": {"a": "bbb"}}]', 'strict $.keyvalue().a');
+select jsonb '{"a": 1, "b": [1, 2]}' @? 'lax $.keyvalue()';
+select jsonb '{"a": 1, "b": [1, 2]}' @? 'lax $.keyvalue().key';
+
+select jsonb_path_query('null', '$.double()');
+select jsonb_path_query('true', '$.double()');
+select jsonb_path_query('[]', '$.double()');
+select jsonb_path_query('[]', 'strict $.double()');
+select jsonb_path_query('{}', '$.double()');
+select jsonb_path_query('1.23', '$.double()');
+select jsonb_path_query('"1.23"', '$.double()');
+select jsonb_path_query('"1.23aaa"', '$.double()');
+select jsonb_path_query('"nan"', '$.double()');
+select jsonb_path_query('"NaN"', '$.double()');
+select jsonb_path_query('"inf"', '$.double()');
+select jsonb_path_query('"-inf"', '$.double()');
+
+select jsonb_path_query('{}', '$.abs()');
+select jsonb_path_query('true', '$.floor()');
+select jsonb_path_query('"1.2"', '$.ceiling()');
+
+select jsonb_path_query('["", "a", "abc", "abcabc"]', '$[*] ? (@ starts with "abc")');
+select jsonb_path_query('["", "a", "abc", "abcabc"]', 'strict $ ? (@[*] starts with "abc")');
+select jsonb_path_query('["", "a", "abd", "abdabc"]', 'strict $ ? (@[*] starts with "abc")');
+select jsonb_path_query('["abc", "abcabc", null, 1]', 'strict $ ? (@[*] starts with "abc")');
+select jsonb_path_query('["abc", "abcabc", null, 1]', 'strict $ ? ((@[*] starts with "abc") is unknown)');
+select jsonb_path_query('[[null, 1, "abc", "abcabc"]]', 'lax $ ? (@[*] starts with "abc")');
+select jsonb_path_query('[[null, 1, "abd", "abdabc"]]', 'lax $ ? ((@[*] starts with "abc") is unknown)');
+select jsonb_path_query('[null, 1, "abd", "abdabc"]', 'lax $[*] ? ((@ starts with "abc") is unknown)');
+
+select jsonb_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "adc\nabc", "babc"]', 'lax $[*] ? (@ like_regex "^ab.*c")');
+select jsonb_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "adc\nabc", "babc"]', 'lax $[*] ? (@ like_regex "^a  b.*  c " flag "ix")');
+select jsonb_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "adc\nabc", "babc"]', 'lax $[*] ? (@ like_regex "^ab.*c" flag "m")');
+select jsonb_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "adc\nabc", "babc"]', 'lax $[*] ? (@ like_regex "^ab.*c" flag "s")');
+
+-- jsonpath operators
+
+SELECT jsonb_path_query('[{"a": 1}, {"a": 2}]', '$[*]');
+SELECT jsonb_path_query('[{"a": 1}, {"a": 2}]', '$[*] ? (@.a > 10)');
+
+SELECT jsonb_path_query_array('[{"a": 1}, {"a": 2}, {}]', 'strict $[*].a');
+SELECT jsonb_path_query_array('[{"a": 1}, {"a": 2}]', '$[*].a');
+SELECT jsonb_path_query_array('[{"a": 1}, {"a": 2}]', '$[*].a ? (@ == 1)');
+SELECT jsonb_path_query_array('[{"a": 1}, {"a": 2}]', '$[*].a ? (@ > 10)');
+SELECT jsonb_path_query_array('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*].a ? (@ > $min && @ < $max)', '{"min": 1, "max": 4}');
+SELECT jsonb_path_query_array('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*].a ? (@ > $min && @ < $max)', '{"min": 3, "max": 4}');
+
+SELECT jsonb_path_query_first('[{"a": 1}, {"a": 2}, {}]', 'strict $[*].a');
+SELECT jsonb_path_query_first('[{"a": 1}, {"a": 2}]', '$[*].a');
+SELECT jsonb_path_query_first('[{"a": 1}, {"a": 2}]', '$[*].a ? (@ == 1)');
+SELECT jsonb_path_query_first('[{"a": 1}, {"a": 2}]', '$[*].a ? (@ > 10)');
+SELECT jsonb_path_query_first('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*].a ? (@ > $min && @ < $max)', '{"min": 1, "max": 4}');
+SELECT jsonb_path_query_first('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*].a ? (@ > $min && @ < $max)', '{"min": 3, "max": 4}');
+
+SELECT jsonb '[{"a": 1}, {"a": 2}]' @? '$[*].a ? (@ > 1)';
+SELECT jsonb '[{"a": 1}, {"a": 2}]' @? '$[*] ? (@.a > 2)';
+SELECT jsonb_path_exists('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*] ? (@.a > $min && @.a < $max)', '{"min": 1, "max": 4}');
+SELECT jsonb_path_exists('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*] ? (@.a > $min && @.a < $max)', '{"min": 3, "max": 4}');
+
+SELECT jsonb '[{"a": 1}, {"a": 2}]' @@ '$[*].a > 1';
+SELECT jsonb '[{"a": 1}, {"a": 2}]' @@ '$[*].a > 2';
diff --git a/src/test/regress/sql/jsonpath.sql b/src/test/regress/sql/jsonpath.sql
new file mode 100644
index 0000000..e5f3391
--- /dev/null
+++ b/src/test/regress/sql/jsonpath.sql
@@ -0,0 +1,147 @@
+--jsonpath io
+
+select ''::jsonpath;
+select '$'::jsonpath;
+select 'strict $'::jsonpath;
+select 'lax $'::jsonpath;
+select '$.a'::jsonpath;
+select '$.a.v'::jsonpath;
+select '$.a.*'::jsonpath;
+select '$.*[*]'::jsonpath;
+select '$.a[*]'::jsonpath;
+select '$.a[*][*]'::jsonpath;
+select '$[*]'::jsonpath;
+select '$[0]'::jsonpath;
+select '$[*][0]'::jsonpath;
+select '$[*].a'::jsonpath;
+select '$[*][0].a.b'::jsonpath;
+select '$.a.**.b'::jsonpath;
+select '$.a.**{2}.b'::jsonpath;
+select '$.a.**{2 to 2}.b'::jsonpath;
+select '$.a.**{2 to 5}.b'::jsonpath;
+select '$.a.**{0 to 5}.b'::jsonpath;
+select '$.a.**{5 to last}.b'::jsonpath;
+select '$.a.**{last}.b'::jsonpath;
+select '$.a.**{last to 5}.b'::jsonpath;
+select '$+1'::jsonpath;
+select '$-1'::jsonpath;
+select '$--+1'::jsonpath;
+select '$.a/+-1'::jsonpath;
+select '1 * 2 + 4 % -3 != false'::jsonpath;
+
+select '"\b\f\r\n\t\v\"\''\\"'::jsonpath;
+select '''\b\f\r\n\t\v\"\''\\'''::jsonpath;
+select '"\x50\u0067\u{53}\u{051}\u{00004C}"'::jsonpath;
+select '''\x50\u0067\u{53}\u{051}\u{00004C}'''::jsonpath;
+select '$.foo\x50\u0067\u{53}\u{051}\u{00004C}\t\"bar'::jsonpath;
+
+select '$.g ? ($.a == 1)'::jsonpath;
+select '$.g ? (@ == 1)'::jsonpath;
+select '$.g ? (@.a == 1)'::jsonpath;
+select '$.g ? (@.a == 1 || @.a == 4)'::jsonpath;
+select '$.g ? (@.a == 1 && @.a == 4)'::jsonpath;
+select '$.g ? (@.a == 1 || @.a == 4 && @.b == 7)'::jsonpath;
+select '$.g ? (@.a == 1 || !(@.a == 4) && @.b == 7)'::jsonpath;
+select '$.g ? (@.a == 1 || !(@.x >= 123 || @.a == 4) && @.b == 7)'::jsonpath;
+select '$.g ? (@.x >= @[*]?(@.a > "abc"))'::jsonpath;
+select '$.g ? ((@.x >= 123 || @.a == 4) is unknown)'::jsonpath;
+select '$.g ? (exists (@.x))'::jsonpath;
+select '$.g ? (exists (@.x ? (@ == 14)))'::jsonpath;
+select '$.g ? ((@.x >= 123 || @.a == 4) && exists (@.x ? (@ == 14)))'::jsonpath;
+select '$.g ? (+@.x >= +-(+@.a + 2))'::jsonpath;
+
+select '$a'::jsonpath;
+select '$a.b'::jsonpath;
+select '$a[*]'::jsonpath;
+select '$.g ? (@.zip == $zip)'::jsonpath;
+select '$.a[1,2, 3 to 16]'::jsonpath;
+select '$.a[$a + 1, ($b[*]) to -($[0] * 2)]'::jsonpath;
+select '$.a[$.a.size() - 3]'::jsonpath;
+select 'last'::jsonpath;
+select '"last"'::jsonpath;
+select '$.last'::jsonpath;
+select '$ ? (last > 0)'::jsonpath;
+select '$[last]'::jsonpath;
+select '$[$[0] ? (last > 0)]'::jsonpath;
+
+select 'null.type()'::jsonpath;
+select '1.type()'::jsonpath;
+select '"aaa".type()'::jsonpath;
+select 'true.type()'::jsonpath;
+select '$.double().floor().ceiling().abs()'::jsonpath;
+select '$.keyvalue().key'::jsonpath;
+
+select '$ ? (@ starts with "abc")'::jsonpath;
+select '$ ? (@ starts with $var)'::jsonpath;
+
+select '$ ? (@ like_regex "(invalid pattern")'::jsonpath;
+select '$ ? (@ like_regex "pattern")'::jsonpath;
+select '$ ? (@ like_regex "pattern" flag "")'::jsonpath;
+select '$ ? (@ like_regex "pattern" flag "i")'::jsonpath;
+select '$ ? (@ like_regex "pattern" flag "is")'::jsonpath;
+select '$ ? (@ like_regex "pattern" flag "isim")'::jsonpath;
+select '$ ? (@ like_regex "pattern" flag "xsms")'::jsonpath;
+select '$ ? (@ like_regex "pattern" flag "a")'::jsonpath;
+
+select '$ < 1'::jsonpath;
+select '($ < 1) || $.a.b <= $x'::jsonpath;
+select '@ + 1'::jsonpath;
+
+select '($).a.b'::jsonpath;
+select '($.a.b).c.d'::jsonpath;
+select '($.a.b + -$.x.y).c.d'::jsonpath;
+select '(-+$.a.b).c.d'::jsonpath;
+select '1 + ($.a.b + 2).c.d'::jsonpath;
+select '1 + ($.a.b > 2).c.d'::jsonpath;
+select '($)'::jsonpath;
+select '(($))'::jsonpath;
+select '((($ + 1)).a + ((2)).b ? ((((@ > 1)) || (exists(@.c)))))'::jsonpath;
+
+select '$ ? (@.a < 1)'::jsonpath;
+select '$ ? (@.a < -1)'::jsonpath;
+select '$ ? (@.a < +1)'::jsonpath;
+select '$ ? (@.a < .1)'::jsonpath;
+select '$ ? (@.a < -.1)'::jsonpath;
+select '$ ? (@.a < +.1)'::jsonpath;
+select '$ ? (@.a < 0.1)'::jsonpath;
+select '$ ? (@.a < -0.1)'::jsonpath;
+select '$ ? (@.a < +0.1)'::jsonpath;
+select '$ ? (@.a < 10.1)'::jsonpath;
+select '$ ? (@.a < -10.1)'::jsonpath;
+select '$ ? (@.a < +10.1)'::jsonpath;
+select '$ ? (@.a < 1e1)'::jsonpath;
+select '$ ? (@.a < -1e1)'::jsonpath;
+select '$ ? (@.a < +1e1)'::jsonpath;
+select '$ ? (@.a < .1e1)'::jsonpath;
+select '$ ? (@.a < -.1e1)'::jsonpath;
+select '$ ? (@.a < +.1e1)'::jsonpath;
+select '$ ? (@.a < 0.1e1)'::jsonpath;
+select '$ ? (@.a < -0.1e1)'::jsonpath;
+select '$ ? (@.a < +0.1e1)'::jsonpath;
+select '$ ? (@.a < 10.1e1)'::jsonpath;
+select '$ ? (@.a < -10.1e1)'::jsonpath;
+select '$ ? (@.a < +10.1e1)'::jsonpath;
+select '$ ? (@.a < 1e-1)'::jsonpath;
+select '$ ? (@.a < -1e-1)'::jsonpath;
+select '$ ? (@.a < +1e-1)'::jsonpath;
+select '$ ? (@.a < .1e-1)'::jsonpath;
+select '$ ? (@.a < -.1e-1)'::jsonpath;
+select '$ ? (@.a < +.1e-1)'::jsonpath;
+select '$ ? (@.a < 0.1e-1)'::jsonpath;
+select '$ ? (@.a < -0.1e-1)'::jsonpath;
+select '$ ? (@.a < +0.1e-1)'::jsonpath;
+select '$ ? (@.a < 10.1e-1)'::jsonpath;
+select '$ ? (@.a < -10.1e-1)'::jsonpath;
+select '$ ? (@.a < +10.1e-1)'::jsonpath;
+select '$ ? (@.a < 1e+1)'::jsonpath;
+select '$ ? (@.a < -1e+1)'::jsonpath;
+select '$ ? (@.a < +1e+1)'::jsonpath;
+select '$ ? (@.a < .1e+1)'::jsonpath;
+select '$ ? (@.a < -.1e+1)'::jsonpath;
+select '$ ? (@.a < +.1e+1)'::jsonpath;
+select '$ ? (@.a < 0.1e+1)'::jsonpath;
+select '$ ? (@.a < -0.1e+1)'::jsonpath;
+select '$ ? (@.a < +0.1e+1)'::jsonpath;
+select '$ ? (@.a < 10.1e+1)'::jsonpath;
+select '$ ? (@.a < -10.1e+1)'::jsonpath;
+select '$ ? (@.a < +10.1e+1)'::jsonpath;
diff --git a/src/tools/msvc/Mkvcbuild.pm b/src/tools/msvc/Mkvcbuild.pm
index f422503..726f2ba 100644
--- a/src/tools/msvc/Mkvcbuild.pm
+++ b/src/tools/msvc/Mkvcbuild.pm
@@ -179,6 +179,8 @@ sub mkvcbuild
 		'src/backend/replication', 'repl_scanner.l',
 		'repl_gram.y',             'syncrep_scanner.l',
 		'syncrep_gram.y');
+	$postgres->AddFiles('src/backend/utils/adt', 'jsonpath_scan.l',
+		'jsonpath_gram.y');
 	$postgres->AddDefine('BUILDING_DLL');
 	$postgres->AddLibrary('secur32.lib');
 	$postgres->AddLibrary('ws2_32.lib');
diff --git a/src/tools/msvc/Solution.pm b/src/tools/msvc/Solution.pm
index 2ea224d..90a8d69 100644
--- a/src/tools/msvc/Solution.pm
+++ b/src/tools/msvc/Solution.pm
@@ -327,6 +327,24 @@ sub GenerateFiles
 		);
 	}
 
+	if (IsNewer(
+			'src/backend/utils/adt/jsonpath_gram.h',
+			'src/backend/utils/adt/jsonpath_gram.y'))
+	{
+		print "Generating jsonpath_gram.h...\n";
+		chdir('src/backend/utils/adt');
+		system('perl ../../../tools/msvc/pgbison.pl jsonpath_gram.y');
+		chdir('../../../..');
+	}
+
+	if (IsNewer(
+			'src/include/utils/jsonpath_gram.h',
+			'src/backend/utils/adt/jsonpath_gram.h'))
+	{
+		copyFile('src/backend/utils/adt/jsonpath_gram.h',
+			'src/include/utils/jsonpath_gram.h');
+	}
+
 	if ($self->{options}->{python}
 		&& IsNewer(
 			'src/pl/plpython/spiexceptions.h',
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 3d3c76d..daaafa3 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -1095,14 +1095,31 @@ JoinType
 JsObject
 JsValue
 JsonAggState
+JsonBaseObjectInfo
 JsonHashEntry
+JsonItemStack
+JsonItemStackEntry
 JsonIterateStringValuesAction
 JsonLexContext
+JsonLikeRegexContext
 JsonParseContext
+JsonPath
+JsonPathBool
+JsonPathExecContext
+JsonPathExecResult
+JsonPathItem
+JsonPathItemType
+JsonPathParseItem
+JsonPathParseResult
+JsonPathPredicateCallback
+JsonPathVariable
+JsonPathVariable_cb
 JsonSemAction
 JsonTokenType
 JsonTransformStringValuesAction
 JsonTypeCategory
+JsonValueList
+JsonValueListIterator
 Jsonb
 JsonbAggState
 JsonbContainer
-- 
2.7.4

  [text/x-patch] 0002-Suppression-of-numeric-errors-in-jsonpath-v34.patch (21.4K, ../a3be6a7a-77d3-0e88-4f9d-4f725d11d7cd@postgrespro.ru/4-0002-Suppression-of-numeric-errors-in-jsonpath-v34.patch)
  download | inline diff:
From 0b566e392ed0dc6c5038d1a6dfb982a8e7c2d62c Mon Sep 17 00:00:00 2001
From: Nikita Glukhov <n.gluhov@postgrespro.ru>
Date: Fri, 1 Mar 2019 03:15:18 +0300
Subject: [PATCH 02/13] Suppression of numeric errors in jsonpath

---
 src/backend/utils/adt/float.c                |  54 +++++---
 src/backend/utils/adt/jsonpath_exec.c        |  76 +++++++----
 src/backend/utils/adt/numeric.c              | 190 +++++++++++++++++++++------
 src/include/utils/float.h                    |   2 +
 src/include/utils/numeric.h                  |   7 +
 src/test/regress/expected/jsonb_jsonpath.out |  35 ++++-
 6 files changed, 275 insertions(+), 89 deletions(-)

diff --git a/src/backend/utils/adt/float.c b/src/backend/utils/adt/float.c
index 37c202d..d338d36 100644
--- a/src/backend/utils/adt/float.c
+++ b/src/backend/utils/adt/float.c
@@ -336,6 +336,15 @@ float8in(PG_FUNCTION_ARGS)
 	PG_RETURN_FLOAT8(float8in_internal(num, NULL, "double precision", num));
 }
 
+#define float8in_ereport(code, msg) \
+	do { \
+		if (error) { \
+			*error = true; \
+			return (Datum) 0; \
+		} else \
+			ereport(ERROR, ((code), (msg))); \
+	} while (false) \
+
 /*
  * float8in_internal - guts of float8in()
  *
@@ -355,8 +364,8 @@ float8in(PG_FUNCTION_ARGS)
  * unreasonable amount of extra casting both here and in callers, so we don't.
  */
 double
-float8in_internal(char *num, char **endptr_p,
-				  const char *type_name, const char *orig_string)
+float8in_internal_error(char *num, char **endptr_p,
+				  const char *type_name, const char *orig_string, bool *error)
 {
 	double		val;
 	char	   *endptr;
@@ -370,10 +379,10 @@ float8in_internal(char *num, char **endptr_p,
 	 * strtod() on different platforms.
 	 */
 	if (*num == '\0')
-		ereport(ERROR,
-				(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
-				 errmsg("invalid input syntax for type %s: \"%s\"",
-						type_name, orig_string)));
+		float8in_ereport(
+				errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
+				errmsg("invalid input syntax for type %s: \"%s\"",
+						type_name, orig_string));
 
 	errno = 0;
 	val = strtod(num, &endptr);
@@ -446,17 +455,17 @@ float8in_internal(char *num, char **endptr_p,
 				char	   *errnumber = pstrdup(num);
 
 				errnumber[endptr - num] = '\0';
-				ereport(ERROR,
-						(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
-						 errmsg("\"%s\" is out of range for type double precision",
-								errnumber)));
+				float8in_ereport(
+						errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
+						errmsg("\"%s\" is out of range for type double precision",
+								errnumber));
 			}
 		}
 		else
-			ereport(ERROR,
-					(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
-					 errmsg("invalid input syntax for type %s: \"%s\"",
-							type_name, orig_string)));
+			float8in_ereport(
+					errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
+					errmsg("invalid input syntax for type %s: \"%s\"",
+							type_name, orig_string));
 	}
 #ifdef HAVE_BUGGY_SOLARIS_STRTOD
 	else
@@ -479,14 +488,23 @@ float8in_internal(char *num, char **endptr_p,
 	if (endptr_p)
 		*endptr_p = endptr;
 	else if (*endptr != '\0')
-		ereport(ERROR,
-				(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
-				 errmsg("invalid input syntax for type %s: \"%s\"",
-						type_name, orig_string)));
+		float8in_ereport(
+				errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
+				errmsg("invalid input syntax for type %s: \"%s\"",
+						type_name, orig_string));
 
 	return val;
 }
 
+double
+float8in_internal(char *num, char **endptr_p,
+				  const char *type_name, const char *orig_string)
+{
+	return float8in_internal_error(num, endptr_p, type_name,
+								   orig_string, NULL);
+}
+
+
 /*
  *		float8out		- converts float8 number to a string
  *						  using a standard output format
diff --git a/src/backend/utils/adt/jsonpath_exec.c b/src/backend/utils/adt/jsonpath_exec.c
index 87f432b..c6a5073 100644
--- a/src/backend/utils/adt/jsonpath_exec.c
+++ b/src/backend/utils/adt/jsonpath_exec.c
@@ -179,6 +179,8 @@ typedef JsonPathBool (*JsonPathPredicateCallback) (JsonPathItem *jsp,
 												   JsonbValue *rarg,
 												   void *param);
 
+typedef Numeric (*BinaryArithmFunc) (Numeric num1, Numeric num2, bool *error);
+
 static JsonPathExecResult executeJsonPath(JsonPath *path, Jsonb *vars,
 				Jsonb *json, bool throwErrors, JsonValueList *result);
 static JsonPathExecResult recursiveExecute(JsonPathExecContext *cxt,
@@ -209,7 +211,7 @@ static JsonPathBool executePredicate(JsonPathExecContext *cxt,
 				 JsonbValue *jb, bool unwrapRightArg,
 				 JsonPathPredicateCallback exec, void *param);
 static JsonPathExecResult executeBinaryArithmExpr(JsonPathExecContext *cxt,
-						JsonPathItem *jsp, JsonbValue *jb, PGFunction func,
+						JsonPathItem *jsp, JsonbValue *jb, BinaryArithmFunc func,
 						JsonValueList *found);
 static JsonPathExecResult executeUnaryArithmExpr(JsonPathExecContext *cxt,
 					   JsonPathItem *jsp, JsonbValue *jb, PGFunction func,
@@ -826,23 +828,23 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 
 		case jpiAdd:
 			return executeBinaryArithmExpr(cxt, jsp, jb,
-										   numeric_add, found);
+										   numeric_add_error, found);
 
 		case jpiSub:
 			return executeBinaryArithmExpr(cxt, jsp, jb,
-										   numeric_sub, found);
+										   numeric_sub_error, found);
 
 		case jpiMul:
 			return executeBinaryArithmExpr(cxt, jsp, jb,
-										   numeric_mul, found);
+										   numeric_mul_error, found);
 
 		case jpiDiv:
 			return executeBinaryArithmExpr(cxt, jsp, jb,
-										   numeric_div, found);
+										   numeric_div_error, found);
 
 		case jpiMod:
 			return executeBinaryArithmExpr(cxt, jsp, jb,
-										   numeric_mod, found);
+										   numeric_mod_error, found);
 
 		case jpiPlus:
 			return executeUnaryArithmExpr(cxt, jsp, jb, NULL, found);
@@ -994,27 +996,39 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 				{
 					char	   *tmp = DatumGetCString(DirectFunctionCall1(numeric_out,
 																		  NumericGetDatum(jb->val.numeric)));
+					bool		error = false;
+
+					(void) float8in_internal_error(tmp,
+											NULL,
+											"double precision",
+											tmp,
+											&error);
 
-					(void) float8in_internal(tmp,
-											 NULL,
-											 "double precision",
-											 tmp);
+					if (error)
+						RETURN_ERROR(ereport(ERROR,
+											 (errcode(ERRCODE_NON_NUMERIC_JSON_ITEM),
+											  errmsg(ERRMSG_NON_NUMERIC_JSON_ITEM),
+											  errdetail("jsonpath item method .%s() is "
+														"applied to not a numeric value",
+														jspOperationName(jsp->type)))));
 
 					res = jperOk;
 				}
 				else if (jb->type == jbvString)
 				{
 					/* cast string as double */
+					bool		error = false;
 					double		val;
 					char	   *tmp = pnstrdup(jb->val.string.val,
 											   jb->val.string.len);
 
-					val = float8in_internal(tmp,
-											NULL,
-											"double precision",
-											tmp);
+					val = float8in_internal_error(tmp,
+												  NULL,
+												  "double precision",
+												  tmp,
+												  &error);
 
-					if (isinf(val))
+					if (error || isinf(val))
 						RETURN_ERROR(ereport(ERROR,
 											 (errcode(ERRCODE_NON_NUMERIC_JSON_ITEM),
 											  errmsg(ERRMSG_NON_NUMERIC_JSON_ITEM),
@@ -1482,7 +1496,7 @@ executePredicate(JsonPathExecContext *cxt, JsonPathItem *pred,
  */
 static JsonPathExecResult
 executeBinaryArithmExpr(JsonPathExecContext *cxt, JsonPathItem *jsp,
-						JsonbValue *jb, PGFunction func,
+						JsonbValue *jb, BinaryArithmFunc func,
 						JsonValueList *found)
 {
 	JsonPathExecResult jper;
@@ -1491,7 +1505,7 @@ executeBinaryArithmExpr(JsonPathExecContext *cxt, JsonPathItem *jsp,
 	JsonValueList rseq = {0};
 	JsonbValue *lval;
 	JsonbValue *rval;
-	Datum		res;
+	Numeric		res;
 
 	jspGetLeftArg(jsp, &elem);
 
@@ -1527,16 +1541,26 @@ executeBinaryArithmExpr(JsonPathExecContext *cxt, JsonPathItem *jsp,
 										"is not a singleton numeric value",
 										jspOperationName(jsp->type)))));
 
-	res = DirectFunctionCall2(func,
-							  NumericGetDatum(lval->val.numeric),
-							  NumericGetDatum(rval->val.numeric));
+	if (jspThrowErrors(cxt))
+	{
+		res = func(lval->val.numeric, rval->val.numeric, NULL);
+	}
+	else
+	{
+		bool	error = false;
+
+		res = func(lval->val.numeric, rval->val.numeric, &error);
+
+		if (error)
+			return jperError;
+	}
 
 	if (!jspGetNext(jsp, &elem) && !found)
 		return jperOk;
 
 	lval = palloc(sizeof(*lval));
 	lval->type = jbvNumeric;
-	lval->val.numeric = DatumGetNumeric(res);
+	lval->val.numeric = res;
 
 	return recursiveExecuteNext(cxt, jsp, &elem, lval, found, false);
 }
@@ -2089,6 +2113,7 @@ getArrayIndex(JsonPathExecContext *cxt, JsonPathItem *jsp, JsonbValue *jb,
 	JsonValueList found = {0};
 	JsonPathExecResult res = recursiveExecute(cxt, jsp, jb, &found);
 	Datum		numeric_index;
+	bool		error = false;
 
 	if (jperIsError(res))
 		return res;
@@ -2105,7 +2130,14 @@ getArrayIndex(JsonPathExecContext *cxt, JsonPathItem *jsp, JsonbValue *jb,
 										NumericGetDatum(jbv->val.numeric),
 										Int32GetDatum(0));
 
-	*index = DatumGetInt32(DirectFunctionCall1(numeric_int4, numeric_index));
+	*index = numeric_int4_error(DatumGetNumeric(numeric_index), &error);
+
+	if (error)
+		RETURN_ERROR(ereport(ERROR,
+							 (errcode(ERRCODE_INVALID_JSON_SUBSCRIPT),
+							  errmsg(ERRMSG_INVALID_JSON_SUBSCRIPT),
+							  errdetail("jsonpath array subscript is out of "
+										"integer range"))));
 
 	return jperOk;
 }
diff --git a/src/backend/utils/adt/numeric.c b/src/backend/utils/adt/numeric.c
index 1c9deeb..38c3313 100644
--- a/src/backend/utils/adt/numeric.c
+++ b/src/backend/utils/adt/numeric.c
@@ -475,10 +475,11 @@ static char *get_str_from_var(const NumericVar *var);
 static char *get_str_from_var_sci(const NumericVar *var, int rscale);
 
 static Numeric make_result(const NumericVar *var);
+static Numeric make_result_error(const NumericVar *var, bool *error);
 
 static void apply_typmod(NumericVar *var, int32 typmod);
 
-static int32 numericvar_to_int32(const NumericVar *var);
+static bool numericvar_to_int32(const NumericVar *var, int32 *result);
 static bool numericvar_to_int64(const NumericVar *var, int64 *result);
 static void int64_to_numericvar(int64 val, NumericVar *var);
 #ifdef HAVE_INT128
@@ -1558,7 +1559,10 @@ width_bucket_numeric(PG_FUNCTION_ARGS)
 	}
 
 	/* if result exceeds the range of a legal int4, we ereport here */
-	result = numericvar_to_int32(&result_var);
+	if (!numericvar_to_int32(&result_var, &result))
+		ereport(ERROR,
+				(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
+				 errmsg("integer out of range")));
 
 	free_var(&count_var);
 	free_var(&result_var);
@@ -2406,6 +2410,17 @@ numeric_add(PG_FUNCTION_ARGS)
 {
 	Numeric		num1 = PG_GETARG_NUMERIC(0);
 	Numeric		num2 = PG_GETARG_NUMERIC(1);
+	Numeric		res;
+
+	res = numeric_add_error(num1, num2, NULL);
+
+	PG_RETURN_NUMERIC(res);
+}
+
+
+Numeric
+numeric_add_error(Numeric num1, Numeric num2, bool *error)
+{
 	NumericVar	arg1;
 	NumericVar	arg2;
 	NumericVar	result;
@@ -2415,7 +2430,7 @@ numeric_add(PG_FUNCTION_ARGS)
 	 * Handle NaN
 	 */
 	if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
-		PG_RETURN_NUMERIC(make_result(&const_nan));
+		return make_result(&const_nan);
 
 	/*
 	 * Unpack the values, let add_var() compute the result and return it.
@@ -2426,11 +2441,11 @@ numeric_add(PG_FUNCTION_ARGS)
 	init_var(&result);
 	add_var(&arg1, &arg2, &result);
 
-	res = make_result(&result);
+	res = make_result_error(&result, error);
 
 	free_var(&result);
 
-	PG_RETURN_NUMERIC(res);
+	return res;
 }
 
 
@@ -2444,6 +2459,17 @@ numeric_sub(PG_FUNCTION_ARGS)
 {
 	Numeric		num1 = PG_GETARG_NUMERIC(0);
 	Numeric		num2 = PG_GETARG_NUMERIC(1);
+	Numeric		res;
+
+	res = numeric_sub_error(num1, num2, NULL);
+
+	PG_RETURN_NUMERIC(res);
+}
+
+
+Numeric
+numeric_sub_error(Numeric num1, Numeric num2, bool *error)
+{
 	NumericVar	arg1;
 	NumericVar	arg2;
 	NumericVar	result;
@@ -2453,7 +2479,7 @@ numeric_sub(PG_FUNCTION_ARGS)
 	 * Handle NaN
 	 */
 	if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
-		PG_RETURN_NUMERIC(make_result(&const_nan));
+		return make_result(&const_nan);
 
 	/*
 	 * Unpack the values, let sub_var() compute the result and return it.
@@ -2464,11 +2490,11 @@ numeric_sub(PG_FUNCTION_ARGS)
 	init_var(&result);
 	sub_var(&arg1, &arg2, &result);
 
-	res = make_result(&result);
+	res = make_result_error(&result, error);
 
 	free_var(&result);
 
-	PG_RETURN_NUMERIC(res);
+	return res;
 }
 
 
@@ -2482,6 +2508,17 @@ numeric_mul(PG_FUNCTION_ARGS)
 {
 	Numeric		num1 = PG_GETARG_NUMERIC(0);
 	Numeric		num2 = PG_GETARG_NUMERIC(1);
+	Numeric		res;
+
+	res = numeric_mul_error(num1, num2, NULL);
+
+	PG_RETURN_NUMERIC(res);
+}
+
+
+Numeric
+numeric_mul_error(Numeric num1, Numeric num2, bool *error)
+{
 	NumericVar	arg1;
 	NumericVar	arg2;
 	NumericVar	result;
@@ -2491,7 +2528,7 @@ numeric_mul(PG_FUNCTION_ARGS)
 	 * Handle NaN
 	 */
 	if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
-		PG_RETURN_NUMERIC(make_result(&const_nan));
+		return make_result(&const_nan);
 
 	/*
 	 * Unpack the values, let mul_var() compute the result and return it.
@@ -2506,11 +2543,11 @@ numeric_mul(PG_FUNCTION_ARGS)
 	init_var(&result);
 	mul_var(&arg1, &arg2, &result, arg1.dscale + arg2.dscale);
 
-	res = make_result(&result);
+	res = make_result_error(&result, error);
 
 	free_var(&result);
 
-	PG_RETURN_NUMERIC(res);
+	return res;
 }
 
 
@@ -2524,6 +2561,17 @@ numeric_div(PG_FUNCTION_ARGS)
 {
 	Numeric		num1 = PG_GETARG_NUMERIC(0);
 	Numeric		num2 = PG_GETARG_NUMERIC(1);
+	Numeric		res;
+
+	res = numeric_div_error(num1, num2, NULL);
+
+	PG_RETURN_NUMERIC(res);
+}
+
+
+Numeric
+numeric_div_error(Numeric num1, Numeric num2, bool *error)
+{
 	NumericVar	arg1;
 	NumericVar	arg2;
 	NumericVar	result;
@@ -2534,7 +2582,7 @@ numeric_div(PG_FUNCTION_ARGS)
 	 * Handle NaN
 	 */
 	if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
-		PG_RETURN_NUMERIC(make_result(&const_nan));
+		return make_result(&const_nan);
 
 	/*
 	 * Unpack the arguments
@@ -2552,13 +2600,19 @@ numeric_div(PG_FUNCTION_ARGS)
 	/*
 	 * Do the divide and return the result
 	 */
+	if (error && (arg2.ndigits == 0 || arg2.digits[0] == 0))
+	{
+		*error = true;
+		return NULL;
+	}
+
 	div_var(&arg1, &arg2, &result, rscale, true);
 
-	res = make_result(&result);
+	res = make_result_error(&result, error);
 
 	free_var(&result);
 
-	PG_RETURN_NUMERIC(res);
+	return res;
 }
 
 
@@ -2615,25 +2669,42 @@ numeric_mod(PG_FUNCTION_ARGS)
 	Numeric		num1 = PG_GETARG_NUMERIC(0);
 	Numeric		num2 = PG_GETARG_NUMERIC(1);
 	Numeric		res;
+
+	res = numeric_mod_error(num1, num2, NULL);
+
+	PG_RETURN_NUMERIC(res);
+}
+
+
+Numeric
+numeric_mod_error(Numeric num1, Numeric num2, bool *error)
+{
+	Numeric		res;
 	NumericVar	arg1;
 	NumericVar	arg2;
 	NumericVar	result;
 
 	if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
-		PG_RETURN_NUMERIC(make_result(&const_nan));
+		return make_result(&const_nan);
 
 	init_var_from_num(num1, &arg1);
 	init_var_from_num(num2, &arg2);
 
 	init_var(&result);
 
+	if (error && (arg2.ndigits == 0 || arg2.digits[0] == 0))
+	{
+		*error = true;
+		return NULL;
+	}
+
 	mod_var(&arg1, &arg2, &result);
 
-	res = make_result(&result);
+	res = make_result_error(&result, NULL);
 
 	free_var(&result);
 
-	PG_RETURN_NUMERIC(res);
+	return res;
 }
 
 
@@ -3090,52 +3161,71 @@ int4_numeric(PG_FUNCTION_ARGS)
 	PG_RETURN_NUMERIC(res);
 }
 
-
-Datum
-numeric_int4(PG_FUNCTION_ARGS)
+int32
+numeric_int4_error(Numeric num, bool *error)
 {
-	Numeric		num = PG_GETARG_NUMERIC(0);
 	NumericVar	x;
 	int32		result;
 
 	/* XXX would it be better to return NULL? */
 	if (NUMERIC_IS_NAN(num))
+	{
+		if (error)
+		{
+			*error = true;
+			return 0;
+		}
+
 		ereport(ERROR,
 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 				 errmsg("cannot convert NaN to integer")));
+	}
 
 	/* Convert to variable format, then convert to int4 */
 	init_var_from_num(num, &x);
-	result = numericvar_to_int32(&x);
-	PG_RETURN_INT32(result);
+
+	if (!numericvar_to_int32(&x, &result))
+	{
+		if (error)
+		{
+			*error = true;
+			return 0;
+		}
+
+		ereport(ERROR,
+				(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
+				 errmsg("integer out of range")));
+	}
+
+	return result;
+}
+
+Datum
+numeric_int4(PG_FUNCTION_ARGS)
+{
+	Numeric		num = PG_GETARG_NUMERIC(0);
+
+	PG_RETURN_INT32(numeric_int4_error(num, NULL));
 }
 
 /*
  * Given a NumericVar, convert it to an int32. If the NumericVar
- * exceeds the range of an int32, raise the appropriate error via
- * ereport(). The input NumericVar is *not* free'd.
+ * exceeds the range of an int32, false is returned, otherwise true is returned.
+ * The input NumericVar is *not* free'd.
  */
-static int32
-numericvar_to_int32(const NumericVar *var)
+static bool
+numericvar_to_int32(const NumericVar *var, int32 *result)
 {
-	int32		result;
 	int64		val;
 
 	if (!numericvar_to_int64(var, &val))
-		ereport(ERROR,
-				(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
-				 errmsg("integer out of range")));
+		return false;
 
 	/* Down-convert to int4 */
-	result = (int32) val;
+	*result = (int32) val;
 
 	/* Test for overflow by reverse-conversion. */
-	if ((int64) result != val)
-		ereport(ERROR,
-				(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
-				 errmsg("integer out of range")));
-
-	return result;
+	return ((int64) *result == val);
 }
 
 Datum
@@ -6097,6 +6187,12 @@ get_str_from_var_sci(const NumericVar *var, int rscale)
 }
 
 
+static Numeric
+make_result(const NumericVar *var)
+{
+	return make_result_error(var, NULL);
+}
+
 /*
  * make_result() -
  *
@@ -6104,7 +6200,7 @@ get_str_from_var_sci(const NumericVar *var, int rscale)
  *	a variable.
  */
 static Numeric
-make_result(const NumericVar *var)
+make_result_error(const NumericVar *var, bool *error)
 {
 	Numeric		result;
 	NumericDigit *digits = var->digits;
@@ -6175,9 +6271,19 @@ make_result(const NumericVar *var)
 	/* Check for overflow of int16 fields */
 	if (NUMERIC_WEIGHT(result) != weight ||
 		NUMERIC_DSCALE(result) != var->dscale)
-		ereport(ERROR,
-				(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
-				 errmsg("value overflows numeric format")));
+	{
+		if (error)
+		{
+			*error = true;
+			return NULL;
+		}
+		else
+		{
+			ereport(ERROR,
+					(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
+					 errmsg("value overflows numeric format")));
+		}
+	}
 
 	dump_numeric("make_result()", result);
 	return result;
diff --git a/src/include/utils/float.h b/src/include/utils/float.h
index 0f82a25..b4599e8 100644
--- a/src/include/utils/float.h
+++ b/src/include/utils/float.h
@@ -40,6 +40,8 @@ extern PGDLLIMPORT int extra_float_digits;
 extern int	is_infinite(float8 val);
 extern float8 float8in_internal(char *num, char **endptr_p,
 				  const char *type_name, const char *orig_string);
+extern float8 float8in_internal_error(char *num, char **endptr_p,
+				  const char *type_name, const char *orig_string, bool *error);
 extern char *float8out_internal(float8 num);
 extern int	float4_cmp_internal(float4 a, float4 b);
 extern int	float8_cmp_internal(float8 a, float8 b);
diff --git a/src/include/utils/numeric.h b/src/include/utils/numeric.h
index 9109cff..199f202 100644
--- a/src/include/utils/numeric.h
+++ b/src/include/utils/numeric.h
@@ -61,4 +61,11 @@ int32		numeric_maximum_size(int32 typmod);
 extern char *numeric_out_sci(Numeric num, int scale);
 extern char *numeric_normalize(Numeric num);
 
+extern Numeric numeric_add_error(Numeric num1, Numeric num2, bool *error);
+extern Numeric numeric_sub_error(Numeric num1, Numeric num2, bool *error);
+extern Numeric numeric_mul_error(Numeric num1, Numeric num2, bool *error);
+extern Numeric numeric_div_error(Numeric num1, Numeric num2, bool *error);
+extern Numeric numeric_mod_error(Numeric num1, Numeric num2, bool *error);
+extern int32 numeric_int4_error(Numeric num, bool *error);
+
 #endif							/* _PG_NUMERIC_H_ */
diff --git a/src/test/regress/expected/jsonb_jsonpath.out b/src/test/regress/expected/jsonb_jsonpath.out
index f295b92..2202ffa 100644
--- a/src/test/regress/expected/jsonb_jsonpath.out
+++ b/src/test/regress/expected/jsonb_jsonpath.out
@@ -122,13 +122,23 @@ select jsonb_path_query('[1]', 'strict $[1]');
 ERROR:  invalid SQL/JSON subscript
 DETAIL:  jsonpath array subscript is out of bounds
 select jsonb '[1]' @? 'lax $[10000000000000000]';
-ERROR:  integer out of range
+ ?column? 
+----------
+ 
+(1 row)
+
 select jsonb '[1]' @? 'strict $[10000000000000000]';
-ERROR:  integer out of range
+ ?column? 
+----------
+ 
+(1 row)
+
 select jsonb_path_query('[1]', 'lax $[10000000000000000]');
-ERROR:  integer out of range
+ERROR:  invalid SQL/JSON subscript
+DETAIL:  jsonpath array subscript is out of integer range
 select jsonb_path_query('[1]', 'strict $[10000000000000000]');
-ERROR:  integer out of range
+ERROR:  invalid SQL/JSON subscript
+DETAIL:  jsonpath array subscript is out of integer range
 select jsonb '[1]' @? '$[0]';
  ?column? 
 ----------
@@ -956,9 +966,19 @@ select jsonb '1' @? '$ ? ($ > 0)';
 
 -- arithmetic errors
 select jsonb_path_query('[1,2,0,3]', '$[*] ? (2 / @ > 0)');
-ERROR:  division by zero
+ jsonb_path_query 
+------------------
+ 1
+ 2
+ 3
+(3 rows)
+
 select jsonb_path_query('[1,2,0,3]', '$[*] ? ((2 / @ > 0) is unknown)');
-ERROR:  division by zero
+ jsonb_path_query 
+------------------
+ 0
+(1 row)
+
 select jsonb_path_query('0', '1 / $');
 ERROR:  division by zero
 select jsonb_path_query('0', '1 / $ + 2');
@@ -1341,7 +1361,8 @@ select jsonb_path_query('"1.23"', '$.double()');
 (1 row)
 
 select jsonb_path_query('"1.23aaa"', '$.double()');
-ERROR:  invalid input syntax for type double precision: "1.23aaa"
+ERROR:  non-numeric SQL/JSON item
+DETAIL:  jsonpath item method .double() is applied to not a numeric value
 select jsonb_path_query('"nan"', '$.double()');
  jsonb_path_query 
 ------------------
-- 
2.7.4

  [text/x-patch] 0003-Implementation-of-datetime-in-jsonpath-v34.patch (121.8K, ../a3be6a7a-77d3-0e88-4f9d-4f725d11d7cd@postgrespro.ru/5-0003-Implementation-of-datetime-in-jsonpath-v34.patch)
  download | inline diff:
From ad1eea822bab92118ee51ba6961c87d89d48059b Mon Sep 17 00:00:00 2001
From: Nikita Glukhov <n.gluhov@postgrespro.ru>
Date: Fri, 1 Mar 2019 03:15:18 +0300
Subject: [PATCH 03/13] Implementation of datetime in jsonpath

---
 doc/src/sgml/func.sgml                       |  49 +-
 src/backend/utils/adt/date.c                 |  59 +-
 src/backend/utils/adt/formatting.c           | 870 +++++++++++++++++++++------
 src/backend/utils/adt/json.c                 |  32 +-
 src/backend/utils/adt/jsonb.c                |  27 +-
 src/backend/utils/adt/jsonb_util.c           |  20 +
 src/backend/utils/adt/jsonpath.c             |  23 +
 src/backend/utils/adt/jsonpath_exec.c        | 436 ++++++++++++++
 src/backend/utils/adt/jsonpath_gram.y        |  16 +
 src/backend/utils/adt/jsonpath_scan.l        |   1 +
 src/backend/utils/adt/timestamp.c            |  59 +-
 src/backend/utils/errcodes.txt               |   1 +
 src/include/utils/date.h                     |   6 +
 src/include/utils/datetime.h                 |   4 +
 src/include/utils/formatting.h               |   3 +
 src/include/utils/jsonapi.h                  |   3 +-
 src/include/utils/jsonb.h                    |  23 +-
 src/include/utils/jsonpath.h                 |   1 +
 src/include/utils/timestamp.h                |   3 +
 src/test/regress/expected/horology.out       |  79 +++
 src/test/regress/expected/jsonb_jsonpath.out | 535 ++++++++++++++++
 src/test/regress/expected/jsonpath.out       |  18 +
 src/test/regress/expected/timestamp.out      |  15 +
 src/test/regress/expected/timestamptz.out    |  15 +
 src/test/regress/sql/horology.sql            |   9 +
 src/test/regress/sql/jsonb_jsonpath.sql      | 148 +++++
 src/test/regress/sql/jsonpath.sql            |   3 +
 src/test/regress/sql/timestamp.sql           |   8 +
 src/test/regress/sql/timestamptz.sql         |   8 +
 29 files changed, 2239 insertions(+), 235 deletions(-)

diff --git a/doc/src/sgml/func.sgml b/doc/src/sgml/func.sgml
index 275fb3f..50299de 100644
--- a/doc/src/sgml/func.sgml
+++ b/doc/src/sgml/func.sgml
@@ -5994,6 +5994,30 @@ SELECT regexp_match('abc01234xyz', '(?:(.*?)(\d+)(.*)){1,1}');
         <entry>microsecond (000000-999999)</entry>
        </row>
        <row>
+        <entry><literal>FF1</literal></entry>
+        <entry>decisecond (0-9)</entry>
+       </row>
+       <row>
+        <entry><literal>FF2</literal></entry>
+        <entry>centisecond (00-99)</entry>
+       </row>
+       <row>
+        <entry><literal>FF3</literal></entry>
+        <entry>millisecond (000-999)</entry>
+       </row>
+       <row>
+        <entry><literal>FF4</literal></entry>
+        <entry>tenth of a millisecond (0000-9999)</entry>
+       </row>
+       <row>
+        <entry><literal>FF5</literal></entry>
+        <entry>hundredth of a millisecond (00000-99999)</entry>
+       </row>
+       <row>
+        <entry><literal>FF6</literal></entry>
+        <entry>microsecond (000000-999999)</entry>
+       </row>
+       <row>
         <entry><literal>SSSS</literal></entry>
         <entry>seconds past midnight (0-86399)</entry>
        </row>
@@ -11413,9 +11437,9 @@ table2-mapping
    listed in <xref linkend="functions-sqljson-path-operators"/>.
    Each method must be preceded by a dot, while arithmetic and boolean
    operators are separated from the operands by spaces. For example,
-   you can get an array size:
+   you can convert a text string into a datetime value:
 <programlisting>
-'$.track.segments.size()'
+'$.track.segments[*]."start time".datetime()'
 </programlisting>
    For more examples of using <type>jsonpath</type> operators
    and methods within path expressions, see
@@ -11667,6 +11691,27 @@ table2-mapping
         <entry><literal>0.3</literal></entry>
        </row>
        <row>
+        <entry><literal>datetime()</literal></entry>
+        <entry>Datetime value converted from a string</entry>
+        <entry><literal>["2015-8-1", "2015-08-12"]</literal></entry>
+        <entry><literal>$[*] ? (@.datetime() &lt; "2015-08-2". datetime())</literal></entry>
+        <entry><literal>2015-8-1</literal></entry>
+       </row>
+       <row>
+        <entry><literal>datetime(<replaceable>template</replaceable>)</literal></entry>
+        <entry>Datetime value converted from a string with a specified template</entry>
+        <entry><literal>["12:30", "18:40"]</literal></entry>
+        <entry><literal>$[*].datetime("HH24:MI")</literal></entry>
+        <entry><literal>"12:30:00", "18:40:00"</literal></entry>
+       </row>
+       <row>
+        <entry><literal>datetime(<replaceable>template</replaceable>, <replaceable>default_tz</replaceable>)</literal></entry>
+        <entry>Datetime value converted from a string with a specified template and default timezone</entry>
+        <entry><literal>["12:30 -02", "18:40"]</literal></entry>
+        <entry><literal>$[*].datetime("HH24:MI TZH", "+03:00")</literal></entry>
+        <entry><literal>"12:30:00-02:00", "18:40:00+03:00"</literal></entry>
+       </row>
+       <row>
         <entry><literal>keyvalue()</literal></entry>
         <entry>
           Sequence of object's key-value pairs represented as array of objects
diff --git a/src/backend/utils/adt/date.c b/src/backend/utils/adt/date.c
index cf5a1c6..5862297 100644
--- a/src/backend/utils/adt/date.c
+++ b/src/backend/utils/adt/date.c
@@ -40,11 +40,15 @@
 #error -ffast-math is known to break this code
 #endif
 
-
-static int	tm2time(struct pg_tm *tm, fsec_t fsec, TimeADT *result);
-static int	tm2timetz(struct pg_tm *tm, fsec_t fsec, int tz, TimeTzADT *result);
-static void AdjustTimeForTypmod(TimeADT *time, int32 typmod);
-
+#define date_ereport(res, msg) do { \
+	if (error) \
+	{ \
+		*error = true; \
+		return (res); \
+	} \
+	else \
+		ereport(ERROR, msg); \
+} while (0)
 
 /* common code for timetypmodin and timetztypmodin */
 static int32
@@ -567,9 +571,8 @@ date_mii(PG_FUNCTION_ARGS)
  * Internal routines for promoting date to timestamp and timestamp with
  * time zone
  */
-
-static Timestamp
-date2timestamp(DateADT dateVal)
+Timestamp
+date2timestamp_internal(DateADT dateVal, bool *error)
 {
 	Timestamp	result;
 
@@ -585,9 +588,9 @@ date2timestamp(DateADT dateVal)
 		 * boundary need be checked for overflow.
 		 */
 		if (dateVal >= (TIMESTAMP_END_JULIAN - POSTGRES_EPOCH_JDATE))
-			ereport(ERROR,
-					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
-					 errmsg("date out of range for timestamp")));
+			date_ereport(0,
+						 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
+						  errmsg("date out of range for timestamp")));
 
 		/* date is days since 2000, timestamp is microseconds since same... */
 		result = dateVal * USECS_PER_DAY;
@@ -597,7 +600,13 @@ date2timestamp(DateADT dateVal)
 }
 
 static TimestampTz
-date2timestamptz(DateADT dateVal)
+date2timestamp(DateADT dateVal)
+{
+	return date2timestamp_internal(dateVal, NULL);
+}
+
+TimestampTz
+date2timestamptz_internal(DateADT dateVal, int *tzp, bool *error)
 {
 	TimestampTz result;
 	struct pg_tm tt,
@@ -616,16 +625,16 @@ date2timestamptz(DateADT dateVal)
 		 * boundary need be checked for overflow.
 		 */
 		if (dateVal >= (TIMESTAMP_END_JULIAN - POSTGRES_EPOCH_JDATE))
-			ereport(ERROR,
-					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
-					 errmsg("date out of range for timestamp")));
+			date_ereport(0,
+						 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
+						  errmsg("date out of range for timestamp")));
 
 		j2date(dateVal + POSTGRES_EPOCH_JDATE,
 			   &(tm->tm_year), &(tm->tm_mon), &(tm->tm_mday));
 		tm->tm_hour = 0;
 		tm->tm_min = 0;
 		tm->tm_sec = 0;
-		tz = DetermineTimeZoneOffset(tm, session_timezone);
+		tz = tzp ? *tzp : DetermineTimeZoneOffset(tm, session_timezone);
 
 		result = dateVal * USECS_PER_DAY + tz * USECS_PER_SEC;
 
@@ -634,14 +643,20 @@ date2timestamptz(DateADT dateVal)
 		 * of time zone, check for allowed timestamp range after adding tz.
 		 */
 		if (!IS_VALID_TIMESTAMP(result))
-			ereport(ERROR,
-					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
-					 errmsg("date out of range for timestamp")));
+			date_ereport(0,
+						 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
+						  errmsg("date out of range for timestamp")));
 	}
 
 	return result;
 }
 
+static TimestampTz
+date2timestamptz(DateADT dateVal)
+{
+	return date2timestamptz_internal(dateVal, NULL, NULL);
+}
+
 /*
  * date2timestamp_no_overflow
  *
@@ -1211,7 +1226,7 @@ time_in(PG_FUNCTION_ARGS)
 /* tm2time()
  * Convert a tm structure to a time data type.
  */
-static int
+int
 tm2time(struct pg_tm *tm, fsec_t fsec, TimeADT *result)
 {
 	*result = ((((tm->tm_hour * MINS_PER_HOUR + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec)
@@ -1387,7 +1402,7 @@ time_scale(PG_FUNCTION_ARGS)
  * have a fundamental tie together but rather a coincidence of
  * implementation. - thomas
  */
-static void
+void
 AdjustTimeForTypmod(TimeADT *time, int32 typmod)
 {
 	static const int64 TimeScales[MAX_TIME_PRECISION + 1] = {
@@ -1965,7 +1980,7 @@ time_part(PG_FUNCTION_ARGS)
 /* tm2timetz()
  * Convert a tm structure to a time data type.
  */
-static int
+int
 tm2timetz(struct pg_tm *tm, fsec_t fsec, int tz, TimeTzADT *result)
 {
 	result->time = ((((tm->tm_hour * MINS_PER_HOUR + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec) *
diff --git a/src/backend/utils/adt/formatting.c b/src/backend/utils/adt/formatting.c
index df1db7b..04382d6 100644
--- a/src/backend/utils/adt/formatting.c
+++ b/src/backend/utils/adt/formatting.c
@@ -86,6 +86,7 @@
 #endif
 
 #include "catalog/pg_collation.h"
+#include "catalog/pg_type.h"
 #include "mb/pg_wchar.h"
 #include "utils/builtins.h"
 #include "utils/date.h"
@@ -436,7 +437,8 @@ typedef struct
 				clock,			/* 12 or 24 hour clock? */
 				tzsign,			/* +1, -1 or 0 if timezone info is absent */
 				tzh,
-				tzm;
+				tzm,
+				ff;				/* fractional precision */
 } TmFromChar;
 
 #define ZERO_tmfc(_X) memset(_X, 0, sizeof(TmFromChar))
@@ -596,6 +598,12 @@ typedef enum
 	DCH_Day,
 	DCH_Dy,
 	DCH_D,
+	DCH_FF1,
+	DCH_FF2,
+	DCH_FF3,
+	DCH_FF4,
+	DCH_FF5,
+	DCH_FF6,
 	DCH_FX,						/* global suffix */
 	DCH_HH24,
 	DCH_HH12,
@@ -645,6 +653,12 @@ typedef enum
 	DCH_dd,
 	DCH_dy,
 	DCH_d,
+	DCH_ff1,
+	DCH_ff2,
+	DCH_ff3,
+	DCH_ff4,
+	DCH_ff5,
+	DCH_ff6,
 	DCH_fx,
 	DCH_hh24,
 	DCH_hh12,
@@ -745,7 +759,13 @@ static const KeyWord DCH_keywords[] = {
 	{"Day", 3, DCH_Day, false, FROM_CHAR_DATE_NONE},
 	{"Dy", 2, DCH_Dy, false, FROM_CHAR_DATE_NONE},
 	{"D", 1, DCH_D, true, FROM_CHAR_DATE_GREGORIAN},
-	{"FX", 2, DCH_FX, false, FROM_CHAR_DATE_NONE},	/* F */
+	{"FF1", 3, DCH_FF1, false, FROM_CHAR_DATE_NONE},	/* F */
+	{"FF2", 3, DCH_FF2, false, FROM_CHAR_DATE_NONE},
+	{"FF3", 3, DCH_FF3, false, FROM_CHAR_DATE_NONE},
+	{"FF4", 3, DCH_FF4, false, FROM_CHAR_DATE_NONE},
+	{"FF5", 3, DCH_FF5, false, FROM_CHAR_DATE_NONE},
+	{"FF6", 3, DCH_FF6, false, FROM_CHAR_DATE_NONE},
+	{"FX", 2, DCH_FX, false, FROM_CHAR_DATE_NONE},
 	{"HH24", 4, DCH_HH24, true, FROM_CHAR_DATE_NONE},	/* H */
 	{"HH12", 4, DCH_HH12, true, FROM_CHAR_DATE_NONE},
 	{"HH", 2, DCH_HH, true, FROM_CHAR_DATE_NONE},
@@ -794,7 +814,13 @@ static const KeyWord DCH_keywords[] = {
 	{"dd", 2, DCH_DD, true, FROM_CHAR_DATE_GREGORIAN},
 	{"dy", 2, DCH_dy, false, FROM_CHAR_DATE_NONE},
 	{"d", 1, DCH_D, true, FROM_CHAR_DATE_GREGORIAN},
-	{"fx", 2, DCH_FX, false, FROM_CHAR_DATE_NONE},	/* f */
+	{"ff1", 3, DCH_FF1, false, FROM_CHAR_DATE_NONE},	/* f */
+	{"ff2", 3, DCH_FF2, false, FROM_CHAR_DATE_NONE},
+	{"ff3", 3, DCH_FF3, false, FROM_CHAR_DATE_NONE},
+	{"ff4", 3, DCH_FF4, false, FROM_CHAR_DATE_NONE},
+	{"ff5", 3, DCH_FF5, false, FROM_CHAR_DATE_NONE},
+	{"ff6", 3, DCH_FF6, false, FROM_CHAR_DATE_NONE},
+	{"fx", 2, DCH_FX, false, FROM_CHAR_DATE_NONE},
 	{"hh24", 4, DCH_HH24, true, FROM_CHAR_DATE_NONE},	/* h */
 	{"hh12", 4, DCH_HH12, true, FROM_CHAR_DATE_NONE},
 	{"hh", 2, DCH_HH, true, FROM_CHAR_DATE_NONE},
@@ -895,10 +921,10 @@ static const int DCH_index[KeyWord_INDEX_SIZE] = {
 	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
 	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
 	-1, -1, -1, -1, -1, DCH_A_D, DCH_B_C, DCH_CC, DCH_DAY, -1,
-	DCH_FX, -1, DCH_HH24, DCH_IDDD, DCH_J, -1, -1, DCH_MI, -1, DCH_OF,
+	DCH_FF1, -1, DCH_HH24, DCH_IDDD, DCH_J, -1, -1, DCH_MI, -1, DCH_OF,
 	DCH_P_M, DCH_Q, DCH_RM, DCH_SSSS, DCH_TZH, DCH_US, -1, DCH_WW, -1, DCH_Y_YYY,
 	-1, -1, -1, -1, -1, -1, -1, DCH_a_d, DCH_b_c, DCH_cc,
-	DCH_day, -1, DCH_fx, -1, DCH_hh24, DCH_iddd, DCH_j, -1, -1, DCH_mi,
+	DCH_day, -1, DCH_ff1, -1, DCH_hh24, DCH_iddd, DCH_j, -1, -1, DCH_mi,
 	-1, -1, DCH_p_m, DCH_q, DCH_rm, DCH_ssss, DCH_tz, DCH_us, -1, DCH_ww,
 	-1, DCH_y_yyy, -1, -1, -1, -1
 
@@ -962,6 +988,19 @@ typedef struct NUMProc
 			   *L_currency_symbol;
 } NUMProc;
 
+/* Return flags for DCH_from_char() */
+#define DCH_DATED	0x01
+#define DCH_TIMED	0x02
+#define DCH_ZONED	0x04
+
+#define dch_ereport(res, ...) do { \
+	if (error) { \
+		*error = true; \
+		return (res); \
+	} else { \
+		ereport(ERROR, (__VA_ARGS__)); \
+	} \
+} while (0)
 
 /* ----------
  * Functions
@@ -977,7 +1016,8 @@ static void parse_format(FormatNode *node, const char *str, const KeyWord *kw,
 
 static void DCH_to_char(FormatNode *node, bool is_interval,
 			TmToChar *in, char *out, Oid collid);
-static void DCH_from_char(FormatNode *node, char *in, TmFromChar *out);
+static bool DCH_from_char(FormatNode *node, char *in, TmFromChar *out,
+			  bool strict, bool *error);
 
 #ifdef DEBUG_TO_FROM_CHAR
 static void dump_index(const KeyWord *k, const int *index);
@@ -988,14 +1028,16 @@ static const char *get_th(char *num, int type);
 static char *str_numth(char *dest, char *num, int type);
 static int	adjust_partial_year_to_2020(int year);
 static int	strspace_len(char *str);
-static void from_char_set_mode(TmFromChar *tmfc, const FromCharDateMode mode);
-static void from_char_set_int(int *dest, const int value, const FormatNode *node);
-static int	from_char_parse_int_len(int *dest, char **src, const int len, FormatNode *node);
-static int	from_char_parse_int(int *dest, char **src, FormatNode *node);
+static bool from_char_set_mode(TmFromChar *tmfc, const FromCharDateMode mode,
+				   bool *error);
+static bool from_char_set_int(int *dest, const int value, const FormatNode *node, bool *error);
+static int	from_char_parse_int_len(int *dest, char **src, const int len, FormatNode *node, bool *error);
+static int	from_char_parse_int(int *dest, char **src, FormatNode *node, bool *error);
 static int	seq_search(char *name, const char *const *array, int type, int max, int *len);
-static int	from_char_seq_search(int *dest, char **src, const char *const *array, int type, int max, FormatNode *node);
-static void do_to_timestamp(text *date_txt, text *fmt,
-				struct pg_tm *tm, fsec_t *fsec);
+static int	from_char_seq_search(int *dest, char **src, const char *const *array, int type, int max, FormatNode *node, bool *error);
+static bool do_to_timestamp(text *date_txt, text *fmt, bool strict,
+				struct pg_tm *tm, fsec_t *fsec, int *fprec, int *flags,
+				bool *error);
 static char *fill_str(char *str, int c, int max);
 static FormatNode *NUM_cache(int len, NUMDesc *Num, text *pars_str, bool *shouldFree);
 static char *int_to_roman(int number);
@@ -2168,21 +2210,26 @@ strspace_len(char *str)
  *
  * Puke if the date mode has already been set, and the caller attempts to set
  * it to a conflicting mode.
+ *
+ * If 'error' is NULL, then errors are thrown, else '*error' is set and false
+ * is returned.
  */
-static void
-from_char_set_mode(TmFromChar *tmfc, const FromCharDateMode mode)
+static bool
+from_char_set_mode(TmFromChar *tmfc, const FromCharDateMode mode, bool *error)
 {
 	if (mode != FROM_CHAR_DATE_NONE)
 	{
 		if (tmfc->mode == FROM_CHAR_DATE_NONE)
 			tmfc->mode = mode;
 		else if (tmfc->mode != mode)
-			ereport(ERROR,
-					(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
-					 errmsg("invalid combination of date conventions"),
-					 errhint("Do not mix Gregorian and ISO week date "
-							 "conventions in a formatting template.")));
+			dch_ereport(false,
+						errcode(ERRCODE_INVALID_DATETIME_FORMAT),
+						errmsg("invalid combination of date conventions"),
+						errhint("Do not mix Gregorian and ISO week date "
+								"conventions in a formatting template."));
 	}
+
+	return true;
 }
 
 /*
@@ -2190,18 +2237,25 @@ from_char_set_mode(TmFromChar *tmfc, const FromCharDateMode mode)
  *
  * Puke if the destination integer has previously been set to some other
  * non-zero value.
+ *
+ * If 'error' is NULL, then errors are thrown, else '*error' is set and false
+ * is returned.
  */
-static void
-from_char_set_int(int *dest, const int value, const FormatNode *node)
+static bool
+from_char_set_int(int *dest, const int value, const FormatNode *node,
+				  bool *error)
 {
 	if (*dest != 0 && *dest != value)
-		ereport(ERROR,
-				(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
-				 errmsg("conflicting values for \"%s\" field in formatting string",
-						node->key->name),
-				 errdetail("This value contradicts a previous setting for "
-						   "the same field type.")));
+		dch_ereport(false,
+					errcode(ERRCODE_INVALID_DATETIME_FORMAT),
+					errmsg("conflicting values for \"%s\" field in "
+						   "formatting string",
+						   node->key->name),
+					errdetail("This value contradicts a previous setting "
+							  "for the same field type."));
 	*dest = value;
+
+	return true;
 }
 
 /*
@@ -2223,9 +2277,14 @@ from_char_set_int(int *dest, const int value, const FormatNode *node)
  * Note that from_char_parse_int() provides a more convenient wrapper where
  * the length of the field is the same as the length of the format keyword (as
  * with DD and MI).
+ *
+ * If 'error' is NULL, then errors are thrown, else '*error' is set and -1
+ * is returned.
+ *
  */
 static int
-from_char_parse_int_len(int *dest, char **src, const int len, FormatNode *node)
+from_char_parse_int_len(int *dest, char **src, const int len, FormatNode *node,
+						bool *error)
 {
 	long		result;
 	char		copy[DCH_MAX_ITEM_SIZ + 1];
@@ -2258,50 +2317,56 @@ from_char_parse_int_len(int *dest, char **src, const int len, FormatNode *node)
 		char	   *last;
 
 		if (used < len)
-			ereport(ERROR,
-					(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
-					 errmsg("source string too short for \"%s\" formatting field",
-							node->key->name),
-					 errdetail("Field requires %d characters, but only %d "
-							   "remain.",
-							   len, used),
-					 errhint("If your source string is not fixed-width, try "
-							 "using the \"FM\" modifier.")));
+			dch_ereport(-1,
+						errcode(ERRCODE_INVALID_DATETIME_FORMAT),
+						errmsg("source string too short for \"%s\" "
+							   "formatting field",
+							   node->key->name),
+						errdetail("Field requires %d characters, "
+								  "but only %d remain.",
+								  len, used),
+						errhint("If your source string is not fixed-width, "
+								"try using the \"FM\" modifier."));
 
 		errno = 0;
 		result = strtol(copy, &last, 10);
 		used = last - copy;
 
 		if (used > 0 && used < len)
-			ereport(ERROR,
-					(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
-					 errmsg("invalid value \"%s\" for \"%s\"",
-							copy, node->key->name),
-					 errdetail("Field requires %d characters, but only %d "
-							   "could be parsed.", len, used),
-					 errhint("If your source string is not fixed-width, try "
-							 "using the \"FM\" modifier.")));
+			dch_ereport(-1,
+						errcode(ERRCODE_INVALID_DATETIME_FORMAT),
+						errmsg("invalid value \"%s\" for \"%s\"",
+							   copy, node->key->name),
+						errdetail("Field requires %d characters, "
+								  "but only %d could be parsed.",
+								  len, used),
+						errhint("If your source string is not fixed-width, "
+								"try using the \"FM\" modifier."));
 
 		*src += used;
 	}
 
 	if (*src == init)
-		ereport(ERROR,
-				(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
-				 errmsg("invalid value \"%s\" for \"%s\"",
-						copy, node->key->name),
-				 errdetail("Value must be an integer.")));
+		dch_ereport(-1,
+					errcode(ERRCODE_INVALID_DATETIME_FORMAT),
+					errmsg("invalid value \"%s\" for \"%s\"",
+						   copy, node->key->name),
+					errdetail("Value must be an integer."));
 
 	if (errno == ERANGE || result < INT_MIN || result > INT_MAX)
-		ereport(ERROR,
-				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
-				 errmsg("value for \"%s\" in source string is out of range",
-						node->key->name),
-				 errdetail("Value must be in the range %d to %d.",
-						   INT_MIN, INT_MAX)));
+		dch_ereport(-1,
+					errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
+					errmsg("value for \"%s\" in source string is out of range",
+						   node->key->name),
+					errdetail("Value must be in the range %d to %d.",
+							  INT_MIN, INT_MAX));
 
 	if (dest != NULL)
-		from_char_set_int(dest, (int) result, node);
+	{
+		if (!from_char_set_int(dest, (int) result, node, error))
+			return -1;			/* error */
+	}
+
 	return *src - init;
 }
 
@@ -2315,9 +2380,9 @@ from_char_parse_int_len(int *dest, char **src, const int len, FormatNode *node)
  * required length explicitly.
  */
 static int
-from_char_parse_int(int *dest, char **src, FormatNode *node)
+from_char_parse_int(int *dest, char **src, FormatNode *node, bool *error)
 {
-	return from_char_parse_int_len(dest, src, node->key->len, node);
+	return from_char_parse_int_len(dest, src, node->key->len, node, error);
 }
 
 /* ----------
@@ -2400,11 +2465,12 @@ seq_search(char *name, const char *const *array, int type, int max, int *len)
  * pointed to by 'dest', advance 'src' to the end of the part of the string
  * which matched, and return the number of characters consumed.
  *
- * If the string doesn't match, throw an error.
+ * If the string doesn't match, throw an error if 'error' is NULL, otherwise
+ * set '*error' and return -1.
  */
 static int
-from_char_seq_search(int *dest, char **src, const char *const *array, int type, int max,
-					 FormatNode *node)
+from_char_seq_search(int *dest, char **src, const char *const *array, int type,
+					 int max, FormatNode *node, bool *error)
 {
 	int			len;
 
@@ -2416,12 +2482,12 @@ from_char_seq_search(int *dest, char **src, const char *const *array, int type,
 		Assert(max <= DCH_MAX_ITEM_SIZ);
 		strlcpy(copy, *src, max + 1);
 
-		ereport(ERROR,
-				(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
-				 errmsg("invalid value \"%s\" for \"%s\"",
-						copy, node->key->name),
-				 errdetail("The given value did not match any of the allowed "
-						   "values for this field.")));
+		dch_ereport(-1,
+					errcode(ERRCODE_INVALID_DATETIME_FORMAT),
+					errmsg("invalid value \"%s\" for \"%s\"",
+						   copy, node->key->name),
+					errdetail("The given value did not match any of "
+							  "the allowed values for this field."));
 	}
 	*src += len;
 	return len;
@@ -2514,18 +2580,32 @@ DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out, Oid col
 					str_numth(s, s, S_TH_TYPE(n->suffix));
 				s += strlen(s);
 				break;
-			case DCH_MS:		/* millisecond */
-				sprintf(s, "%03d", (int) (in->fsec / INT64CONST(1000)));
-				if (S_THth(n->suffix))
-					str_numth(s, s, S_TH_TYPE(n->suffix));
+#define DCH_to_char_fsec(frac_fmt, frac_val) \
+				sprintf(s, frac_fmt, (int) (frac_val)); \
+				if (S_THth(n->suffix)) \
+					str_numth(s, s, S_TH_TYPE(n->suffix)); \
 				s += strlen(s);
+			case DCH_FF1:		/* decisecond */
+				DCH_to_char_fsec("%01d", in->fsec / 100000);
+				break;
+			case DCH_FF2:		/* centisecond */
+				DCH_to_char_fsec("%02d", in->fsec / 10000);
+				break;
+			case DCH_FF3:
+			case DCH_MS:		/* millisecond */
+				DCH_to_char_fsec("%03d", in->fsec / 1000);
+				break;
+			case DCH_FF4:
+				DCH_to_char_fsec("%04d", in->fsec / 100);
 				break;
+			case DCH_FF5:
+				DCH_to_char_fsec("%05d", in->fsec / 10);
+				break;
+			case DCH_FF6:
 			case DCH_US:		/* microsecond */
-				sprintf(s, "%06d", (int) in->fsec);
-				if (S_THth(n->suffix))
-					str_numth(s, s, S_TH_TYPE(n->suffix));
-				s += strlen(s);
+				DCH_to_char_fsec("%06d", in->fsec);
 				break;
+#undef DCH_to_char_fsec
 			case DCH_SSSS:
 				sprintf(s, "%d", tm->tm_hour * SECS_PER_HOUR +
 						tm->tm_min * SECS_PER_MINUTE +
@@ -3007,19 +3087,26 @@ DCH_to_char(FormatNode *node, bool is_interval, TmToChar *in, char *out, Oid col
 /* ----------
  * Process a string as denoted by a list of FormatNodes.
  * The TmFromChar struct pointed to by 'out' is populated with the results.
+ * 'strict' enables error reporting on unmatched trailing characters in input or
+ * format strings patterns.
  *
  * Note: we currently don't have any to_interval() function, so there
  * is no need here for INVALID_FOR_INTERVAL checks.
+ *
+ * If 'error' is NULL, then errors are thrown, else '*error' is set and false
+ * is returned.
  * ----------
  */
-static void
-DCH_from_char(FormatNode *node, char *in, TmFromChar *out)
+static bool
+DCH_from_char(FormatNode *node, char *in, TmFromChar *out, bool strict,
+			  bool *error)
 {
 	FormatNode *n;
 	char	   *s;
 	int			len,
 				value;
 	bool		fx_mode = false;
+
 	/* number of extra skipped characters (more than given in format string) */
 	int			extra_skip = 0;
 
@@ -3095,7 +3182,8 @@ DCH_from_char(FormatNode *node, char *in, TmFromChar *out)
 			continue;
 		}
 
-		from_char_set_mode(out, n->key->date_mode);
+		if (!from_char_set_mode(out, n->key->date_mode, error))
+			return false;		/* error */
 
 		switch (n->key->id)
 		{
@@ -3106,40 +3194,49 @@ DCH_from_char(FormatNode *node, char *in, TmFromChar *out)
 			case DCH_P_M:
 			case DCH_a_m:
 			case DCH_p_m:
-				from_char_seq_search(&value, &s, ampm_strings_long,
-									 ALL_UPPER, n->key->len, n);
-				from_char_set_int(&out->pm, value % 2, n);
+				if (from_char_seq_search(&value, &s, ampm_strings_long,
+										 ALL_UPPER, n->key->len, n,
+										 error) < 0 ||
+					!from_char_set_int(&out->pm, value % 2, n, error))
+					return false;	/* error */
 				out->clock = CLOCK_12_HOUR;
 				break;
 			case DCH_AM:
 			case DCH_PM:
 			case DCH_am:
 			case DCH_pm:
-				from_char_seq_search(&value, &s, ampm_strings,
-									 ALL_UPPER, n->key->len, n);
-				from_char_set_int(&out->pm, value % 2, n);
+				if (from_char_seq_search(&value, &s, ampm_strings, ALL_UPPER,
+										 n->key->len, n, error) < 0 ||
+					!from_char_set_int(&out->pm, value % 2, n, error))
+					return false;
 				out->clock = CLOCK_12_HOUR;
 				break;
 			case DCH_HH:
 			case DCH_HH12:
-				from_char_parse_int_len(&out->hh, &s, 2, n);
+				if (from_char_parse_int_len(&out->hh, &s, 2, n, error) < 0)
+					return false;
 				out->clock = CLOCK_12_HOUR;
 				SKIP_THth(s, n->suffix);
 				break;
 			case DCH_HH24:
-				from_char_parse_int_len(&out->hh, &s, 2, n);
+				if (from_char_parse_int_len(&out->hh, &s, 2, n, error) < 0)
+					return false;
 				SKIP_THth(s, n->suffix);
 				break;
 			case DCH_MI:
-				from_char_parse_int(&out->mi, &s, n);
+				if (from_char_parse_int(&out->mi, &s, n, error) < 0)
+					return false;
 				SKIP_THth(s, n->suffix);
 				break;
 			case DCH_SS:
-				from_char_parse_int(&out->ss, &s, n);
+				if (from_char_parse_int(&out->ss, &s, n, error) < 0)
+					return false;
 				SKIP_THth(s, n->suffix);
 				break;
 			case DCH_MS:		/* millisecond */
-				len = from_char_parse_int_len(&out->ms, &s, 3, n);
+				len = from_char_parse_int_len(&out->ms, &s, 3, n, error);
+				if (len < 0)
+					return false;
 
 				/*
 				 * 25 is 0.25 and 250 is 0.25 too; 025 is 0.025 and not 0.25
@@ -3149,8 +3246,20 @@ DCH_from_char(FormatNode *node, char *in, TmFromChar *out)
 
 				SKIP_THth(s, n->suffix);
 				break;
+			case DCH_FF1:
+			case DCH_FF2:
+			case DCH_FF3:
+			case DCH_FF4:
+			case DCH_FF5:
+			case DCH_FF6:
+				out->ff = n->key->id - DCH_FF1 + 1;
+				/* fall through */
 			case DCH_US:		/* microsecond */
-				len = from_char_parse_int_len(&out->us, &s, 6, n);
+				len = from_char_parse_int_len(&out->us, &s,
+											  n->key->id == DCH_US ? 6 :
+											  out->ff, n, error);
+				if (len < 0)
+					return false;
 
 				out->us *= len == 1 ? 100000 :
 					len == 2 ? 10000 :
@@ -3161,18 +3270,20 @@ DCH_from_char(FormatNode *node, char *in, TmFromChar *out)
 				SKIP_THth(s, n->suffix);
 				break;
 			case DCH_SSSS:
-				from_char_parse_int(&out->ssss, &s, n);
+				if (from_char_parse_int(&out->ssss, &s, n, error) < 0)
+					return false;
 				SKIP_THth(s, n->suffix);
 				break;
 			case DCH_tz:
 			case DCH_TZ:
 			case DCH_OF:
-				ereport(ERROR,
-						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-						 errmsg("formatting field \"%s\" is only supported in to_char",
-								n->key->name)));
+				dch_ereport(false,
+							errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+							errmsg("formatting field \"%s\" is only supported in to_char",
+								   n->key->name));
 				break;
 			case DCH_TZH:
+
 				/*
 				 * Value of TZH might be negative.  And the issue is that we
 				 * might swallow minus sign as the separator.  So, if we have
@@ -3192,82 +3303,97 @@ DCH_from_char(FormatNode *node, char *in, TmFromChar *out)
 						out->tzsign = +1;
 				}
 
-				from_char_parse_int_len(&out->tzh, &s, 2, n);
+				if (from_char_parse_int_len(&out->tzh, &s, 2, n, error) < 0)
+					return false;
 				break;
 			case DCH_TZM:
 				/* assign positive timezone sign if TZH was not seen before */
 				if (!out->tzsign)
 					out->tzsign = +1;
-				from_char_parse_int_len(&out->tzm, &s, 2, n);
+				if (from_char_parse_int_len(&out->tzm, &s, 2, n, error) < 0)
+					return false;
 				break;
 			case DCH_A_D:
 			case DCH_B_C:
 			case DCH_a_d:
 			case DCH_b_c:
-				from_char_seq_search(&value, &s, adbc_strings_long,
-									 ALL_UPPER, n->key->len, n);
-				from_char_set_int(&out->bc, value % 2, n);
+				if (from_char_seq_search(&value, &s, adbc_strings_long,
+										 ALL_UPPER, n->key->len, n,
+										 error) < 0 ||
+					!from_char_set_int(&out->bc, value % 2, n, error))
+					return false;
 				break;
 			case DCH_AD:
 			case DCH_BC:
 			case DCH_ad:
 			case DCH_bc:
-				from_char_seq_search(&value, &s, adbc_strings,
-									 ALL_UPPER, n->key->len, n);
-				from_char_set_int(&out->bc, value % 2, n);
+				if (from_char_seq_search(&value, &s, adbc_strings, ALL_UPPER,
+										 n->key->len, n, error) < 0 ||
+					!from_char_set_int(&out->bc, value % 2, n, error))
+					return false;
 				break;
 			case DCH_MONTH:
 			case DCH_Month:
 			case DCH_month:
-				from_char_seq_search(&value, &s, months_full, ONE_UPPER,
-									 MAX_MONTH_LEN, n);
-				from_char_set_int(&out->mm, value + 1, n);
+				if (from_char_seq_search(&value, &s, months_full, ONE_UPPER,
+										 MAX_MONTH_LEN, n, error) < 0 ||
+					!from_char_set_int(&out->mm, value + 1, n, error))
+					return false;
 				break;
 			case DCH_MON:
 			case DCH_Mon:
 			case DCH_mon:
-				from_char_seq_search(&value, &s, months, ONE_UPPER,
-									 MAX_MON_LEN, n);
-				from_char_set_int(&out->mm, value + 1, n);
+				if (from_char_seq_search(&value, &s, months, ONE_UPPER,
+										 MAX_MON_LEN, n, error) < 0 ||
+					!from_char_set_int(&out->mm, value + 1, n, error))
+					return false;
 				break;
 			case DCH_MM:
-				from_char_parse_int(&out->mm, &s, n);
+				if (from_char_parse_int(&out->mm, &s, n, error) < 0)
+					return false;
 				SKIP_THth(s, n->suffix);
 				break;
 			case DCH_DAY:
 			case DCH_Day:
 			case DCH_day:
-				from_char_seq_search(&value, &s, days, ONE_UPPER,
-									 MAX_DAY_LEN, n);
-				from_char_set_int(&out->d, value, n);
+				if (from_char_seq_search(&value, &s, days, ONE_UPPER,
+										 MAX_DAY_LEN, n, error) < 0 ||
+					!from_char_set_int(&out->d, value, n, error))
+					return false;
 				out->d++;
 				break;
 			case DCH_DY:
 			case DCH_Dy:
 			case DCH_dy:
-				from_char_seq_search(&value, &s, days, ONE_UPPER,
-									 MAX_DY_LEN, n);
-				from_char_set_int(&out->d, value, n);
+				if (from_char_seq_search(&value, &s, days, ONE_UPPER,
+										 MAX_DY_LEN, n, error) < 0 ||
+					!from_char_set_int(&out->d, value, n, error))
+					return false;
 				out->d++;
 				break;
 			case DCH_DDD:
-				from_char_parse_int(&out->ddd, &s, n);
+				if (from_char_parse_int(&out->ddd, &s, n, error) < 0)
+					return false;
 				SKIP_THth(s, n->suffix);
 				break;
 			case DCH_IDDD:
-				from_char_parse_int_len(&out->ddd, &s, 3, n);
+				if (from_char_parse_int_len(&out->ddd, &s, 3, n, error) < 0)
+					return false;
 				SKIP_THth(s, n->suffix);
 				break;
 			case DCH_DD:
-				from_char_parse_int(&out->dd, &s, n);
+				if (from_char_parse_int(&out->dd, &s, n, error) < 0)
+					return false;
 				SKIP_THth(s, n->suffix);
 				break;
 			case DCH_D:
-				from_char_parse_int(&out->d, &s, n);
+				if (from_char_parse_int(&out->d, &s, n, error) < 0)
+					return false;
 				SKIP_THth(s, n->suffix);
 				break;
 			case DCH_ID:
-				from_char_parse_int_len(&out->d, &s, 1, n);
+				if (from_char_parse_int_len(&out->d, &s, 1, n, error) < 0)
+					return false;
 				/* Shift numbering to match Gregorian where Sunday = 1 */
 				if (++out->d > 7)
 					out->d = 1;
@@ -3275,7 +3401,8 @@ DCH_from_char(FormatNode *node, char *in, TmFromChar *out)
 				break;
 			case DCH_WW:
 			case DCH_IW:
-				from_char_parse_int(&out->ww, &s, n);
+				if (from_char_parse_int(&out->ww, &s, n, error) < 0)
+					return false;
 				SKIP_THth(s, n->suffix);
 				break;
 			case DCH_Q:
@@ -3290,11 +3417,13 @@ DCH_from_char(FormatNode *node, char *in, TmFromChar *out)
 				 * We still parse the source string for an integer, but it
 				 * isn't stored anywhere in 'out'.
 				 */
-				from_char_parse_int((int *) NULL, &s, n);
+				if (from_char_parse_int((int *) NULL, &s, n, error) < 0)
+					return false;
 				SKIP_THth(s, n->suffix);
 				break;
 			case DCH_CC:
-				from_char_parse_int(&out->cc, &s, n);
+				if (from_char_parse_int(&out->cc, &s, n, error) < 0)
+					return false;
 				SKIP_THth(s, n->suffix);
 				break;
 			case DCH_Y_YYY:
@@ -3306,11 +3435,12 @@ DCH_from_char(FormatNode *node, char *in, TmFromChar *out)
 
 					matched = sscanf(s, "%d,%03d%n", &millennia, &years, &nch);
 					if (matched < 2)
-						ereport(ERROR,
-								(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
-								 errmsg("invalid input string for \"Y,YYY\"")));
+						dch_ereport(false,
+									errcode(ERRCODE_INVALID_DATETIME_FORMAT),
+									errmsg("invalid input string for \"Y,YYY\""));
 					years += (millennia * 1000);
-					from_char_set_int(&out->year, years, n);
+					if (!from_char_set_int(&out->year, years, n, error))
+						return false;
 					out->yysz = 4;
 					s += nch;
 					SKIP_THth(s, n->suffix);
@@ -3318,47 +3448,63 @@ DCH_from_char(FormatNode *node, char *in, TmFromChar *out)
 				break;
 			case DCH_YYYY:
 			case DCH_IYYY:
-				from_char_parse_int(&out->year, &s, n);
+				if (from_char_parse_int(&out->year, &s, n, error) < 0)
+					return false;
 				out->yysz = 4;
 				SKIP_THth(s, n->suffix);
 				break;
 			case DCH_YYY:
 			case DCH_IYY:
-				if (from_char_parse_int(&out->year, &s, n) < 4)
+				len = from_char_parse_int(&out->year, &s, n, error);
+				if (len < 0)
+					return false;
+				if (len < 4)
 					out->year = adjust_partial_year_to_2020(out->year);
 				out->yysz = 3;
 				SKIP_THth(s, n->suffix);
 				break;
 			case DCH_YY:
 			case DCH_IY:
-				if (from_char_parse_int(&out->year, &s, n) < 4)
+				len = from_char_parse_int(&out->year, &s, n, error);
+				if (len < 0)
+					return false;
+				if (len < 4)
 					out->year = adjust_partial_year_to_2020(out->year);
 				out->yysz = 2;
 				SKIP_THth(s, n->suffix);
 				break;
 			case DCH_Y:
 			case DCH_I:
-				if (from_char_parse_int(&out->year, &s, n) < 4)
+				len = from_char_parse_int(&out->year, &s, n, error);
+				if (len < 0)
+					return false;
+				if (len < 4)
 					out->year = adjust_partial_year_to_2020(out->year);
 				out->yysz = 1;
 				SKIP_THth(s, n->suffix);
 				break;
 			case DCH_RM:
-				from_char_seq_search(&value, &s, rm_months_upper,
-									 ALL_UPPER, MAX_RM_LEN, n);
-				from_char_set_int(&out->mm, MONTHS_PER_YEAR - value, n);
+				if (from_char_seq_search(&value, &s, rm_months_upper,
+										 ALL_UPPER, MAX_RM_LEN, n, error) < 0 ||
+					!from_char_set_int(&out->mm, MONTHS_PER_YEAR - value, n,
+									   error))
+					return false;
 				break;
 			case DCH_rm:
-				from_char_seq_search(&value, &s, rm_months_lower,
-									 ALL_LOWER, MAX_RM_LEN, n);
-				from_char_set_int(&out->mm, MONTHS_PER_YEAR - value, n);
+				if (from_char_seq_search(&value, &s, rm_months_lower,
+										 ALL_LOWER, MAX_RM_LEN, n, error) < 0 ||
+					!from_char_set_int(&out->mm, MONTHS_PER_YEAR - value, n,
+									   error))
+					return false;
 				break;
 			case DCH_W:
-				from_char_parse_int(&out->w, &s, n);
+				if (from_char_parse_int(&out->w, &s, n, error) < 0)
+					return false;
 				SKIP_THth(s, n->suffix);
 				break;
 			case DCH_J:
-				from_char_parse_int(&out->j, &s, n);
+				if (from_char_parse_int(&out->j, &s, n, error) < 0)
+					return false;
 				SKIP_THth(s, n->suffix);
 				break;
 		}
@@ -3374,6 +3520,25 @@ DCH_from_char(FormatNode *node, char *in, TmFromChar *out)
 			}
 		}
 	}
+
+	if (strict)
+	{
+		if (n->type != NODE_TYPE_END)
+			dch_ereport(false,
+						errcode(ERRCODE_INVALID_DATETIME_FORMAT),
+						errmsg("input string is too short for datetime format"));
+
+		while (*s != '\0' && isspace((unsigned char) *s))
+			s++;
+
+		if (*s != '\0')
+			dch_ereport(false,
+						errcode(ERRCODE_INVALID_DATETIME_FORMAT),
+						errmsg("trailing characters remain in input string "
+							   "after datetime format"));
+	}
+
+	return true;
 }
 
 /*
@@ -3394,6 +3559,115 @@ DCH_prevent_counter_overflow(void)
 	}
 }
 
+/*
+ * Get mask of date/time/zone components present in format nodes.
+ *
+ * If 'error' is NULL, then errors are thrown, else '*error' is set and 0
+ * is returned.
+ */
+static int
+DCH_datetime_type(FormatNode *node, bool *error)
+{
+	FormatNode *n;
+	int			flags = 0;
+
+	for (n = node; n->type != NODE_TYPE_END; n++)
+	{
+		if (n->type != NODE_TYPE_ACTION)
+			continue;
+
+		switch (n->key->id)
+		{
+			case DCH_FX:
+				break;
+			case DCH_A_M:
+			case DCH_P_M:
+			case DCH_a_m:
+			case DCH_p_m:
+			case DCH_AM:
+			case DCH_PM:
+			case DCH_am:
+			case DCH_pm:
+			case DCH_HH:
+			case DCH_HH12:
+			case DCH_HH24:
+			case DCH_MI:
+			case DCH_SS:
+			case DCH_MS:		/* millisecond */
+			case DCH_US:		/* microsecond */
+			case DCH_FF1:
+			case DCH_FF2:
+			case DCH_FF3:
+			case DCH_FF4:
+			case DCH_FF5:
+			case DCH_FF6:
+			case DCH_SSSS:
+				flags |= DCH_TIMED;
+				break;
+			case DCH_tz:
+			case DCH_TZ:
+			case DCH_OF:
+				dch_ereport(0,
+							errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+							errmsg("formatting field \"%s\" is only "
+								   "supported in to_char",
+								   n->key->name));
+				flags |= DCH_ZONED;
+				break;
+			case DCH_TZH:
+			case DCH_TZM:
+				flags |= DCH_ZONED;
+				break;
+			case DCH_A_D:
+			case DCH_B_C:
+			case DCH_a_d:
+			case DCH_b_c:
+			case DCH_AD:
+			case DCH_BC:
+			case DCH_ad:
+			case DCH_bc:
+			case DCH_MONTH:
+			case DCH_Month:
+			case DCH_month:
+			case DCH_MON:
+			case DCH_Mon:
+			case DCH_mon:
+			case DCH_MM:
+			case DCH_DAY:
+			case DCH_Day:
+			case DCH_day:
+			case DCH_DY:
+			case DCH_Dy:
+			case DCH_dy:
+			case DCH_DDD:
+			case DCH_IDDD:
+			case DCH_DD:
+			case DCH_D:
+			case DCH_ID:
+			case DCH_WW:
+			case DCH_Q:
+			case DCH_CC:
+			case DCH_Y_YYY:
+			case DCH_YYYY:
+			case DCH_IYYY:
+			case DCH_YYY:
+			case DCH_IYY:
+			case DCH_YY:
+			case DCH_IY:
+			case DCH_Y:
+			case DCH_I:
+			case DCH_RM:
+			case DCH_rm:
+			case DCH_W:
+			case DCH_J:
+				flags |= DCH_DATED;
+				break;
+		}
+	}
+
+	return flags;
+}
+
 /* select a DCHCacheEntry to hold the given format picture */
 static DCHCacheEntry *
 DCH_cache_getnew(const char *str)
@@ -3666,6 +3940,72 @@ interval_to_char(PG_FUNCTION_ARGS)
 	PG_RETURN_TEXT_P(res);
 }
 
+/*
+ * Decode the specified or default timezone, if any, or use the session
+ * timezone if it is allowed.
+ */
+static bool
+get_timezone(struct pg_tm *tm, char *default_tz_name, text *date_txt,
+			 const char *type_name, bool allow_session_timezone,
+			 int *tz, bool *error)
+{
+	/* Use the specified or default time zone, if any. */
+	char	   *tz_name =
+		tm->tm_zone ? unconstify(char *, tm->tm_zone) : default_tz_name;
+
+	if (tz_name)
+	{
+		int			dterr = DecodeTimezone(tz_name, tz);
+
+		if (dterr)
+		{
+			if (error)
+			{
+				*error = true;
+				return false;
+			}
+
+			DateTimeParseError(dterr,
+							   date_txt ? text_to_cstring(date_txt) : tz_name,
+							   type_name);
+		}
+	}
+	else if (*tz == PG_INT32_MIN)
+	{
+		if (!allow_session_timezone)
+			dch_ereport(false,
+						errcode(ERRCODE_INVALID_DATETIME_FORMAT),
+						errmsg("missing time-zone in input string for type %s",
+							   type_name));
+
+		*tz = DetermineTimeZoneOffset(tm, session_timezone);
+	}
+
+	return true;
+}
+
+/*
+ * Convert pg_tm to timestamp ('tz' is NULL) or timestamptz ('tz' is not NULL)
+ * using the specified fractional precision 'typmod'.
+ */
+static inline Timestamp
+tm_to_timestamp(struct pg_tm *tm, fsec_t fsec, int32 typmod, int *tz,
+				bool *error)
+{
+	Timestamp	result;
+
+	if (tm2timestamp(tm, fsec, tz, &result) != 0)
+		dch_ereport(ERROR,
+					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
+					 errmsg("timestamp out of range")));
+
+	/* Use the specified fractional precision, if any. */
+	if (typmod != -1)
+		AdjustTimestampForTypmodError(&result, typmod, error);
+
+	return result;
+}
+
 /* ---------------------
  * TO_TIMESTAMP()
  *
@@ -3678,30 +4018,45 @@ to_timestamp(PG_FUNCTION_ARGS)
 {
 	text	   *date_txt = PG_GETARG_TEXT_PP(0);
 	text	   *fmt = PG_GETARG_TEXT_PP(1);
-	Timestamp	result;
-	int			tz;
+	int			tz = PG_INT32_MIN;
 	struct pg_tm tm;
 	fsec_t		fsec;
+	int			fprec;
 
-	do_to_timestamp(date_txt, fmt, &tm, &fsec);
+	do_to_timestamp(date_txt, fmt, false, &tm, &fsec, &fprec, NULL, NULL);
 
 	/* Use the specified time zone, if any. */
-	if (tm.tm_zone)
-	{
-		int			dterr = DecodeTimezone(unconstify(char *, tm.tm_zone), &tz);
+	get_timezone(&tm, NULL, date_txt, "timestamp", true, &tz, NULL);
 
-		if (dterr)
-			DateTimeParseError(dterr, text_to_cstring(date_txt), "timestamptz");
-	}
-	else
-		tz = DetermineTimeZoneOffset(&tm, session_timezone);
+	PG_RETURN_DATUM(tm_to_timestamp(&tm, fsec, fprec ? fprec : -1, &tz, NULL));
+}
 
-	if (tm2timestamp(&tm, fsec, &tz, &result) != 0)
-		ereport(ERROR,
-				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
-				 errmsg("timestamp out of range")));
+/*
+ * Convert pg_tm to date with out of range checking.
+ */
+static DateADT
+tm_to_date(struct pg_tm *tm, text *date_txt, bool *error)
+{
+	DateADT		result;
+
+	/* Prevent overflow in Julian-day routines */
+	if (!IS_VALID_JULIAN(tm->tm_year, tm->tm_mon, tm->tm_mday))
+		dch_ereport((Datum) 0,
+					errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
+					errmsg("date out of range: \"%s\"",
+						   text_to_cstring(date_txt)));
+
+	result = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) -
+		POSTGRES_EPOCH_JDATE;
+
+	/* Now check for just-out-of-range dates */
+	if (!IS_VALID_DATE(result))
+		dch_ereport((Datum) 0,
+					errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
+					errmsg("date out of range: \"%s\"",
+						   text_to_cstring(date_txt)));
 
-	PG_RETURN_TIMESTAMP(result);
+	return DateADTGetDatum(result);
 }
 
 /* ----------
@@ -3714,36 +4069,149 @@ to_date(PG_FUNCTION_ARGS)
 {
 	text	   *date_txt = PG_GETARG_TEXT_PP(0);
 	text	   *fmt = PG_GETARG_TEXT_PP(1);
-	DateADT		result;
 	struct pg_tm tm;
 	fsec_t		fsec;
 
-	do_to_timestamp(date_txt, fmt, &tm, &fsec);
+	do_to_timestamp(date_txt, fmt, false, &tm, &fsec, NULL, NULL, NULL);
 
-	/* Prevent overflow in Julian-day routines */
-	if (!IS_VALID_JULIAN(tm.tm_year, tm.tm_mon, tm.tm_mday))
-		ereport(ERROR,
-				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
-				 errmsg("date out of range: \"%s\"",
-						text_to_cstring(date_txt))));
+	PG_RETURN_DATUM(tm_to_date(&tm, date_txt, NULL));
+}
+
+/*
+ * Convert pg_tm to timetz using the specified fractional precision 'typmod'
+ * and timezone 'tz'.
+ */
+static Datum
+tm_to_timetz(struct pg_tm *tm, fsec_t fsec, int32 typmod, int *tz, bool *error)
+{
+	TimeTzADT  *result = palloc(sizeof(TimeTzADT));
 
-	result = date2j(tm.tm_year, tm.tm_mon, tm.tm_mday) - POSTGRES_EPOCH_JDATE;
+	if (tm2timetz(tm, fsec, *tz, result) != 0)
+		dch_ereport((Datum) 0,
+					errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
+					errmsg("timetz out of range"));
 
-	/* Now check for just-out-of-range dates */
-	if (!IS_VALID_DATE(result))
-		ereport(ERROR,
-				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
-				 errmsg("date out of range: \"%s\"",
-						text_to_cstring(date_txt))));
+	if (typmod != -1)
+		AdjustTimeForTypmod(&result->time, typmod);
 
-	PG_RETURN_DATEADT(result);
+	return TimeTzADTPGetDatum(result);
+}
+
+/*
+ * Convert pg_tm to time using the specified fractional precision 'typmod'.
+ */
+static Datum
+tm_to_time(struct pg_tm *tm, fsec_t fsec, int32 typmod, bool *error)
+{
+	TimeADT		result;
+
+	if (tm2time(tm, fsec, &result) != 0)
+		dch_ereport((Datum) 0,
+					errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
+					errmsg("time out of range"));
+
+	if (typmod != -1)
+		AdjustTimeForTypmod(&result, typmod);
+
+	return TimeADTGetDatum(result);
+}
+
+/*
+ * Make datetime type from 'date_txt' which is formated at argument 'fmt'.
+ * Actual datatype (returned in 'typid', 'typmod') is determined by
+ * presence of date/time/zone components in the format string.
+ *
+ * Default time-zone for tz types is specified with 'tzname'.  If 'tzname' is
+ * NULL and the input string does not contain zone components then "missing tz"
+ * error is thrown.
+ *
+ * If 'error' is NULL, then errors are thrown, else '*error' is set and
+ * ((Datum) 0) is returned.
+ */
+Datum
+parse_datetime(text *date_txt, text *fmt, char *tzname, bool strict,
+			   Oid *typid, int32 *typmod, int *tz, bool *error)
+{
+	struct pg_tm tm;
+	fsec_t		fsec;
+	int			fprec = 0;
+	int			flags;
+
+	if (!do_to_timestamp(date_txt, fmt, strict, &tm, &fsec, &fprec, &flags,
+						 error))
+		return (Datum) 0;
+
+	/* Save default time-zone for non-zoned types. */
+	if (!(flags & DCH_ZONED) && tzname &&
+		!get_timezone(&tm, tzname, NULL, "timezone", false, tz, error))
+		return (Datum) 0;
+
+	if (flags & DCH_DATED)
+	{
+		if (flags & DCH_TIMED)
+		{
+			*typmod = fprec ? fprec : -1;	/* fractional part precision */
+
+			if (flags & DCH_ZONED)
+			{
+				if (!get_timezone(&tm, tzname, NULL, "timestamptz", false, tz,
+								  error))
+					return (Datum) 0;
+
+				*typid = TIMESTAMPTZOID;
+				return tm_to_timestamp(&tm, fsec, *typmod, tz, error);
+			}
+			else
+			{
+				*typid = TIMESTAMPOID;
+				return tm_to_timestamp(&tm, fsec, *typmod, NULL, error);
+			}
+		}
+		else
+		{
+			if (flags & DCH_ZONED)
+				dch_ereport((Datum) 0,
+							errcode(ERRCODE_INVALID_DATETIME_FORMAT),
+							errmsg("datetime format is zoned but not timed"));
+
+			*typid = DATEOID;
+			*typmod = -1;
+			return tm_to_date(&tm, date_txt, error);
+		}
+	}
+	else if (flags & DCH_TIMED)
+	{
+		*typmod = fprec ? fprec : -1;	/* fractional part precision */
+
+		if (flags & DCH_ZONED)
+		{
+			if (!get_timezone(&tm, tzname, NULL, "timetz", false, tz, error))
+				return (Datum) 0;
+
+			*typid = TIMETZOID;
+			return tm_to_timetz(&tm, fsec, *typmod, tz, error);
+		}
+		else
+		{
+			*typid = TIMEOID;
+			return tm_to_time(&tm, fsec, *typmod, error);
+		}
+	}
+	else
+	{
+		dch_ereport((Datum) 0,
+					errcode(ERRCODE_INVALID_DATETIME_FORMAT),
+					errmsg("datetime format is not dated and not timed"));
+	}
+
+	return (Datum) 0;
 }
 
 /*
  * do_to_timestamp: shared code for to_timestamp and to_date
  *
  * Parse the 'date_txt' according to 'fmt', return results as a struct pg_tm
- * and fractional seconds.
+ * and fractional seconds and fractional precision.
  *
  * We parse 'fmt' into a list of FormatNodes, which is then passed to
  * DCH_from_char to populate a TmFromChar with the parsed contents of
@@ -3751,10 +4219,18 @@ to_date(PG_FUNCTION_ARGS)
  *
  * The TmFromChar is then analysed and converted into the final results in
  * struct 'tm' and 'fsec'.
+ *
+ * Bit mask of date/time/zone components found in 'fmt' is returned in 'flags'.
+ *
+ * 'strict' enables error reporting on unmatched trailing characters in input or
+ * format strings patterns.
+ *
+ * If 'error' is NULL, then errors are thrown, else '*error' is set and false
+ * is returned.
  */
-static void
-do_to_timestamp(text *date_txt, text *fmt,
-				struct pg_tm *tm, fsec_t *fsec)
+static bool
+do_to_timestamp(text *date_txt, text *fmt, bool strict, struct pg_tm *tm,
+				fsec_t *fsec, int *fprec, int *flags, bool *error)
 {
 	FormatNode *format;
 	TmFromChar	tmfc;
@@ -3807,11 +4283,18 @@ do_to_timestamp(text *date_txt, text *fmt,
 		/* dump_index(DCH_keywords, DCH_index); */
 #endif
 
-		DCH_from_char(format, date_str, &tmfc);
+		DCH_from_char(format, date_str, &tmfc, strict, error);
 
 		pfree(fmt_str);
+
+		if (flags && (!error || !*error))
+			*flags = DCH_datetime_type(format, error);
+
 		if (!incache)
 			pfree(format);
+
+		if (error && *error)
+			goto err;
 	}
 
 	DEBUG_TMFC(&tmfc);
@@ -3840,11 +4323,15 @@ do_to_timestamp(text *date_txt, text *fmt,
 	if (tmfc.clock == CLOCK_12_HOUR)
 	{
 		if (tm->tm_hour < 1 || tm->tm_hour > HOURS_PER_DAY / 2)
+		{
+			if (error)
+				goto err;
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
 					 errmsg("hour \"%d\" is invalid for the 12-hour clock",
 							tm->tm_hour),
 					 errhint("Use the 24-hour clock, or give an hour between 1 and 12.")));
+		}
 
 		if (tmfc.pm && tm->tm_hour < HOURS_PER_DAY / 2)
 			tm->tm_hour += HOURS_PER_DAY / 2;
@@ -3948,9 +4435,13 @@ do_to_timestamp(text *date_txt, text *fmt,
 		 */
 
 		if (!tm->tm_year && !tmfc.bc)
+		{
+			if (error)
+				goto err;
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_DATETIME_FORMAT),
 					 errmsg("cannot calculate day of year without year information")));
+		}
 
 		if (tmfc.mode == FROM_CHAR_DATE_ISOWEEK)
 		{
@@ -3991,6 +4482,8 @@ do_to_timestamp(text *date_txt, text *fmt,
 		*fsec += tmfc.ms * 1000;
 	if (tmfc.us)
 		*fsec += tmfc.us;
+	if (fprec)
+		*fprec = tmfc.ff;		/* fractional precision, if specified */
 
 	/* Range-check date fields according to bit mask computed above */
 	if (fmask != 0)
@@ -4000,6 +4493,9 @@ do_to_timestamp(text *date_txt, text *fmt,
 
 		if (dterr != 0)
 		{
+			if (error)
+				goto err;
+
 			/*
 			 * Force the error to be DTERR_FIELD_OVERFLOW even if ValidateDate
 			 * said DTERR_MD_FIELD_OVERFLOW, because we don't want to print an
@@ -4014,7 +4510,12 @@ do_to_timestamp(text *date_txt, text *fmt,
 		tm->tm_min < 0 || tm->tm_min >= MINS_PER_HOUR ||
 		tm->tm_sec < 0 || tm->tm_sec >= SECS_PER_MINUTE ||
 		*fsec < INT64CONST(0) || *fsec >= USECS_PER_SEC)
+	{
+		if (error)
+			goto err;
+
 		DateTimeParseError(DTERR_FIELD_OVERFLOW, date_str, "timestamp");
+	}
 
 	/* Save parsed time-zone into tm->tm_zone if it was specified */
 	if (tmfc.tzsign)
@@ -4023,7 +4524,12 @@ do_to_timestamp(text *date_txt, text *fmt,
 
 		if (tmfc.tzh < 0 || tmfc.tzh > MAX_TZDISP_HOUR ||
 			tmfc.tzm < 0 || tmfc.tzm >= MINS_PER_HOUR)
+		{
+			if (error)
+				goto err;
+
 			DateTimeParseError(DTERR_TZDISP_OVERFLOW, date_str, "timestamp");
+		}
 
 		tz = psprintf("%c%02d:%02d",
 					  tmfc.tzsign > 0 ? '+' : '-', tmfc.tzh, tmfc.tzm);
@@ -4034,6 +4540,12 @@ do_to_timestamp(text *date_txt, text *fmt,
 	DEBUG_TM(tm);
 
 	pfree(date_str);
+	return true;
+
+err:
+	*error = true;
+	pfree(date_str);
+	return false;
 }
 
 
diff --git a/src/backend/utils/adt/json.c b/src/backend/utils/adt/json.c
index de0d072..5239903 100644
--- a/src/backend/utils/adt/json.c
+++ b/src/backend/utils/adt/json.c
@@ -1506,7 +1506,7 @@ datum_to_json(Datum val, bool is_null, StringInfo result,
 			{
 				char		buf[MAXDATELEN + 1];
 
-				JsonEncodeDateTime(buf, val, DATEOID);
+				JsonEncodeDateTime(buf, val, DATEOID, NULL);
 				appendStringInfo(result, "\"%s\"", buf);
 			}
 			break;
@@ -1514,7 +1514,7 @@ datum_to_json(Datum val, bool is_null, StringInfo result,
 			{
 				char		buf[MAXDATELEN + 1];
 
-				JsonEncodeDateTime(buf, val, TIMESTAMPOID);
+				JsonEncodeDateTime(buf, val, TIMESTAMPOID, NULL);
 				appendStringInfo(result, "\"%s\"", buf);
 			}
 			break;
@@ -1522,7 +1522,7 @@ datum_to_json(Datum val, bool is_null, StringInfo result,
 			{
 				char		buf[MAXDATELEN + 1];
 
-				JsonEncodeDateTime(buf, val, TIMESTAMPTZOID);
+				JsonEncodeDateTime(buf, val, TIMESTAMPTZOID, NULL);
 				appendStringInfo(result, "\"%s\"", buf);
 			}
 			break;
@@ -1550,10 +1550,11 @@ datum_to_json(Datum val, bool is_null, StringInfo result,
 
 /*
  * Encode 'value' of datetime type 'typid' into JSON string in ISO format using
- * optionally preallocated buffer 'buf'.
+ * optionally preallocated buffer 'buf'.  Optional 'tzp' determines time-zone
+ * offset (in seconds) in which we want to show timestamptz.
  */
 char *
-JsonEncodeDateTime(char *buf, Datum value, Oid typid)
+JsonEncodeDateTime(char *buf, Datum value, Oid typid, const int *tzp)
 {
 	if (!buf)
 		buf = palloc(MAXDATELEN + 1);
@@ -1630,11 +1631,30 @@ JsonEncodeDateTime(char *buf, Datum value, Oid typid)
 				const char *tzn = NULL;
 
 				timestamp = DatumGetTimestampTz(value);
+
+				/*
+				 * If time-zone is specified, we apply a time-zone shift,
+				 * convert timestamptz to pg_tm as if it was without
+				 * time-zone, and then use specified time-zone for encoding
+				 * timestamp into a string.
+				 */
+				if (tzp)
+				{
+					tz = *tzp;
+					timestamp -= (TimestampTz) tz * USECS_PER_SEC;
+				}
+
 				/* Same as timestamptz_out(), but forcing DateStyle */
 				if (TIMESTAMP_NOT_FINITE(timestamp))
 					EncodeSpecialTimestamp(timestamp, buf);
-				else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0)
+				else if (timestamp2tm(timestamp, tzp ? NULL : &tz, &tm, &fsec,
+									  tzp ? NULL : &tzn, NULL) == 0)
+				{
+					if (tzp)
+						tm.tm_isdst = 1;	/* set time-zone presence flag */
+
 					EncodeDateTime(&tm, fsec, true, tz, tzn, USE_XSD_DATES, buf);
+				}
 				else
 					ereport(ERROR,
 							(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
diff --git a/src/backend/utils/adt/jsonb.c b/src/backend/utils/adt/jsonb.c
index 7af4091..87d3a8d 100644
--- a/src/backend/utils/adt/jsonb.c
+++ b/src/backend/utils/adt/jsonb.c
@@ -206,6 +206,24 @@ JsonbTypeName(JsonbValue *jbv)
 			return "boolean";
 		case jbvNull:
 			return "null";
+		case jbvDatetime:
+			switch (jbv->val.datetime.typid)
+			{
+				case DATEOID:
+					return "date";
+				case TIMEOID:
+					return "time without time zone";
+				case TIMETZOID:
+					return "time with time zone";
+				case TIMESTAMPOID:
+					return "timestamp without time zone";
+				case TIMESTAMPTZOID:
+					return "timestamp with time zone";
+				default:
+					elog(ERROR, "unrecognized jsonb value datetime type: %d",
+						 jbv->val.datetime.typid);
+			}
+			return "unknown";
 		default:
 			elog(ERROR, "unrecognized jsonb value type: %d", jbv->type);
 			return "unknown";
@@ -805,17 +823,20 @@ datum_to_jsonb(Datum val, bool is_null, JsonbInState *result,
 				break;
 			case JSONBTYPE_DATE:
 				jb.type = jbvString;
-				jb.val.string.val = JsonEncodeDateTime(NULL, val, DATEOID);
+				jb.val.string.val = JsonEncodeDateTime(NULL, val,
+													   DATEOID, NULL);
 				jb.val.string.len = strlen(jb.val.string.val);
 				break;
 			case JSONBTYPE_TIMESTAMP:
 				jb.type = jbvString;
-				jb.val.string.val = JsonEncodeDateTime(NULL, val, TIMESTAMPOID);
+				jb.val.string.val = JsonEncodeDateTime(NULL, val,
+													   TIMESTAMPOID, NULL);
 				jb.val.string.len = strlen(jb.val.string.val);
 				break;
 			case JSONBTYPE_TIMESTAMPTZ:
 				jb.type = jbvString;
-				jb.val.string.val = JsonEncodeDateTime(NULL, val, TIMESTAMPTZOID);
+				jb.val.string.val = JsonEncodeDateTime(NULL, val,
+													   TIMESTAMPTZOID, NULL);
 				jb.val.string.len = strlen(jb.val.string.val);
 				break;
 			case JSONBTYPE_JSONCAST:
diff --git a/src/backend/utils/adt/jsonb_util.c b/src/backend/utils/adt/jsonb_util.c
index d8276ab..5618d39 100644
--- a/src/backend/utils/adt/jsonb_util.c
+++ b/src/backend/utils/adt/jsonb_util.c
@@ -15,8 +15,11 @@
 
 #include "access/hash.h"
 #include "catalog/pg_collation.h"
+#include "catalog/pg_type.h"
 #include "miscadmin.h"
 #include "utils/builtins.h"
+#include "utils/datetime.h"
+#include "utils/jsonapi.h"
 #include "utils/jsonb.h"
 #include "utils/memutils.h"
 #include "utils/varlena.h"
@@ -241,6 +244,7 @@ compareJsonbContainers(JsonbContainer *a, JsonbContainer *b)
 							res = (va.val.object.nPairs > vb.val.object.nPairs) ? 1 : -1;
 						break;
 					case jbvBinary:
+					case jbvDatetime:
 						elog(ERROR, "unexpected jbvBinary value");
 				}
 			}
@@ -1749,6 +1753,22 @@ convertJsonbScalar(StringInfo buffer, JEntry *jentry, JsonbValue *scalarVal)
 				JENTRY_ISBOOL_TRUE : JENTRY_ISBOOL_FALSE;
 			break;
 
+		case jbvDatetime:
+			{
+				char		buf[MAXDATELEN + 1];
+				size_t		len;
+
+				JsonEncodeDateTime(buf,
+								   scalarVal->val.datetime.value,
+								   scalarVal->val.datetime.typid,
+								   &scalarVal->val.datetime.tz);
+				len = strlen(buf);
+				appendToBuffer(buffer, buf, len);
+
+				*jentry = JENTRY_ISSTRING | len;
+			}
+			break;
+
 		default:
 			elog(ERROR, "invalid jsonb scalar type");
 	}
diff --git a/src/backend/utils/adt/jsonpath.c b/src/backend/utils/adt/jsonpath.c
index 0696b04..450e5e9 100644
--- a/src/backend/utils/adt/jsonpath.c
+++ b/src/backend/utils/adt/jsonpath.c
@@ -282,6 +282,7 @@ flattenJsonPathParseItem(StringInfo buf, JsonPathParseItem *item,
 		case jpiDiv:
 		case jpiMod:
 		case jpiStartsWith:
+		case jpiDatetime:
 			{
 				int32		left,
 							right;
@@ -684,6 +685,22 @@ printJsonPathItem(StringInfo buf, JsonPathItem *v, bool inKey,
 		case jpiDouble:
 			appendBinaryStringInfo(buf, ".double()", 9);
 			break;
+		case jpiDatetime:
+			appendBinaryStringInfo(buf, ".datetime(", 10);
+			if (v->content.args.left)
+			{
+				jspGetLeftArg(v, &elem);
+				printJsonPathItem(buf, &elem, false, false);
+
+				if (v->content.args.right)
+				{
+					appendBinaryStringInfo(buf, ", ", 2);
+					jspGetRightArg(v, &elem);
+					printJsonPathItem(buf, &elem, false, false);
+				}
+			}
+			appendStringInfoChar(buf, ')');
+			break;
 		case jpiKeyValue:
 			appendBinaryStringInfo(buf, ".keyvalue()", 11);
 			break;
@@ -746,6 +763,8 @@ jspOperationName(JsonPathItemType type)
 			return "floor";
 		case jpiCeiling:
 			return "ceiling";
+		case jpiDatetime:
+			return "datetime";
 		default:
 			elog(ERROR, "unrecognized jsonpath item type: %d", type);
 			return NULL;
@@ -866,6 +885,7 @@ jspInitByBuffer(JsonPathItem *v, char *base, int32 pos)
 		case jpiLessOrEqual:
 		case jpiGreaterOrEqual:
 		case jpiStartsWith:
+		case jpiDatetime:
 			read_int32(v->content.args.left, base, pos);
 			read_int32(v->content.args.right, base, pos);
 			break;
@@ -953,6 +973,7 @@ jspGetNext(JsonPathItem *v, JsonPathItem *a)
 			   v->type == jpiFloor ||
 			   v->type == jpiCeiling ||
 			   v->type == jpiDouble ||
+			   v->type == jpiDatetime ||
 			   v->type == jpiKeyValue ||
 			   v->type == jpiStartsWith);
 
@@ -980,6 +1001,7 @@ jspGetLeftArg(JsonPathItem *v, JsonPathItem *a)
 		   v->type == jpiMul ||
 		   v->type == jpiDiv ||
 		   v->type == jpiMod ||
+		   v->type == jpiDatetime ||
 		   v->type == jpiStartsWith);
 
 	jspInitByBuffer(a, v->base, v->content.args.left);
@@ -1001,6 +1023,7 @@ jspGetRightArg(JsonPathItem *v, JsonPathItem *a)
 		   v->type == jpiMul ||
 		   v->type == jpiDiv ||
 		   v->type == jpiMod ||
+		   v->type == jpiDatetime ||
 		   v->type == jpiStartsWith);
 
 	jspInitByBuffer(a, v->base, v->content.args.right);
diff --git a/src/backend/utils/adt/jsonpath_exec.c b/src/backend/utils/adt/jsonpath_exec.c
index c6a5073..7d84ef9 100644
--- a/src/backend/utils/adt/jsonpath_exec.c
+++ b/src/backend/utils/adt/jsonpath_exec.c
@@ -66,6 +66,7 @@
 #include "miscadmin.h"
 #include "regex/regex.h"
 #include "utils/builtins.h"
+#include "utils/datetime.h"
 #include "utils/datum.h"
 #include "utils/formatting.h"
 #include "utils/float.h"
@@ -86,6 +87,8 @@
 #define ERRMSG_SINGLETON_JSON_ITEM_REQUIRED	"singleton SQL/JSON item required"
 #define ERRMSG_NON_NUMERIC_JSON_ITEM		"non-numeric SQL/JSON item"
 #define ERRMSG_INVALID_JSON_SUBSCRIPT		"invalid SQL/JSON subscript"
+#define ERRMSG_INVALID_ARGUMENT_FOR_JSON_DATETIME_FUNCTION	\
+	"invalid argument for SQL/JSON datetime function"
 
 /*
  * Represents "base object" and it's "id" for .keyvalue() evaluation.
@@ -256,6 +259,13 @@ static int	JsonbType(JsonbValue *jb);
 static JsonbValue *getScalar(JsonbValue *scalar, enum jbvType type);
 static JsonbValue *wrapItemsInArray(const JsonValueList *items);
 
+static bool tryToParseDatetime(text *fmt, text *datetime, char *tzname,
+				   bool strict, Datum *value, Oid *typid,
+				   int32 *typmod, int *tzp, bool throwErrors);
+static int compareDatetime(Datum val1, Oid typid1, int tz1,
+				Datum val2, Oid typid2, int tz2,
+				bool *error);
+
 /****************** User interface to JsonPath executor ********************/
 
 /*
@@ -1056,6 +1066,177 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 			}
 			break;
 
+		case jpiDatetime:
+			{
+				JsonbValue	jbvbuf;
+				Datum		value;
+				text	   *datetime;
+				Oid			typid;
+				int32		typmod = -1;
+				int			tz = PG_INT32_MIN;
+				bool		hasNext;
+				char	   *tzname = NULL;
+
+				if (unwrap && JsonbType(jb) == jbvArray)
+					return recursiveExecuteUnwrapArray(cxt, jsp, jb, found,
+													   false);
+
+				if (!(jb = getScalar(jb, jbvString)))
+					RETURN_ERROR(ereport(ERROR,
+										 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_JSON_DATETIME_FUNCTION),
+										  errmsg(ERRMSG_INVALID_ARGUMENT_FOR_JSON_DATETIME_FUNCTION),
+										  errdetail("jsonpath item method .%s() is "
+													"applied to not a string",
+													jspOperationName(jsp->type)))));
+
+				datetime = cstring_to_text_with_len(jb->val.string.val,
+													jb->val.string.len);
+
+				if (jsp->content.args.left)
+				{
+					text	   *template;
+					char	   *template_str;
+					int			template_len;
+
+					jspGetLeftArg(jsp, &elem);
+
+					if (elem.type != jpiString)
+						elog(ERROR, "invalid jsonpath item type for "
+							 ".datetime() argument");
+
+					template_str = jspGetString(&elem, &template_len);
+
+					if (jsp->content.args.right)
+					{
+						JsonValueList tzlist = {0};
+						JsonPathExecResult tzres;
+						JsonbValue *tzjbv;
+
+						jspGetRightArg(jsp, &elem);
+						tzres = recursiveExecute(cxt, &elem, jb, &tzlist);
+						if (jperIsError(tzres))
+							return tzres;
+
+						if (JsonValueListLength(&tzlist) != 1 ||
+							((tzjbv = JsonValueListHead(&tzlist))->type != jbvString &&
+							 tzjbv->type != jbvNumeric))
+							RETURN_ERROR(ereport(ERROR,
+												 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_JSON_DATETIME_FUNCTION),
+												  errmsg(ERRMSG_INVALID_ARGUMENT_FOR_JSON_DATETIME_FUNCTION),
+												  errdetail("timezone argument of "
+															"jsonpath item method .%s() "
+															"is not a singleton string or number",
+															jspOperationName(jsp->type)))));
+
+						if (tzjbv->type == jbvString)
+							tzname = pnstrdup(tzjbv->val.string.val,
+											  tzjbv->val.string.len);
+						else
+						{
+							bool		error = false;
+
+							tz = numeric_int4_error(tzjbv->val.numeric, &error);
+
+							if (error || tz == PG_INT32_MIN)
+								RETURN_ERROR(ereport(ERROR,
+													 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_JSON_DATETIME_FUNCTION),
+													  errmsg(ERRMSG_INVALID_ARGUMENT_FOR_JSON_DATETIME_FUNCTION),
+													  errdetail("timezone argument of "
+																"jsonpath item method .%s() "
+																"is out of integer range",
+																jspOperationName(jsp->type)))));
+
+							tz = -tz;
+						}
+					}
+
+					if (template_len)
+					{
+						template = cstring_to_text_with_len(template_str,
+															template_len);
+
+						if (tryToParseDatetime(template, datetime, tzname, false,
+											   &value, &typid, &typmod,
+											   &tz, jspThrowErrors(cxt)))
+							res = jperOk;
+						else
+							res = jperError;
+					}
+				}
+
+				if (res == jperNotFound)
+				{
+					/* Try to recognize one of ISO formats. */
+					static const char *fmt_str[] =
+					{
+						"yyyy-mm-dd HH24:MI:SS TZH:TZM",
+						"yyyy-mm-dd HH24:MI:SS TZH",
+						"yyyy-mm-dd HH24:MI:SS",
+						"yyyy-mm-dd",
+						"HH24:MI:SS TZH:TZM",
+						"HH24:MI:SS TZH",
+						"HH24:MI:SS"
+					};
+
+					/* cache for format texts */
+					static text *fmt_txt[lengthof(fmt_str)] = {0};
+					int			i;
+
+					for (i = 0; i < lengthof(fmt_str); i++)
+					{
+						if (!fmt_txt[i])
+						{
+							MemoryContext oldcxt =
+							MemoryContextSwitchTo(TopMemoryContext);
+
+							fmt_txt[i] = cstring_to_text(fmt_str[i]);
+							MemoryContextSwitchTo(oldcxt);
+						}
+
+						if (tryToParseDatetime(fmt_txt[i], datetime, tzname,
+											   true, &value, &typid, &typmod,
+											   &tz, false))
+						{
+							res = jperOk;
+							break;
+						}
+					}
+
+					if (res == jperNotFound)
+						RETURN_ERROR(ereport(ERROR,
+											 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_JSON_DATETIME_FUNCTION),
+											  errmsg(ERRMSG_INVALID_ARGUMENT_FOR_JSON_DATETIME_FUNCTION),
+											  errdetail("unrecognized datetime format"),
+											  errhint("use datetime template "
+													  "argument for explicit "
+													  "format specification"))));
+				}
+
+				if (tzname)
+					pfree(tzname);
+
+				pfree(datetime);
+
+				if (jperIsError(res))
+					break;
+
+				hasNext = jspGetNext(jsp, &elem);
+
+				if (!hasNext && !found)
+					break;
+
+				jb = hasNext ? &jbvbuf : palloc(sizeof(*jb));
+
+				jb->type = jbvDatetime;
+				jb->val.datetime.value = value;
+				jb->val.datetime.typid = typid;
+				jb->val.datetime.typmod = typmod;
+				jb->val.datetime.tz = tz;
+
+				res = recursiveExecuteNext(cxt, jsp, &elem, jb, found, hasNext);
+			}
+			break;
+
 		case jpiKeyValue:
 			if (unwrap && JsonbType(jb) == jbvArray)
 				return recursiveExecuteUnwrapArray(cxt, jsp, jb, found, false);
@@ -2044,6 +2225,22 @@ compareItems(int32 op, JsonbValue *jb1, JsonbValue *jb2)
 							 jb2->val.string.val, jb2->val.string.len,
 							 DEFAULT_COLLATION_OID);
 			break;
+		case jbvDatetime:
+			{
+				bool		error = false;
+
+				cmp = compareDatetime(jb1->val.datetime.value,
+									  jb1->val.datetime.typid,
+									  jb1->val.datetime.tz,
+									  jb2->val.datetime.value,
+									  jb2->val.datetime.typid,
+									  jb2->val.datetime.tz,
+									  &error);
+
+				if (error)
+					return jpbUnknown;
+			}
+			break;
 
 		case jbvBinary:
 		case jbvArray:
@@ -2303,3 +2500,242 @@ wrapItemsInArray(const JsonValueList *items)
 
 	return pushJsonbValue(&ps, WJB_END_ARRAY, NULL);
 }
+
+static inline Datum
+time_to_timetz(Datum time, int tz, bool *error)
+{
+	TimeADT		tm = DatumGetTimeADT(time);
+	TimeTzADT  *result = palloc(sizeof(TimeTzADT));
+
+	if (tz == PG_INT32_MIN)
+	{
+		*error = true;
+		return (Datum) 0;
+	}
+
+	result->time = tm;
+	result->zone = tz;
+
+	return TimeTzADTPGetDatum(result);
+}
+
+static inline Datum
+date_to_timestamp(Datum date, bool *error)
+{
+	DateADT		dt = DatumGetDateADT(date);
+	Timestamp	ts = date2timestamp_internal(dt, error);
+
+	return TimestampGetDatum(ts);
+}
+
+static inline Datum
+date_to_timestamptz(Datum date, int tz, bool *error)
+{
+	DateADT		dt = DatumGetDateADT(date);
+	TimestampTz ts;
+
+	if (tz == PG_INT32_MIN)
+	{
+		*error = true;
+		return (Datum) 0;
+	}
+
+	ts = date2timestamptz_internal(dt, &tz, error);
+
+	return TimestampTzGetDatum(ts);
+}
+
+static inline Datum
+timestamp_to_timestamptz(Datum val, int tz, bool *error)
+{
+	Timestamp	ts = DatumGetTimestamp(val);
+	TimestampTz tstz;
+
+	if (tz == PG_INT32_MIN)
+	{
+		*error = true;
+		return (Datum) 0;
+	}
+
+	tstz = timestamp2timestamptz_internal(ts, &tz, error);
+
+	return TimestampTzGetDatum(tstz);
+}
+
+/*
+ * Cross-type comparison of two datetime SQL/JSON items.  If items are
+ * uncomparable, 'error' flag is set.
+ */
+static int
+compareDatetime(Datum val1, Oid typid1, int tz1,
+				Datum val2, Oid typid2, int tz2,
+				bool *error)
+{
+	PGFunction cmpfunc = NULL;
+
+	switch (typid1)
+	{
+		case DATEOID:
+			switch (typid2)
+			{
+				case DATEOID:
+					cmpfunc = date_cmp;
+
+					break;
+
+				case TIMESTAMPOID:
+					val1 = date_to_timestamp(val1, error);
+					cmpfunc = timestamp_cmp;
+
+					break;
+
+				case TIMESTAMPTZOID:
+					val1 = date_to_timestamptz(val1, tz1, error);
+					cmpfunc = timestamp_cmp;
+
+					break;
+
+				case TIMEOID:
+				case TIMETZOID:
+					*error = true;
+					return 0;
+			}
+			break;
+
+		case TIMEOID:
+			switch (typid2)
+			{
+				case TIMEOID:
+					cmpfunc = time_cmp;
+
+					break;
+
+				case TIMETZOID:
+					val1 = time_to_timetz(val1, tz1, error);
+					cmpfunc = timetz_cmp;
+
+					break;
+
+				case DATEOID:
+				case TIMESTAMPOID:
+				case TIMESTAMPTZOID:
+					*error = true;
+					return 0;
+			}
+			break;
+
+		case TIMETZOID:
+			switch (typid2)
+			{
+				case TIMEOID:
+					val2 = time_to_timetz(val2, tz2, error);
+					cmpfunc = timetz_cmp;
+
+					break;
+
+				case TIMETZOID:
+					cmpfunc = timetz_cmp;
+
+					break;
+
+				case DATEOID:
+				case TIMESTAMPOID:
+				case TIMESTAMPTZOID:
+					*error = true;
+					return 0;
+			}
+			break;
+
+		case TIMESTAMPOID:
+			switch (typid2)
+			{
+				case DATEOID:
+					val2 = date_to_timestamp(val2, error);
+					cmpfunc = timestamp_cmp;
+
+					break;
+
+				case TIMESTAMPOID:
+					cmpfunc = timestamp_cmp;
+
+					break;
+
+				case TIMESTAMPTZOID:
+					val1 = timestamp_to_timestamptz(val1, tz1, error);
+					cmpfunc = timestamp_cmp;
+
+					break;
+
+				case TIMEOID:
+				case TIMETZOID:
+					*error = true;
+					return 0;
+			}
+			break;
+
+		case TIMESTAMPTZOID:
+			switch (typid2)
+			{
+				case DATEOID:
+					val2 = date_to_timestamptz(val2, tz2, error);
+					cmpfunc = timestamp_cmp;
+
+					break;
+
+				case TIMESTAMPOID:
+					val2 = timestamp_to_timestamptz(val2, tz2, error);
+					cmpfunc = timestamp_cmp;
+
+					break;
+
+				case TIMESTAMPTZOID:
+					cmpfunc = timestamp_cmp;
+
+					break;
+
+				case TIMEOID:
+				case TIMETZOID:
+					*error = true;
+					return 0;
+			}
+			break;
+
+		default:
+			elog(ERROR, "unrecognized SQL/JSON datetime type oid: %d",
+				 typid1);
+	}
+
+	if (*error)
+		return 0;
+
+	if (!cmpfunc)
+		elog(ERROR, "unrecognized SQL/JSON datetime type oid: %d",
+			 typid2);
+
+	*error = false;
+
+	return DatumGetInt32(DirectFunctionCall2(cmpfunc, val1, val2));
+}
+
+/*
+ * Try to parse datetime text with the specified datetime template and
+ * default time-zone 'tzname'.
+ * Returns 'value' datum, its type 'typid' and 'typmod'.
+ * Datetime error is rethrown with SQL/JSON errcode if 'throwErrors' is true.
+ */
+static bool
+tryToParseDatetime(text *fmt, text *datetime, char *tzname, bool strict,
+				   Datum *value, Oid *typid, int32 *typmod, int *tzp,
+				   bool throwErrors)
+{
+	bool		error = false;
+	int			tz = *tzp;
+
+	*value = parse_datetime(datetime, fmt, tzname, strict, typid, typmod,
+							&tz, throwErrors ? NULL : &error);
+
+	if (!error)
+		*tzp = tz;
+
+	return !error;
+}
diff --git a/src/backend/utils/adt/jsonpath_gram.y b/src/backend/utils/adt/jsonpath_gram.y
index 183861f..1dd5978 100644
--- a/src/backend/utils/adt/jsonpath_gram.y
+++ b/src/backend/utils/adt/jsonpath_gram.y
@@ -283,12 +283,14 @@ makeItemLikeRegex(JsonPathParseItem *expr, string *pattern, string *flags)
 %token	<str>		LESS_P LESSEQUAL_P EQUAL_P NOTEQUAL_P GREATEREQUAL_P GREATER_P
 %token	<str>		ANY_P STRICT_P LAX_P LAST_P STARTS_P WITH_P LIKE_REGEX_P FLAG_P
 %token	<str>		ABS_P SIZE_P TYPE_P FLOOR_P DOUBLE_P CEILING_P KEYVALUE_P
+%token	<str>		DATETIME_P
 
 %type	<result>	result
 
 %type	<value>		scalar_value path_primary expr array_accessor
 					any_path accessor_op key predicate delimited_predicate
 					index_elem starts_with_initial expr_or_predicate
+					datetime_template opt_datetime_template
 
 %type	<elems>		accessor_expr
 
@@ -434,9 +436,22 @@ accessor_op:
 	| array_accessor				{ $$ = $1; }
 	| '.' any_path					{ $$ = $2; }
 	| '.' method '(' ')'			{ $$ = makeItemType($2); }
+	| '.' DATETIME_P '(' opt_datetime_template ')'
+									{ $$ = makeItemBinary(jpiDatetime, $4, NULL); }
+	| '.' DATETIME_P '(' datetime_template ',' expr ')'
+									{ $$ = makeItemBinary(jpiDatetime, $4, $6); }
 	| '?' '(' predicate ')'			{ $$ = makeItemUnary(jpiFilter, $3); }
 	;
 
+datetime_template:
+	STRING_P						{ $$ = makeItemString(&$1); }
+	;
+
+opt_datetime_template:
+	datetime_template				{ $$ = $1; }
+	| /* EMPTY */					{ $$ = NULL; }
+	;
+
 key:
 	key_name						{ $$ = makeItemKey(&$1); }
 	;
@@ -459,6 +474,7 @@ key_name:
 	| FLOOR_P
 	| DOUBLE_P
 	| CEILING_P
+	| DATETIME_P
 	| KEYVALUE_P
 	| LAST_P
 	| STARTS_P
diff --git a/src/backend/utils/adt/jsonpath_scan.l b/src/backend/utils/adt/jsonpath_scan.l
index 110ea21..52db47c 100644
--- a/src/backend/utils/adt/jsonpath_scan.l
+++ b/src/backend/utils/adt/jsonpath_scan.l
@@ -315,6 +315,7 @@ static keyword keywords[] = {
 	{ 6, false,	STRICT_P,	"strict"},
 	{ 7, false,	CEILING_P,	"ceiling"},
 	{ 7, false,	UNKNOWN_P,	"unknown"},
+	{ 8, false,	DATETIME_P,	"datetime"},
 	{ 8, false,	KEYVALUE_P,	"keyvalue"},
 	{ 10,false, LIKE_REGEX_P, "like_regex"},
 };
diff --git a/src/backend/utils/adt/timestamp.c b/src/backend/utils/adt/timestamp.c
index e0ef2f7..04596e1 100644
--- a/src/backend/utils/adt/timestamp.c
+++ b/src/backend/utils/adt/timestamp.c
@@ -71,7 +71,6 @@ typedef struct
 
 static TimeOffset time2t(const int hour, const int min, const int sec, const fsec_t fsec);
 static Timestamp dt2local(Timestamp dt, int timezone);
-static void AdjustTimestampForTypmod(Timestamp *time, int32 typmod);
 static void AdjustIntervalForTypmod(Interval *interval, int32 typmod);
 static TimestampTz timestamp2timestamptz(Timestamp timestamp);
 static Timestamp timestamptz2timestamp(TimestampTz timestamp);
@@ -339,11 +338,11 @@ timestamp_scale(PG_FUNCTION_ARGS)
 }
 
 /*
- * AdjustTimestampForTypmod --- round off a timestamp to suit given typmod
+ * AdjustTimestampForTypmodError --- round off a timestamp to suit given typmod
  * Works for either timestamp or timestamptz.
  */
-static void
-AdjustTimestampForTypmod(Timestamp *time, int32 typmod)
+bool
+AdjustTimestampForTypmodError(Timestamp *time, int32 typmod, bool *error)
 {
 	static const int64 TimestampScales[MAX_TIMESTAMP_PRECISION + 1] = {
 		INT64CONST(1000000),
@@ -369,10 +368,18 @@ AdjustTimestampForTypmod(Timestamp *time, int32 typmod)
 		&& (typmod != -1) && (typmod != MAX_TIMESTAMP_PRECISION))
 	{
 		if (typmod < 0 || typmod > MAX_TIMESTAMP_PRECISION)
+		{
+			if (error)
+			{
+				*error = true;
+				return false;
+			}
+
 			ereport(ERROR,
 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
 					 errmsg("timestamp(%d) precision must be between %d and %d",
 							typmod, 0, MAX_TIMESTAMP_PRECISION)));
+		}
 
 		if (*time >= INT64CONST(0))
 		{
@@ -385,8 +392,15 @@ AdjustTimestampForTypmod(Timestamp *time, int32 typmod)
 					  * TimestampScales[typmod]);
 		}
 	}
+
+	return true;
 }
 
+void
+AdjustTimestampForTypmod(Timestamp *time, int32 typmod)
+{
+	(void) AdjustTimestampForTypmodError(time, typmod, NULL);
+}
 
 /* timestamptz_in()
  * Convert a string to internal form.
@@ -5179,8 +5193,8 @@ timestamp_timestamptz(PG_FUNCTION_ARGS)
 	PG_RETURN_TIMESTAMPTZ(timestamp2timestamptz(timestamp));
 }
 
-static TimestampTz
-timestamp2timestamptz(Timestamp timestamp)
+TimestampTz
+timestamp2timestamptz_internal(Timestamp timestamp, int *tzp, bool *error)
 {
 	TimestampTz result;
 	struct pg_tm tt,
@@ -5189,23 +5203,30 @@ timestamp2timestamptz(Timestamp timestamp)
 	int			tz;
 
 	if (TIMESTAMP_NOT_FINITE(timestamp))
-		result = timestamp;
-	else
-	{
-		if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
-			ereport(ERROR,
-					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
-					 errmsg("timestamp out of range")));
+		return timestamp;
 
-		tz = DetermineTimeZoneOffset(tm, session_timezone);
+	if (!timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL))
+	{
+		tz = tzp ? *tzp : DetermineTimeZoneOffset(tm, session_timezone);
 
-		if (tm2timestamp(tm, fsec, &tz, &result) != 0)
-			ereport(ERROR,
-					(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
-					 errmsg("timestamp out of range")));
+		if (!tm2timestamp(tm, fsec, &tz, &result))
+			return result;
 	}
 
-	return result;
+	if (error)
+		*error = true;
+	else
+		ereport(ERROR,
+				(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
+				 errmsg("timestamp out of range")));
+
+	return 0;
+}
+
+static TimestampTz
+timestamp2timestamptz(Timestamp timestamp)
+{
+	return timestamp2timestamptz_internal(timestamp, NULL, NULL);
 }
 
 /* timestamptz_timestamp()
diff --git a/src/backend/utils/errcodes.txt b/src/backend/utils/errcodes.txt
index 16f5ca2..7287653 100644
--- a/src/backend/utils/errcodes.txt
+++ b/src/backend/utils/errcodes.txt
@@ -207,6 +207,7 @@ Section: Class 22 - Data Exception
 2200S    E    ERRCODE_INVALID_XML_COMMENT                                    invalid_xml_comment
 2200T    E    ERRCODE_INVALID_XML_PROCESSING_INSTRUCTION                     invalid_xml_processing_instruction
 22030    E    ERRCODE_DUPLICATE_JSON_OBJECT_KEY_VALUE                        duplicate_json_object_key_value
+22031    E    ERRCODE_INVALID_ARGUMENT_FOR_JSON_DATETIME_FUNCTION            invalid_argument_for_json_datetime_function
 22032    E    ERRCODE_INVALID_JSON_TEXT                                      invalid_json_text
 22033    E    ERRCODE_INVALID_JSON_SUBSCRIPT                                 invalid_json_subscript
 22034    E    ERRCODE_MORE_THAN_ONE_JSON_ITEM                                more_than_one_json_item
diff --git a/src/include/utils/date.h b/src/include/utils/date.h
index bec129a..06ebb7d 100644
--- a/src/include/utils/date.h
+++ b/src/include/utils/date.h
@@ -70,11 +70,17 @@ typedef struct
 /* date.c */
 extern int32 anytime_typmod_check(bool istz, int32 typmod);
 extern double date2timestamp_no_overflow(DateADT dateVal);
+extern Timestamp date2timestamp_internal(DateADT dateVal, bool *error);
+extern TimestampTz date2timestamptz_internal(DateADT dateVal, int *tzp,
+						  bool *error);
 extern void EncodeSpecialDate(DateADT dt, char *str);
 extern DateADT GetSQLCurrentDate(void);
 extern TimeTzADT *GetSQLCurrentTime(int32 typmod);
 extern TimeADT GetSQLLocalTime(int32 typmod);
 extern int	time2tm(TimeADT time, struct pg_tm *tm, fsec_t *fsec);
 extern int	timetz2tm(TimeTzADT *time, struct pg_tm *tm, fsec_t *fsec, int *tzp);
+extern int	tm2time(struct pg_tm *tm, fsec_t fsec, TimeADT *result);
+extern int	tm2timetz(struct pg_tm *tm, fsec_t fsec, int tz, TimeTzADT *result);
+extern void AdjustTimeForTypmod(TimeADT *time, int32 typmod);
 
 #endif							/* DATE_H */
diff --git a/src/include/utils/datetime.h b/src/include/utils/datetime.h
index 87f819e..7217312 100644
--- a/src/include/utils/datetime.h
+++ b/src/include/utils/datetime.h
@@ -338,4 +338,8 @@ extern TimeZoneAbbrevTable *ConvertTimeZoneAbbrevs(struct tzEntry *abbrevs,
 					   int n);
 extern void InstallTimeZoneAbbrevs(TimeZoneAbbrevTable *tbl);
 
+extern void AdjustTimestampForTypmod(Timestamp *time, int32 typmod);
+extern bool AdjustTimestampForTypmodError(Timestamp *time, int32 typmod,
+							  bool *error);
+
 #endif							/* DATETIME_H */
diff --git a/src/include/utils/formatting.h b/src/include/utils/formatting.h
index 5b275dc..c9efdd1 100644
--- a/src/include/utils/formatting.h
+++ b/src/include/utils/formatting.h
@@ -28,4 +28,7 @@ extern char *asc_tolower(const char *buff, size_t nbytes);
 extern char *asc_toupper(const char *buff, size_t nbytes);
 extern char *asc_initcap(const char *buff, size_t nbytes);
 
+extern Datum parse_datetime(text *date_txt, text *fmt_txt, char *tzname,
+			   bool strict, Oid *typid, int32 *typmod, int *tz, bool *error);
+
 #endif
diff --git a/src/include/utils/jsonapi.h b/src/include/utils/jsonapi.h
index b9993a9..9eda9a3 100644
--- a/src/include/utils/jsonapi.h
+++ b/src/include/utils/jsonapi.h
@@ -161,6 +161,7 @@ extern Jsonb *transform_jsonb_string_values(Jsonb *jsonb, void *action_state,
 extern text *transform_json_string_values(text *json, void *action_state,
 							 JsonTransformStringValuesAction transform_action);
 
-extern char *JsonEncodeDateTime(char *buf, Datum value, Oid typid);
+extern char *JsonEncodeDateTime(char *buf, Datum value, Oid typid,
+				   const int *tzp);
 
 #endif							/* JSONAPI_H */
diff --git a/src/include/utils/jsonb.h b/src/include/utils/jsonb.h
index ec0355f..9698c46 100644
--- a/src/include/utils/jsonb.h
+++ b/src/include/utils/jsonb.h
@@ -238,7 +238,15 @@ enum jbvType
 	jbvArray = 0x10,
 	jbvObject,
 	/* Binary (i.e. struct Jsonb) jbvArray/jbvObject */
-	jbvBinary
+	jbvBinary,
+
+	/*
+	 * Virtual types.
+	 *
+	 * These types are used only for in-memory JSON processing and serialized
+	 * into JSON strings when outputted to json/jsonb.
+	 */
+	jbvDatetime = 0x20,
 };
 
 /*
@@ -279,11 +287,20 @@ struct JsonbValue
 			int			len;
 			JsonbContainer *data;
 		}			binary;		/* Array or object, in on-disk format */
+
+		struct
+		{
+			Datum		value;
+			Oid			typid;
+			int32		typmod;
+			int			tz;
+		}			datetime;
 	}			val;
 };
 
-#define IsAJsonbScalar(jsonbval)	((jsonbval)->type >= jbvNull && \
-									 (jsonbval)->type <= jbvBool)
+#define IsAJsonbScalar(jsonbval)	(((jsonbval)->type >= jbvNull && \
+									  (jsonbval)->type <= jbvBool) || \
+									  (jsonbval)->type == jbvDatetime)
 
 /*
  * Key/value pair within an Object.
diff --git a/src/include/utils/jsonpath.h b/src/include/utils/jsonpath.h
index 14f837e..2170a70 100644
--- a/src/include/utils/jsonpath.h
+++ b/src/include/utils/jsonpath.h
@@ -77,6 +77,7 @@ typedef enum JsonPathItemType
 	jpiFloor,					/* .floor() item method */
 	jpiCeiling,					/* .ceiling() item method */
 	jpiDouble,					/* .double() item method */
+	jpiDatetime,				/* .datetime() item method */
 	jpiKeyValue,				/* .keyvalue() item method */
 	jpiSubscript,				/* array subscript: 'expr' or 'expr TO expr' */
 	jpiLast,					/* LAST array subscript */
diff --git a/src/include/utils/timestamp.h b/src/include/utils/timestamp.h
index aeb89dc..8ae8e8f 100644
--- a/src/include/utils/timestamp.h
+++ b/src/include/utils/timestamp.h
@@ -97,6 +97,9 @@ extern int	timestamp_cmp_internal(Timestamp dt1, Timestamp dt2);
 /* timestamp comparison works for timestamptz also */
 #define timestamptz_cmp_internal(dt1,dt2)	timestamp_cmp_internal(dt1, dt2)
 
+extern TimestampTz timestamp2timestamptz_internal(Timestamp timestamp,
+							   int *tzp, bool *error);
+
 extern int	isoweek2j(int year, int week);
 extern void isoweek2date(int woy, int *year, int *mon, int *mday);
 extern void isoweekdate2date(int isoweek, int wday, int *year, int *mon, int *mday);
diff --git a/src/test/regress/expected/horology.out b/src/test/regress/expected/horology.out
index b2b4577..74ecb7c 100644
--- a/src/test/regress/expected/horology.out
+++ b/src/test/regress/expected/horology.out
@@ -2786,6 +2786,85 @@ SELECT to_timestamp('2011-12-18 11:38 20',     'YYYY-MM-DD HH12:MI TZM');
  Sun Dec 18 03:18:00 2011 PST
 (1 row)
 
+SELECT i, to_timestamp('2018-11-02 12:34:56', 'YYYY-MM-DD HH24:MI:SS.FF' || i) FROM generate_series(1, 6) i;
+ i |         to_timestamp         
+---+------------------------------
+ 1 | Fri Nov 02 12:34:56 2018 PDT
+ 2 | Fri Nov 02 12:34:56 2018 PDT
+ 3 | Fri Nov 02 12:34:56 2018 PDT
+ 4 | Fri Nov 02 12:34:56 2018 PDT
+ 5 | Fri Nov 02 12:34:56 2018 PDT
+ 6 | Fri Nov 02 12:34:56 2018 PDT
+(6 rows)
+
+SELECT i, to_timestamp('2018-11-02 12:34:56.1', 'YYYY-MM-DD HH24:MI:SS.FF' || i) FROM generate_series(1, 6) i;
+ i |          to_timestamp          
+---+--------------------------------
+ 1 | Fri Nov 02 12:34:56.1 2018 PDT
+ 2 | Fri Nov 02 12:34:56.1 2018 PDT
+ 3 | Fri Nov 02 12:34:56.1 2018 PDT
+ 4 | Fri Nov 02 12:34:56.1 2018 PDT
+ 5 | Fri Nov 02 12:34:56.1 2018 PDT
+ 6 | Fri Nov 02 12:34:56.1 2018 PDT
+(6 rows)
+
+SELECT i, to_timestamp('2018-11-02 12:34:56.12', 'YYYY-MM-DD HH24:MI:SS.FF' || i) FROM generate_series(1, 6) i;
+ i |          to_timestamp           
+---+---------------------------------
+ 1 | Fri Nov 02 12:34:56.1 2018 PDT
+ 2 | Fri Nov 02 12:34:56.12 2018 PDT
+ 3 | Fri Nov 02 12:34:56.12 2018 PDT
+ 4 | Fri Nov 02 12:34:56.12 2018 PDT
+ 5 | Fri Nov 02 12:34:56.12 2018 PDT
+ 6 | Fri Nov 02 12:34:56.12 2018 PDT
+(6 rows)
+
+SELECT i, to_timestamp('2018-11-02 12:34:56.123', 'YYYY-MM-DD HH24:MI:SS.FF' || i) FROM generate_series(1, 6) i;
+ i |           to_timestamp           
+---+----------------------------------
+ 1 | Fri Nov 02 12:34:56.1 2018 PDT
+ 2 | Fri Nov 02 12:34:56.12 2018 PDT
+ 3 | Fri Nov 02 12:34:56.123 2018 PDT
+ 4 | Fri Nov 02 12:34:56.123 2018 PDT
+ 5 | Fri Nov 02 12:34:56.123 2018 PDT
+ 6 | Fri Nov 02 12:34:56.123 2018 PDT
+(6 rows)
+
+SELECT i, to_timestamp('2018-11-02 12:34:56.1234', 'YYYY-MM-DD HH24:MI:SS.FF' || i) FROM generate_series(1, 6) i;
+ i |           to_timestamp            
+---+-----------------------------------
+ 1 | Fri Nov 02 12:34:56.1 2018 PDT
+ 2 | Fri Nov 02 12:34:56.12 2018 PDT
+ 3 | Fri Nov 02 12:34:56.123 2018 PDT
+ 4 | Fri Nov 02 12:34:56.1234 2018 PDT
+ 5 | Fri Nov 02 12:34:56.1234 2018 PDT
+ 6 | Fri Nov 02 12:34:56.1234 2018 PDT
+(6 rows)
+
+SELECT i, to_timestamp('2018-11-02 12:34:56.12345', 'YYYY-MM-DD HH24:MI:SS.FF' || i) FROM generate_series(1, 6) i;
+ i |            to_timestamp            
+---+------------------------------------
+ 1 | Fri Nov 02 12:34:56.1 2018 PDT
+ 2 | Fri Nov 02 12:34:56.12 2018 PDT
+ 3 | Fri Nov 02 12:34:56.123 2018 PDT
+ 4 | Fri Nov 02 12:34:56.1235 2018 PDT
+ 5 | Fri Nov 02 12:34:56.12345 2018 PDT
+ 6 | Fri Nov 02 12:34:56.12345 2018 PDT
+(6 rows)
+
+SELECT i, to_timestamp('2018-11-02 12:34:56.123456', 'YYYY-MM-DD HH24:MI:SS.FF' || i) FROM generate_series(1, 6) i;
+ i |            to_timestamp             
+---+-------------------------------------
+ 1 | Fri Nov 02 12:34:56.1 2018 PDT
+ 2 | Fri Nov 02 12:34:56.12 2018 PDT
+ 3 | Fri Nov 02 12:34:56.123 2018 PDT
+ 4 | Fri Nov 02 12:34:56.1235 2018 PDT
+ 5 | Fri Nov 02 12:34:56.12346 2018 PDT
+ 6 | Fri Nov 02 12:34:56.123456 2018 PDT
+(6 rows)
+
+SELECT i, to_timestamp('2018-11-02 12:34:56.123456789', 'YYYY-MM-DD HH24:MI:SS.FF' || i) FROM generate_series(1, 6) i;
+ERROR:  date/time field value out of range: "2018-11-02 12:34:56.123456789"
 --
 -- Check handling of multiple spaces in format and/or input
 --
diff --git a/src/test/regress/expected/jsonb_jsonpath.out b/src/test/regress/expected/jsonb_jsonpath.out
index 2202ffa..150a138 100644
--- a/src/test/regress/expected/jsonb_jsonpath.out
+++ b/src/test/regress/expected/jsonb_jsonpath.out
@@ -1468,6 +1468,541 @@ select jsonb_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "adc\nabc", "
  "abdacb"
 (2 rows)
 
+select jsonb_path_query('null', '$.datetime()');
+ERROR:  invalid argument for SQL/JSON datetime function
+DETAIL:  jsonpath item method .datetime() is applied to not a string
+select jsonb_path_query('true', '$.datetime()');
+ERROR:  invalid argument for SQL/JSON datetime function
+DETAIL:  jsonpath item method .datetime() is applied to not a string
+select jsonb_path_query('1', '$.datetime()');
+ERROR:  invalid argument for SQL/JSON datetime function
+DETAIL:  jsonpath item method .datetime() is applied to not a string
+select jsonb_path_query('[]', '$.datetime()');
+ jsonb_path_query 
+------------------
+(0 rows)
+
+select jsonb_path_query('[]', 'strict $.datetime()');
+ERROR:  invalid argument for SQL/JSON datetime function
+DETAIL:  jsonpath item method .datetime() is applied to not a string
+select jsonb_path_query('{}', '$.datetime()');
+ERROR:  invalid argument for SQL/JSON datetime function
+DETAIL:  jsonpath item method .datetime() is applied to not a string
+select jsonb_path_query('""', '$.datetime()');
+ERROR:  invalid argument for SQL/JSON datetime function
+DETAIL:  unrecognized datetime format
+HINT:  use datetime template argument for explicit format specification
+select jsonb_path_query('"12:34"', '$.datetime("aaa")');
+ERROR:  datetime format is not dated and not timed
+select jsonb_path_query('"12:34"', '$.datetime("aaa", 1)');
+ERROR:  datetime format is not dated and not timed
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH", 1)');
+  jsonb_path_query   
+---------------------
+ "12:34:00+00:00:01"
+(1 row)
+
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH", 10000000000000)');
+ERROR:  invalid argument for SQL/JSON datetime function
+DETAIL:  timezone argument of jsonpath item method .datetime() is out of integer range
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH", 10000000000000)');
+ERROR:  invalid argument for SQL/JSON datetime function
+DETAIL:  timezone argument of jsonpath item method .datetime() is out of integer range
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH", 2147483647)');
+    jsonb_path_query     
+-------------------------
+ "12:34:00+596523:14:07"
+(1 row)
+
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH", 2147483648)');
+ERROR:  invalid argument for SQL/JSON datetime function
+DETAIL:  timezone argument of jsonpath item method .datetime() is out of integer range
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH", -2147483647)');
+    jsonb_path_query     
+-------------------------
+ "12:34:00-596523:14:07"
+(1 row)
+
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH", -2147483648)');
+ERROR:  invalid argument for SQL/JSON datetime function
+DETAIL:  timezone argument of jsonpath item method .datetime() is out of integer range
+select jsonb_path_query('"aaaa"', '$.datetime("HH24")');
+ERROR:  invalid value "aa" for "HH24"
+DETAIL:  Value must be an integer.
+select jsonb '"10-03-2017"' @? '$.datetime("dd-mm-yyyy")';
+ ?column? 
+----------
+ t
+(1 row)
+
+select jsonb_path_query('"10-03-2017"', '$.datetime("dd-mm-yyyy")');
+ jsonb_path_query 
+------------------
+ "2017-03-10"
+(1 row)
+
+select jsonb_path_query('"10-03-2017"', '$.datetime("dd-mm-yyyy").type()');
+ jsonb_path_query 
+------------------
+ "date"
+(1 row)
+
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy")');
+ jsonb_path_query 
+------------------
+ "2017-03-10"
+(1 row)
+
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy").type()');
+ jsonb_path_query 
+------------------
+ "date"
+(1 row)
+
+select jsonb_path_query('"10-03-2017 12:34"', '       $.datetime("dd-mm-yyyy HH24:MI").type()');
+       jsonb_path_query        
+-------------------------------
+ "timestamp without time zone"
+(1 row)
+
+select jsonb_path_query('"10-03-2017 12:34 +05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM").type()');
+      jsonb_path_query      
+----------------------------
+ "timestamp with time zone"
+(1 row)
+
+select jsonb_path_query('"12:34:56"', '$.datetime("HH24:MI:SS").type()');
+     jsonb_path_query     
+--------------------------
+ "time without time zone"
+(1 row)
+
+select jsonb_path_query('"12:34:56 +05:20"', '$.datetime("HH24:MI:SS TZH:TZM").type()');
+   jsonb_path_query    
+-----------------------
+ "time with time zone"
+(1 row)
+
+set time zone '+00';
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI")');
+   jsonb_path_query    
+-----------------------
+ "2017-03-10T12:34:00"
+(1 row)
+
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+ERROR:  missing time-zone in input string for type timestamptz
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", "+00")');
+      jsonb_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+00:00"
+(1 row)
+
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", "+00:12")');
+      jsonb_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+00:12"
+(1 row)
+
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", "-00:12:34")');
+        jsonb_path_query        
+--------------------------------
+ "2017-03-10T12:34:00-00:12:34"
+(1 row)
+
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", "UTC")');
+ERROR:  invalid input syntax for type timestamptz: "UTC"
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", 12 * 60)');
+      jsonb_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+00:12"
+(1 row)
+
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", -(5 * 3600 + 12 * 60 + 34))');
+        jsonb_path_query        
+--------------------------------
+ "2017-03-10T12:34:00-05:12:34"
+(1 row)
+
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", $tz)',
+                        jsonb_build_object('tz', extract(timezone from now())));
+      jsonb_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+00:00"
+(1 row)
+
+select jsonb_path_query('"10-03-2017 12:34 +05"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+      jsonb_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+05:00"
+(1 row)
+
+select jsonb_path_query('"10-03-2017 12:34 -05"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+      jsonb_path_query       
+-----------------------------
+ "2017-03-10T12:34:00-05:00"
+(1 row)
+
+select jsonb_path_query('"10-03-2017 12:34 +05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")');
+      jsonb_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+05:20"
+(1 row)
+
+select jsonb_path_query('"10-03-2017 12:34 -05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")');
+      jsonb_path_query       
+-----------------------------
+ "2017-03-10T12:34:00-05:20"
+(1 row)
+
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI")');
+ jsonb_path_query 
+------------------
+ "12:34:00"
+(1 row)
+
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH")');
+ERROR:  missing time-zone in input string for type timetz
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH", "+00")');
+ jsonb_path_query 
+------------------
+ "12:34:00+00:00"
+(1 row)
+
+select jsonb_path_query('"12:34 +05"', '$.datetime("HH24:MI TZH")');
+ jsonb_path_query 
+------------------
+ "12:34:00+05:00"
+(1 row)
+
+select jsonb_path_query('"12:34 -05"', '$.datetime("HH24:MI TZH")');
+ jsonb_path_query 
+------------------
+ "12:34:00-05:00"
+(1 row)
+
+select jsonb_path_query('"12:34 +05:20"', '$.datetime("HH24:MI TZH:TZM")');
+ jsonb_path_query 
+------------------
+ "12:34:00+05:20"
+(1 row)
+
+select jsonb_path_query('"12:34 -05:20"', '$.datetime("HH24:MI TZH:TZM")');
+ jsonb_path_query 
+------------------
+ "12:34:00-05:20"
+(1 row)
+
+set time zone '+10';
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI")');
+   jsonb_path_query    
+-----------------------
+ "2017-03-10T12:34:00"
+(1 row)
+
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+ERROR:  missing time-zone in input string for type timestamptz
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", "+10")');
+      jsonb_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+10:00"
+(1 row)
+
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", $tz)',
+                        jsonb_build_object('tz', extract(timezone from now())));
+      jsonb_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+10:00"
+(1 row)
+
+select jsonb_path_query('"10-03-2017 12:34 +05"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+      jsonb_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+05:00"
+(1 row)
+
+select jsonb_path_query('"10-03-2017 12:34 -05"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+      jsonb_path_query       
+-----------------------------
+ "2017-03-10T12:34:00-05:00"
+(1 row)
+
+select jsonb_path_query('"10-03-2017 12:34 +05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")');
+      jsonb_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+05:20"
+(1 row)
+
+select jsonb_path_query('"10-03-2017 12:34 -05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")');
+      jsonb_path_query       
+-----------------------------
+ "2017-03-10T12:34:00-05:20"
+(1 row)
+
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI")');
+ jsonb_path_query 
+------------------
+ "12:34:00"
+(1 row)
+
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH")');
+ERROR:  missing time-zone in input string for type timetz
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH", "+10")');
+ jsonb_path_query 
+------------------
+ "12:34:00+10:00"
+(1 row)
+
+select jsonb_path_query('"12:34 +05"', '$.datetime("HH24:MI TZH")');
+ jsonb_path_query 
+------------------
+ "12:34:00+05:00"
+(1 row)
+
+select jsonb_path_query('"12:34 -05"', '$.datetime("HH24:MI TZH")');
+ jsonb_path_query 
+------------------
+ "12:34:00-05:00"
+(1 row)
+
+select jsonb_path_query('"12:34 +05:20"', '$.datetime("HH24:MI TZH:TZM")');
+ jsonb_path_query 
+------------------
+ "12:34:00+05:20"
+(1 row)
+
+select jsonb_path_query('"12:34 -05:20"', '$.datetime("HH24:MI TZH:TZM")');
+ jsonb_path_query 
+------------------
+ "12:34:00-05:20"
+(1 row)
+
+set time zone default;
+select jsonb_path_query('"2017-03-10"', '$.datetime().type()');
+ jsonb_path_query 
+------------------
+ "date"
+(1 row)
+
+select jsonb_path_query('"2017-03-10"', '$.datetime()');
+ jsonb_path_query 
+------------------
+ "2017-03-10"
+(1 row)
+
+select jsonb_path_query('"2017-03-10 12:34:56"', '$.datetime().type()');
+       jsonb_path_query        
+-------------------------------
+ "timestamp without time zone"
+(1 row)
+
+select jsonb_path_query('"2017-03-10 12:34:56"', '$.datetime()');
+   jsonb_path_query    
+-----------------------
+ "2017-03-10T12:34:56"
+(1 row)
+
+select jsonb_path_query('"2017-03-10 12:34:56 +3"', '$.datetime().type()');
+      jsonb_path_query      
+----------------------------
+ "timestamp with time zone"
+(1 row)
+
+select jsonb_path_query('"2017-03-10 12:34:56 +3"', '$.datetime()');
+      jsonb_path_query       
+-----------------------------
+ "2017-03-10T12:34:56+03:00"
+(1 row)
+
+select jsonb_path_query('"2017-03-10 12:34:56 +3:10"', '$.datetime().type()');
+      jsonb_path_query      
+----------------------------
+ "timestamp with time zone"
+(1 row)
+
+select jsonb_path_query('"2017-03-10 12:34:56 +3:10"', '$.datetime()');
+      jsonb_path_query       
+-----------------------------
+ "2017-03-10T12:34:56+03:10"
+(1 row)
+
+select jsonb_path_query('"12:34:56"', '$.datetime().type()');
+     jsonb_path_query     
+--------------------------
+ "time without time zone"
+(1 row)
+
+select jsonb_path_query('"12:34:56"', '$.datetime()');
+ jsonb_path_query 
+------------------
+ "12:34:56"
+(1 row)
+
+select jsonb_path_query('"12:34:56 +3"', '$.datetime().type()');
+   jsonb_path_query    
+-----------------------
+ "time with time zone"
+(1 row)
+
+select jsonb_path_query('"12:34:56 +3"', '$.datetime()');
+ jsonb_path_query 
+------------------
+ "12:34:56+03:00"
+(1 row)
+
+select jsonb_path_query('"12:34:56 +3:10"', '$.datetime().type()');
+   jsonb_path_query    
+-----------------------
+ "time with time zone"
+(1 row)
+
+select jsonb_path_query('"12:34:56 +3:10"', '$.datetime()');
+ jsonb_path_query 
+------------------
+ "12:34:56+03:10"
+(1 row)
+
+set time zone '+00';
+-- date comparison
+select jsonb_path_query(
+	'["2017-03-10", "2017-03-11", "2017-03-09", "12:34:56", "01:02:03 +04", "2017-03-10 00:00:00", "2017-03-10 12:34:56", "2017-03-10 01:02:03 +04", "2017-03-10 03:00:00 +03"]',
+	'$[*].datetime() ? (@ == "10.03.2017".datetime("dd.mm.yyyy"))');
+   jsonb_path_query    
+-----------------------
+ "2017-03-10"
+ "2017-03-10T00:00:00"
+(2 rows)
+
+select jsonb_path_query(
+	'["2017-03-10", "2017-03-11", "2017-03-09", "12:34:56", "01:02:03 +04", "2017-03-10 00:00:00", "2017-03-10 12:34:56", "2017-03-10 01:02:03 +04", "2017-03-10 03:00:00 +03"]',
+	'$[*].datetime() ? (@ >= "10.03.2017".datetime("dd.mm.yyyy"))');
+   jsonb_path_query    
+-----------------------
+ "2017-03-10"
+ "2017-03-11"
+ "2017-03-10T00:00:00"
+ "2017-03-10T12:34:56"
+(4 rows)
+
+select jsonb_path_query(
+	'["2017-03-10", "2017-03-11", "2017-03-09", "12:34:56", "01:02:03 +04", "2017-03-10 00:00:00", "2017-03-10 12:34:56", "2017-03-10 01:02:03 +04", "2017-03-10 03:00:00 +03"]',
+	'$[*].datetime() ? (@ <  "10.03.2017".datetime("dd.mm.yyyy"))');
+ jsonb_path_query 
+------------------
+ "2017-03-09"
+(1 row)
+
+-- time comparison
+select jsonb_path_query(
+	'["12:34:00", "12:35:00", "12:36:00", "12:35:00 +00", "12:35:00 +01", "13:35:00 +01", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +01"]',
+	'$[*].datetime() ? (@ == "12:35".datetime("HH24:MI"))');
+ jsonb_path_query 
+------------------
+ "12:35:00"
+(1 row)
+
+select jsonb_path_query(
+	'["12:34:00", "12:35:00", "12:36:00", "12:35:00 +00", "12:35:00 +01", "13:35:00 +01", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +01"]',
+	'$[*].datetime() ? (@ >= "12:35".datetime("HH24:MI"))');
+ jsonb_path_query 
+------------------
+ "12:35:00"
+ "12:36:00"
+(2 rows)
+
+select jsonb_path_query(
+	'["12:34:00", "12:35:00", "12:36:00", "12:35:00 +00", "12:35:00 +01", "13:35:00 +01", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +01"]',
+	'$[*].datetime() ? (@ <  "12:35".datetime("HH24:MI"))');
+ jsonb_path_query 
+------------------
+ "12:34:00"
+(1 row)
+
+-- timetz comparison
+select jsonb_path_query(
+	'["12:34:00 +01", "12:35:00 +01", "12:36:00 +01", "12:35:00 +02", "12:35:00 -02", "10:35:00", "11:35:00", "12:35:00", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +1"]',
+	'$[*].datetime() ? (@ == "12:35 +1".datetime("HH24:MI TZH"))');
+ jsonb_path_query 
+------------------
+ "12:35:00+01:00"
+(1 row)
+
+select jsonb_path_query(
+	'["12:34:00 +01", "12:35:00 +01", "12:36:00 +01", "12:35:00 +02", "12:35:00 -02", "10:35:00", "11:35:00", "12:35:00", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +1"]',
+	'$[*].datetime() ? (@ >= "12:35 +1".datetime("HH24:MI TZH"))');
+ jsonb_path_query 
+------------------
+ "12:35:00+01:00"
+ "12:36:00+01:00"
+ "12:35:00-02:00"
+(3 rows)
+
+select jsonb_path_query(
+	'["12:34:00 +01", "12:35:00 +01", "12:36:00 +01", "12:35:00 +02", "12:35:00 -02", "10:35:00", "11:35:00", "12:35:00", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +1"]',
+	'$[*].datetime() ? (@ <  "12:35 +1".datetime("HH24:MI TZH"))');
+ jsonb_path_query 
+------------------
+ "12:34:00+01:00"
+ "12:35:00+02:00"
+(2 rows)
+
+-- timestamp comparison
+select jsonb_path_query(
+	'["2017-03-10 12:34:00", "2017-03-10 12:35:00", "2017-03-10 12:36:00", "2017-03-10 12:35:00 +01", "2017-03-10 13:35:00 +01", "2017-03-10 12:35:00 -01", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ == "10.03.2017 12:35".datetime("dd.mm.yyyy HH24:MI"))');
+   jsonb_path_query    
+-----------------------
+ "2017-03-10T12:35:00"
+(1 row)
+
+select jsonb_path_query(
+	'["2017-03-10 12:34:00", "2017-03-10 12:35:00", "2017-03-10 12:36:00", "2017-03-10 12:35:00 +01", "2017-03-10 13:35:00 +01", "2017-03-10 12:35:00 -01", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ >= "10.03.2017 12:35".datetime("dd.mm.yyyy HH24:MI"))');
+   jsonb_path_query    
+-----------------------
+ "2017-03-10T12:35:00"
+ "2017-03-10T12:36:00"
+ "2017-03-11"
+(3 rows)
+
+select jsonb_path_query(
+	'["2017-03-10 12:34:00", "2017-03-10 12:35:00", "2017-03-10 12:36:00", "2017-03-10 12:35:00 +01", "2017-03-10 13:35:00 +01", "2017-03-10 12:35:00 -01", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ < "10.03.2017 12:35".datetime("dd.mm.yyyy HH24:MI"))');
+   jsonb_path_query    
+-----------------------
+ "2017-03-10T12:34:00"
+ "2017-03-10"
+(2 rows)
+
+-- timestamptz comparison
+select jsonb_path_query(
+	'["2017-03-10 12:34:00 +01", "2017-03-10 12:35:00 +01", "2017-03-10 12:36:00 +01", "2017-03-10 12:35:00 +02", "2017-03-10 12:35:00 -02", "2017-03-10 10:35:00", "2017-03-10 11:35:00", "2017-03-10 12:35:00", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ == "10.03.2017 12:35 +1".datetime("dd.mm.yyyy HH24:MI TZH"))');
+      jsonb_path_query       
+-----------------------------
+ "2017-03-10T12:35:00+01:00"
+(1 row)
+
+select jsonb_path_query(
+	'["2017-03-10 12:34:00 +01", "2017-03-10 12:35:00 +01", "2017-03-10 12:36:00 +01", "2017-03-10 12:35:00 +02", "2017-03-10 12:35:00 -02", "2017-03-10 10:35:00", "2017-03-10 11:35:00", "2017-03-10 12:35:00", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ >= "10.03.2017 12:35 +1".datetime("dd.mm.yyyy HH24:MI TZH"))');
+      jsonb_path_query       
+-----------------------------
+ "2017-03-10T12:35:00+01:00"
+ "2017-03-10T12:36:00+01:00"
+ "2017-03-10T12:35:00-02:00"
+(3 rows)
+
+select jsonb_path_query(
+	'["2017-03-10 12:34:00 +01", "2017-03-10 12:35:00 +01", "2017-03-10 12:36:00 +01", "2017-03-10 12:35:00 +02", "2017-03-10 12:35:00 -02", "2017-03-10 10:35:00", "2017-03-10 11:35:00", "2017-03-10 12:35:00", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ < "10.03.2017 12:35 +1".datetime("dd.mm.yyyy HH24:MI TZH"))');
+      jsonb_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+01:00"
+ "2017-03-10T12:35:00+02:00"
+(2 rows)
+
+set time zone default;
 -- jsonpath operators
 SELECT jsonb_path_query('[{"a": 1}, {"a": 2}]', '$[*]');
  jsonb_path_query 
diff --git a/src/test/regress/expected/jsonpath.out b/src/test/regress/expected/jsonpath.out
index baaf9e3..7b94746 100644
--- a/src/test/regress/expected/jsonpath.out
+++ b/src/test/regress/expected/jsonpath.out
@@ -389,6 +389,24 @@ select '$.keyvalue().key'::jsonpath;
  $.keyvalue()."key"
 (1 row)
 
+select '$.datetime()'::jsonpath;
+   jsonpath   
+--------------
+ $.datetime()
+(1 row)
+
+select '$.datetime("datetime template")'::jsonpath;
+            jsonpath             
+---------------------------------
+ $.datetime("datetime template")
+(1 row)
+
+select '$.datetime("datetime template", "default timezone")'::jsonpath;
+                      jsonpath                       
+-----------------------------------------------------
+ $.datetime("datetime template", "default timezone")
+(1 row)
+
 select '$ ? (@ starts with "abc")'::jsonpath;
         jsonpath         
 -------------------------
diff --git a/src/test/regress/expected/timestamp.out b/src/test/regress/expected/timestamp.out
index 4a2fabd..cb3dd19 100644
--- a/src/test/regress/expected/timestamp.out
+++ b/src/test/regress/expected/timestamp.out
@@ -1597,6 +1597,21 @@ SELECT '' AS to_char_11, to_char(d1, 'FMIYYY FMIYY FMIY FMI FMIW FMIDDD FMID')
             | 2001 1 1 1 1 1 1
 (65 rows)
 
+SELECT '' AS to_char_12, to_char(d, 'FF1 FF2 FF3 FF4 FF5 FF6  ff1 ff2 ff3 ff4 ff5 ff6  MS US')
+   FROM (VALUES
+       ('2018-11-02 12:34:56'::timestamp),
+       ('2018-11-02 12:34:56.78'),
+       ('2018-11-02 12:34:56.78901'),
+       ('2018-11-02 12:34:56.78901234')
+   ) d(d);
+ to_char_12 |                              to_char                               
+------------+--------------------------------------------------------------------
+            | 0 00 000 0000 00000 000000  0 00 000 0000 00000 000000  000 000000
+            | 7 78 780 7800 78000 780000  7 78 780 7800 78000 780000  780 780000
+            | 7 78 789 7890 78901 789010  7 78 789 7890 78901 789010  789 789010
+            | 7 78 789 7890 78901 789012  7 78 789 7890 78901 789012  789 789012
+(4 rows)
+
 -- timestamp numeric fields constructor
 SELECT make_timestamp(2014,12,28,6,30,45.887);
         make_timestamp        
diff --git a/src/test/regress/expected/timestamptz.out b/src/test/regress/expected/timestamptz.out
index 8a4c719..cdd3c14 100644
--- a/src/test/regress/expected/timestamptz.out
+++ b/src/test/regress/expected/timestamptz.out
@@ -1717,6 +1717,21 @@ SELECT '' AS to_char_11, to_char(d1, 'FMIYYY FMIYY FMIY FMI FMIW FMIDDD FMID')
             | 2001 1 1 1 1 1 1
 (66 rows)
 
+SELECT '' AS to_char_12, to_char(d, 'FF1 FF2 FF3 FF4 FF5 FF6  ff1 ff2 ff3 ff4 ff5 ff6  MS US')
+   FROM (VALUES
+       ('2018-11-02 12:34:56'::timestamptz),
+       ('2018-11-02 12:34:56.78'),
+       ('2018-11-02 12:34:56.78901'),
+       ('2018-11-02 12:34:56.78901234')
+   ) d(d);
+ to_char_12 |                              to_char                               
+------------+--------------------------------------------------------------------
+            | 0 00 000 0000 00000 000000  0 00 000 0000 00000 000000  000 000000
+            | 7 78 780 7800 78000 780000  7 78 780 7800 78000 780000  780 780000
+            | 7 78 789 7890 78901 789010  7 78 789 7890 78901 789010  789 789010
+            | 7 78 789 7890 78901 789012  7 78 789 7890 78901 789012  789 789012
+(4 rows)
+
 -- Check OF, TZH, TZM with various zone offsets, particularly fractional hours
 SET timezone = '00:00';
 SELECT to_char(now(), 'OF') as "OF", to_char(now(), 'TZH:TZM') as "TZH:TZM";
diff --git a/src/test/regress/sql/horology.sql b/src/test/regress/sql/horology.sql
index e356dd5..3c85803 100644
--- a/src/test/regress/sql/horology.sql
+++ b/src/test/regress/sql/horology.sql
@@ -402,6 +402,15 @@ SELECT to_timestamp('2011-12-18 11:38 +05:20', 'YYYY-MM-DD HH12:MI TZH:TZM');
 SELECT to_timestamp('2011-12-18 11:38 -05:20', 'YYYY-MM-DD HH12:MI TZH:TZM');
 SELECT to_timestamp('2011-12-18 11:38 20',     'YYYY-MM-DD HH12:MI TZM');
 
+SELECT i, to_timestamp('2018-11-02 12:34:56', 'YYYY-MM-DD HH24:MI:SS.FF' || i) FROM generate_series(1, 6) i;
+SELECT i, to_timestamp('2018-11-02 12:34:56.1', 'YYYY-MM-DD HH24:MI:SS.FF' || i) FROM generate_series(1, 6) i;
+SELECT i, to_timestamp('2018-11-02 12:34:56.12', 'YYYY-MM-DD HH24:MI:SS.FF' || i) FROM generate_series(1, 6) i;
+SELECT i, to_timestamp('2018-11-02 12:34:56.123', 'YYYY-MM-DD HH24:MI:SS.FF' || i) FROM generate_series(1, 6) i;
+SELECT i, to_timestamp('2018-11-02 12:34:56.1234', 'YYYY-MM-DD HH24:MI:SS.FF' || i) FROM generate_series(1, 6) i;
+SELECT i, to_timestamp('2018-11-02 12:34:56.12345', 'YYYY-MM-DD HH24:MI:SS.FF' || i) FROM generate_series(1, 6) i;
+SELECT i, to_timestamp('2018-11-02 12:34:56.123456', 'YYYY-MM-DD HH24:MI:SS.FF' || i) FROM generate_series(1, 6) i;
+SELECT i, to_timestamp('2018-11-02 12:34:56.123456789', 'YYYY-MM-DD HH24:MI:SS.FF' || i) FROM generate_series(1, 6) i;
+
 --
 -- Check handling of multiple spaces in format and/or input
 --
diff --git a/src/test/regress/sql/jsonb_jsonpath.sql b/src/test/regress/sql/jsonb_jsonpath.sql
index bb5f97b..7245250 100644
--- a/src/test/regress/sql/jsonb_jsonpath.sql
+++ b/src/test/regress/sql/jsonb_jsonpath.sql
@@ -301,6 +301,154 @@ select jsonb_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "adc\nabc", "
 select jsonb_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "adc\nabc", "babc"]', 'lax $[*] ? (@ like_regex "^ab.*c" flag "m")');
 select jsonb_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "adc\nabc", "babc"]', 'lax $[*] ? (@ like_regex "^ab.*c" flag "s")');
 
+select jsonb_path_query('null', '$.datetime()');
+select jsonb_path_query('true', '$.datetime()');
+select jsonb_path_query('1', '$.datetime()');
+select jsonb_path_query('[]', '$.datetime()');
+select jsonb_path_query('[]', 'strict $.datetime()');
+select jsonb_path_query('{}', '$.datetime()');
+select jsonb_path_query('""', '$.datetime()');
+select jsonb_path_query('"12:34"', '$.datetime("aaa")');
+select jsonb_path_query('"12:34"', '$.datetime("aaa", 1)');
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH", 1)');
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH", 10000000000000)');
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH", 10000000000000)');
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH", 2147483647)');
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH", 2147483648)');
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH", -2147483647)');
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH", -2147483648)');
+select jsonb_path_query('"aaaa"', '$.datetime("HH24")');
+
+select jsonb '"10-03-2017"' @? '$.datetime("dd-mm-yyyy")';
+select jsonb_path_query('"10-03-2017"', '$.datetime("dd-mm-yyyy")');
+select jsonb_path_query('"10-03-2017"', '$.datetime("dd-mm-yyyy").type()');
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy")');
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy").type()');
+
+select jsonb_path_query('"10-03-2017 12:34"', '       $.datetime("dd-mm-yyyy HH24:MI").type()');
+select jsonb_path_query('"10-03-2017 12:34 +05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM").type()');
+select jsonb_path_query('"12:34:56"', '$.datetime("HH24:MI:SS").type()');
+select jsonb_path_query('"12:34:56 +05:20"', '$.datetime("HH24:MI:SS TZH:TZM").type()');
+
+set time zone '+00';
+
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI")');
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", "+00")');
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", "+00:12")');
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", "-00:12:34")');
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", "UTC")');
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", 12 * 60)');
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", -(5 * 3600 + 12 * 60 + 34))');
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", $tz)',
+                        jsonb_build_object('tz', extract(timezone from now())));
+select jsonb_path_query('"10-03-2017 12:34 +05"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+select jsonb_path_query('"10-03-2017 12:34 -05"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+select jsonb_path_query('"10-03-2017 12:34 +05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")');
+select jsonb_path_query('"10-03-2017 12:34 -05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")');
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI")');
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH")');
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH", "+00")');
+select jsonb_path_query('"12:34 +05"', '$.datetime("HH24:MI TZH")');
+select jsonb_path_query('"12:34 -05"', '$.datetime("HH24:MI TZH")');
+select jsonb_path_query('"12:34 +05:20"', '$.datetime("HH24:MI TZH:TZM")');
+select jsonb_path_query('"12:34 -05:20"', '$.datetime("HH24:MI TZH:TZM")');
+
+set time zone '+10';
+
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI")');
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", "+10")');
+select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", $tz)',
+                        jsonb_build_object('tz', extract(timezone from now())));
+select jsonb_path_query('"10-03-2017 12:34 +05"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+select jsonb_path_query('"10-03-2017 12:34 -05"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+select jsonb_path_query('"10-03-2017 12:34 +05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")');
+select jsonb_path_query('"10-03-2017 12:34 -05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")');
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI")');
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH")');
+select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH", "+10")');
+select jsonb_path_query('"12:34 +05"', '$.datetime("HH24:MI TZH")');
+select jsonb_path_query('"12:34 -05"', '$.datetime("HH24:MI TZH")');
+select jsonb_path_query('"12:34 +05:20"', '$.datetime("HH24:MI TZH:TZM")');
+select jsonb_path_query('"12:34 -05:20"', '$.datetime("HH24:MI TZH:TZM")');
+
+set time zone default;
+
+select jsonb_path_query('"2017-03-10"', '$.datetime().type()');
+select jsonb_path_query('"2017-03-10"', '$.datetime()');
+select jsonb_path_query('"2017-03-10 12:34:56"', '$.datetime().type()');
+select jsonb_path_query('"2017-03-10 12:34:56"', '$.datetime()');
+select jsonb_path_query('"2017-03-10 12:34:56 +3"', '$.datetime().type()');
+select jsonb_path_query('"2017-03-10 12:34:56 +3"', '$.datetime()');
+select jsonb_path_query('"2017-03-10 12:34:56 +3:10"', '$.datetime().type()');
+select jsonb_path_query('"2017-03-10 12:34:56 +3:10"', '$.datetime()');
+select jsonb_path_query('"12:34:56"', '$.datetime().type()');
+select jsonb_path_query('"12:34:56"', '$.datetime()');
+select jsonb_path_query('"12:34:56 +3"', '$.datetime().type()');
+select jsonb_path_query('"12:34:56 +3"', '$.datetime()');
+select jsonb_path_query('"12:34:56 +3:10"', '$.datetime().type()');
+select jsonb_path_query('"12:34:56 +3:10"', '$.datetime()');
+
+set time zone '+00';
+
+-- date comparison
+select jsonb_path_query(
+	'["2017-03-10", "2017-03-11", "2017-03-09", "12:34:56", "01:02:03 +04", "2017-03-10 00:00:00", "2017-03-10 12:34:56", "2017-03-10 01:02:03 +04", "2017-03-10 03:00:00 +03"]',
+	'$[*].datetime() ? (@ == "10.03.2017".datetime("dd.mm.yyyy"))');
+select jsonb_path_query(
+	'["2017-03-10", "2017-03-11", "2017-03-09", "12:34:56", "01:02:03 +04", "2017-03-10 00:00:00", "2017-03-10 12:34:56", "2017-03-10 01:02:03 +04", "2017-03-10 03:00:00 +03"]',
+	'$[*].datetime() ? (@ >= "10.03.2017".datetime("dd.mm.yyyy"))');
+select jsonb_path_query(
+	'["2017-03-10", "2017-03-11", "2017-03-09", "12:34:56", "01:02:03 +04", "2017-03-10 00:00:00", "2017-03-10 12:34:56", "2017-03-10 01:02:03 +04", "2017-03-10 03:00:00 +03"]',
+	'$[*].datetime() ? (@ <  "10.03.2017".datetime("dd.mm.yyyy"))');
+
+-- time comparison
+select jsonb_path_query(
+	'["12:34:00", "12:35:00", "12:36:00", "12:35:00 +00", "12:35:00 +01", "13:35:00 +01", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +01"]',
+	'$[*].datetime() ? (@ == "12:35".datetime("HH24:MI"))');
+select jsonb_path_query(
+	'["12:34:00", "12:35:00", "12:36:00", "12:35:00 +00", "12:35:00 +01", "13:35:00 +01", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +01"]',
+	'$[*].datetime() ? (@ >= "12:35".datetime("HH24:MI"))');
+select jsonb_path_query(
+	'["12:34:00", "12:35:00", "12:36:00", "12:35:00 +00", "12:35:00 +01", "13:35:00 +01", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +01"]',
+	'$[*].datetime() ? (@ <  "12:35".datetime("HH24:MI"))');
+
+-- timetz comparison
+select jsonb_path_query(
+	'["12:34:00 +01", "12:35:00 +01", "12:36:00 +01", "12:35:00 +02", "12:35:00 -02", "10:35:00", "11:35:00", "12:35:00", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +1"]',
+	'$[*].datetime() ? (@ == "12:35 +1".datetime("HH24:MI TZH"))');
+select jsonb_path_query(
+	'["12:34:00 +01", "12:35:00 +01", "12:36:00 +01", "12:35:00 +02", "12:35:00 -02", "10:35:00", "11:35:00", "12:35:00", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +1"]',
+	'$[*].datetime() ? (@ >= "12:35 +1".datetime("HH24:MI TZH"))');
+select jsonb_path_query(
+	'["12:34:00 +01", "12:35:00 +01", "12:36:00 +01", "12:35:00 +02", "12:35:00 -02", "10:35:00", "11:35:00", "12:35:00", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +1"]',
+	'$[*].datetime() ? (@ <  "12:35 +1".datetime("HH24:MI TZH"))');
+
+-- timestamp comparison
+select jsonb_path_query(
+	'["2017-03-10 12:34:00", "2017-03-10 12:35:00", "2017-03-10 12:36:00", "2017-03-10 12:35:00 +01", "2017-03-10 13:35:00 +01", "2017-03-10 12:35:00 -01", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ == "10.03.2017 12:35".datetime("dd.mm.yyyy HH24:MI"))');
+select jsonb_path_query(
+	'["2017-03-10 12:34:00", "2017-03-10 12:35:00", "2017-03-10 12:36:00", "2017-03-10 12:35:00 +01", "2017-03-10 13:35:00 +01", "2017-03-10 12:35:00 -01", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ >= "10.03.2017 12:35".datetime("dd.mm.yyyy HH24:MI"))');
+select jsonb_path_query(
+	'["2017-03-10 12:34:00", "2017-03-10 12:35:00", "2017-03-10 12:36:00", "2017-03-10 12:35:00 +01", "2017-03-10 13:35:00 +01", "2017-03-10 12:35:00 -01", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ < "10.03.2017 12:35".datetime("dd.mm.yyyy HH24:MI"))');
+
+-- timestamptz comparison
+select jsonb_path_query(
+	'["2017-03-10 12:34:00 +01", "2017-03-10 12:35:00 +01", "2017-03-10 12:36:00 +01", "2017-03-10 12:35:00 +02", "2017-03-10 12:35:00 -02", "2017-03-10 10:35:00", "2017-03-10 11:35:00", "2017-03-10 12:35:00", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ == "10.03.2017 12:35 +1".datetime("dd.mm.yyyy HH24:MI TZH"))');
+select jsonb_path_query(
+	'["2017-03-10 12:34:00 +01", "2017-03-10 12:35:00 +01", "2017-03-10 12:36:00 +01", "2017-03-10 12:35:00 +02", "2017-03-10 12:35:00 -02", "2017-03-10 10:35:00", "2017-03-10 11:35:00", "2017-03-10 12:35:00", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ >= "10.03.2017 12:35 +1".datetime("dd.mm.yyyy HH24:MI TZH"))');
+select jsonb_path_query(
+	'["2017-03-10 12:34:00 +01", "2017-03-10 12:35:00 +01", "2017-03-10 12:36:00 +01", "2017-03-10 12:35:00 +02", "2017-03-10 12:35:00 -02", "2017-03-10 10:35:00", "2017-03-10 11:35:00", "2017-03-10 12:35:00", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ < "10.03.2017 12:35 +1".datetime("dd.mm.yyyy HH24:MI TZH"))');
+
+set time zone default;
+
 -- jsonpath operators
 
 SELECT jsonb_path_query('[{"a": 1}, {"a": 2}]', '$[*]');
diff --git a/src/test/regress/sql/jsonpath.sql b/src/test/regress/sql/jsonpath.sql
index e5f3391..288da17 100644
--- a/src/test/regress/sql/jsonpath.sql
+++ b/src/test/regress/sql/jsonpath.sql
@@ -70,6 +70,9 @@ select '"aaa".type()'::jsonpath;
 select 'true.type()'::jsonpath;
 select '$.double().floor().ceiling().abs()'::jsonpath;
 select '$.keyvalue().key'::jsonpath;
+select '$.datetime()'::jsonpath;
+select '$.datetime("datetime template")'::jsonpath;
+select '$.datetime("datetime template", "default timezone")'::jsonpath;
 
 select '$ ? (@ starts with "abc")'::jsonpath;
 select '$ ? (@ starts with $var)'::jsonpath;
diff --git a/src/test/regress/sql/timestamp.sql b/src/test/regress/sql/timestamp.sql
index b7957cb..fea4255 100644
--- a/src/test/regress/sql/timestamp.sql
+++ b/src/test/regress/sql/timestamp.sql
@@ -228,5 +228,13 @@ SELECT '' AS to_char_10, to_char(d1, 'IYYY IYY IY I IW IDDD ID')
 SELECT '' AS to_char_11, to_char(d1, 'FMIYYY FMIYY FMIY FMI FMIW FMIDDD FMID')
    FROM TIMESTAMP_TBL;
 
+SELECT '' AS to_char_12, to_char(d, 'FF1 FF2 FF3 FF4 FF5 FF6  ff1 ff2 ff3 ff4 ff5 ff6  MS US')
+   FROM (VALUES
+       ('2018-11-02 12:34:56'::timestamp),
+       ('2018-11-02 12:34:56.78'),
+       ('2018-11-02 12:34:56.78901'),
+       ('2018-11-02 12:34:56.78901234')
+   ) d(d);
+
 -- timestamp numeric fields constructor
 SELECT make_timestamp(2014,12,28,6,30,45.887);
diff --git a/src/test/regress/sql/timestamptz.sql b/src/test/regress/sql/timestamptz.sql
index c3bd46c..588c3e0 100644
--- a/src/test/regress/sql/timestamptz.sql
+++ b/src/test/regress/sql/timestamptz.sql
@@ -252,6 +252,14 @@ SELECT '' AS to_char_10, to_char(d1, 'IYYY IYY IY I IW IDDD ID')
 SELECT '' AS to_char_11, to_char(d1, 'FMIYYY FMIYY FMIY FMI FMIW FMIDDD FMID')
    FROM TIMESTAMPTZ_TBL;
 
+SELECT '' AS to_char_12, to_char(d, 'FF1 FF2 FF3 FF4 FF5 FF6  ff1 ff2 ff3 ff4 ff5 ff6  MS US')
+   FROM (VALUES
+       ('2018-11-02 12:34:56'::timestamptz),
+       ('2018-11-02 12:34:56.78'),
+       ('2018-11-02 12:34:56.78901'),
+       ('2018-11-02 12:34:56.78901234')
+   ) d(d);
+
 -- Check OF, TZH, TZM with various zone offsets, particularly fractional hours
 SET timezone = '00:00';
 SELECT to_char(now(), 'OF') as "OF", to_char(now(), 'TZH:TZM') as "TZH:TZM";
-- 
2.7.4

  [text/x-patch] 0004-Jsonpath-support-for-json-v34.patch (192.5K, ../a3be6a7a-77d3-0e88-4f9d-4f725d11d7cd@postgrespro.ru/6-0004-Jsonpath-support-for-json-v34.patch)
  download | inline diff:
From 121bb4d21063cfc22cae535f6978a8ef4f3f257d Mon Sep 17 00:00:00 2001
From: Nikita Glukhov <n.gluhov@postgrespro.ru>
Date: Fri, 1 Mar 2019 03:15:18 +0300
Subject: [PATCH 04/13] Jsonpath support for json

---
 src/backend/catalog/system_views.sql        |   58 +
 src/backend/utils/adt/json.c                |  855 ++++++++++-
 src/backend/utils/adt/jsonb.c               |   18 -
 src/backend/utils/adt/jsonb_util.c          |   33 +-
 src/backend/utils/adt/jsonpath_exec.c       | 1516 +++++++++++++------
 src/include/catalog/pg_operator.dat         |    8 +
 src/include/catalog/pg_proc.dat             |   34 +
 src/include/utils/jsonapi.h                 |   69 +
 src/include/utils/jsonb.h                   |   33 +-
 src/test/regress/expected/json_jsonpath.out | 2120 +++++++++++++++++++++++++++
 src/test/regress/parallel_schedule          |    2 +-
 src/test/regress/serial_schedule            |    1 +
 src/test/regress/sql/json_jsonpath.sql      |  477 ++++++
 src/tools/pgindent/typedefs.list            |    2 +
 14 files changed, 4728 insertions(+), 498 deletions(-)
 create mode 100644 src/test/regress/expected/json_jsonpath.out
 create mode 100644 src/test/regress/sql/json_jsonpath.sql

diff --git a/src/backend/catalog/system_views.sql b/src/backend/catalog/system_views.sql
index f5d11d5..5ac1fab 100644
--- a/src/backend/catalog/system_views.sql
+++ b/src/backend/catalog/system_views.sql
@@ -1167,6 +1167,64 @@ LANGUAGE INTERNAL
 STRICT IMMUTABLE PARALLEL SAFE
 AS 'jsonb_path_query_first';
 
+CREATE OR REPLACE FUNCTION
+  jsonb_path_query_first_text(target jsonb, path jsonpath, vars jsonb DEFAULT '{}',
+                              silent boolean DEFAULT false)
+RETURNS text
+LANGUAGE INTERNAL
+STRICT IMMUTABLE PARALLEL SAFE
+AS 'jsonb_path_query_first_text';
+
+
+
+CREATE OR REPLACE FUNCTION
+  json_path_exists(target json, path jsonpath, vars json DEFAULT '{}',
+                   silent boolean DEFAULT false)
+RETURNS boolean
+LANGUAGE INTERNAL
+STRICT IMMUTABLE PARALLEL SAFE
+AS 'json_path_exists';
+
+CREATE OR REPLACE FUNCTION
+  json_path_match(target json, path jsonpath, vars json DEFAULT '{}',
+                  silent boolean DEFAULT false)
+RETURNS boolean
+LANGUAGE INTERNAL
+STRICT IMMUTABLE PARALLEL SAFE
+AS 'json_path_match';
+
+CREATE OR REPLACE FUNCTION
+  json_path_query(target json, path jsonpath, vars json DEFAULT '{}',
+                  silent boolean DEFAULT false)
+RETURNS SETOF json
+LANGUAGE INTERNAL
+STRICT IMMUTABLE PARALLEL SAFE
+AS 'json_path_query';
+
+CREATE OR REPLACE FUNCTION
+  json_path_query_array(target json, path jsonpath, vars json DEFAULT '{}',
+                        silent boolean DEFAULT false)
+RETURNS json
+LANGUAGE INTERNAL
+STRICT IMMUTABLE PARALLEL SAFE
+AS 'json_path_query_array';
+
+CREATE OR REPLACE FUNCTION
+  json_path_query_first(target json, path jsonpath, vars json DEFAULT '{}',
+                        silent boolean DEFAULT false)
+RETURNS json
+LANGUAGE INTERNAL
+STRICT IMMUTABLE PARALLEL SAFE
+AS 'json_path_query_first';
+
+CREATE OR REPLACE FUNCTION
+  json_path_query_first_text(target json, path jsonpath, vars json DEFAULT '{}',
+                             silent boolean DEFAULT false)
+RETURNS text
+LANGUAGE INTERNAL
+STRICT IMMUTABLE PARALLEL SAFE
+AS 'json_path_query_first_text';
+
 --
 -- The default permissions for functions mean that anyone can execute them.
 -- A number of functions shouldn't be executable by just anyone, but rather
diff --git a/src/backend/utils/adt/json.c b/src/backend/utils/adt/json.c
index 5239903..803d478 100644
--- a/src/backend/utils/adt/json.c
+++ b/src/backend/utils/adt/json.c
@@ -106,6 +106,9 @@ static void add_json(Datum val, bool is_null, StringInfo result,
 		 Oid val_type, bool key_scalar);
 static text *catenate_stringinfo_string(StringInfo buffer, const char *addon);
 
+static JsonIterator *JsonIteratorInitFromLex(JsonContainer *jc,
+						JsonLexContext *lex, JsonIterator *parent);
+
 /* the null action object used for pure validation */
 static JsonSemAction nullSemAction =
 {
@@ -127,6 +130,27 @@ lex_peek(JsonLexContext *lex)
 }
 
 /*
+ * lex_peek_value
+ *
+ * get the current look_ahead de-escaped lexeme.
+*/
+static inline char *
+lex_peek_value(JsonLexContext *lex)
+{
+	if (lex->token_type == JSON_TOKEN_STRING)
+		return lex->strval ? pstrdup(lex->strval->data) : NULL;
+	else
+	{
+		int			len = lex->token_terminator - lex->token_start;
+		char	   *tokstr = palloc(len + 1);
+
+		memcpy(tokstr, lex->token_start, len);
+		tokstr[len] = '\0';
+		return tokstr;
+	}
+}
+
+/*
  * lex_accept
  *
  * accept the look_ahead token and move the lexer to the next token if the
@@ -141,22 +165,8 @@ lex_accept(JsonLexContext *lex, JsonTokenType token, char **lexeme)
 	if (lex->token_type == token)
 	{
 		if (lexeme != NULL)
-		{
-			if (lex->token_type == JSON_TOKEN_STRING)
-			{
-				if (lex->strval != NULL)
-					*lexeme = pstrdup(lex->strval->data);
-			}
-			else
-			{
-				int			len = (lex->token_terminator - lex->token_start);
-				char	   *tokstr = palloc(len + 1);
+			*lexeme = lex_peek_value(lex);
 
-				memcpy(tokstr, lex->token_start, len);
-				tokstr[len] = '\0';
-				*lexeme = tokstr;
-			}
-		}
 		json_lex(lex);
 		return true;
 	}
@@ -2573,3 +2583,818 @@ json_typeof(PG_FUNCTION_ARGS)
 
 	PG_RETURN_TEXT_P(cstring_to_text(type));
 }
+
+/*
+ * Initialize a JsonContainer from a json text, its type and size.
+ * 'type' can be JB_FOBJECT, JB_FARRAY, (JB_FARRAY | JB_FSCALAR).
+ * 'size' is a number of elements/pairs in array/object, or -1 if unknown.
+ */
+static void
+jsonInitContainer(JsonContainerData *jc, char *json, int len, int type,
+				  int size)
+{
+	if (size < 0 || size > JB_CMASK)
+		size = JB_CMASK;	/* unknown size */
+
+	jc->data = json;
+	jc->len = len;
+	jc->header = type | size;
+}
+
+/*
+ * Initialize a JsonContainer from a text datum.
+ */
+static void
+jsonInit(JsonContainerData *jc, Datum value)
+{
+	text	   *json = DatumGetTextP(value);
+	JsonLexContext *lex = makeJsonLexContext(json, false);
+	JsonTokenType tok;
+	int			type;
+	int			size = -1;
+
+	/* Lex exactly one token from the input and check its type. */
+	json_lex(lex);
+	tok = lex_peek(lex);
+
+	switch (tok)
+	{
+		case JSON_TOKEN_OBJECT_START:
+			type = JB_FOBJECT;
+			lex_accept(lex, tok, NULL);
+			if (lex_peek(lex) == JSON_TOKEN_OBJECT_END)
+				size = 0;
+			break;
+		case JSON_TOKEN_ARRAY_START:
+			type = JB_FARRAY;
+			lex_accept(lex, tok, NULL);
+			if (lex_peek(lex) == JSON_TOKEN_ARRAY_END)
+				size = 0;
+			break;
+		case JSON_TOKEN_STRING:
+		case JSON_TOKEN_NUMBER:
+		case JSON_TOKEN_TRUE:
+		case JSON_TOKEN_FALSE:
+		case JSON_TOKEN_NULL:
+			type = JB_FARRAY | JB_FSCALAR;
+			size = 1;
+			break;
+		default:
+			elog(ERROR, "unexpected json token: %d", tok);
+			type = jbvNull;
+			break;
+	}
+
+	pfree(lex);
+
+	jsonInitContainer(jc, VARDATA(json), VARSIZE(json) - VARHDRSZ, type, size);
+}
+
+/*
+ * Wrap JSON text into a palloc()'d Json structure.
+ */
+Json *
+JsonCreate(text *json)
+{
+	Json	   *res = palloc0(sizeof(*res));
+
+	jsonInit((JsonContainerData *) &res->root, PointerGetDatum(json));
+
+	return res;
+}
+
+/*
+ * Fill JsonbValue from the current iterator token.
+ * Returns true if recursion into nested object or array is needed (in this case
+ * child iterator is created and put into *pit).
+ */
+static bool
+jsonFillValue(JsonIterator **pit, JsonbValue *res, bool skipNested,
+			  JsontIterState nextState)
+{
+	JsonIterator *it = *pit;
+	JsonLexContext *lex = it->lex;
+	JsonTokenType tok = lex_peek(lex);
+
+	switch (tok)
+	{
+		case JSON_TOKEN_NULL:
+			res->type = jbvNull;
+			break;
+
+		case JSON_TOKEN_TRUE:
+			res->type = jbvBool;
+			res->val.boolean = true;
+			break;
+
+		case JSON_TOKEN_FALSE:
+			res->type = jbvBool;
+			res->val.boolean = false;
+			break;
+
+		case JSON_TOKEN_STRING:
+		{
+			char	   *token = lex_peek_value(lex);
+			res->type = jbvString;
+			res->val.string.val = token;
+			res->val.string.len = strlen(token);
+			break;
+		}
+
+		case JSON_TOKEN_NUMBER:
+		{
+			char	   *token = lex_peek_value(lex);
+			res->type = jbvNumeric;
+			res->val.numeric = DatumGetNumeric(DirectFunctionCall3(
+					numeric_in, CStringGetDatum(token), 0, -1));
+			break;
+		}
+
+		case JSON_TOKEN_OBJECT_START:
+		case JSON_TOKEN_ARRAY_START:
+		{
+			JsonContainerData *cont = palloc(sizeof(*cont));
+			char	   *token_start = lex->token_start;
+			int			len;
+
+			if (skipNested)
+			{
+				/* find the end of a container for its length calculation */
+				if (tok == JSON_TOKEN_OBJECT_START)
+					parse_object(lex, &nullSemAction);
+				else
+					parse_array(lex, &nullSemAction);
+
+				len = lex->token_start - token_start;
+			}
+			else
+				len = lex->input_length - (lex->token_start - lex->input);
+
+			jsonInitContainer(cont,
+							  token_start, len,
+							  tok == JSON_TOKEN_OBJECT_START ?
+									JB_FOBJECT : JB_FARRAY,
+							  -1);
+
+			res->type = jbvBinary;
+			res->val.binary.data = (JsonbContainer *) cont;
+			res->val.binary.len = len;
+
+			if (skipNested)
+				return false;
+
+			/* recurse into container */
+			it->state = nextState;
+			*pit = JsonIteratorInitFromLex(cont, lex, *pit);
+			return true;
+		}
+
+		default:
+			report_parse_error(JSON_PARSE_VALUE, lex);
+	}
+
+	lex_accept(lex, tok, NULL);
+
+	return false;
+}
+
+/*
+ * Free the topmost entry in the stack of JsonIterators.
+ */
+static inline JsonIterator *
+JsonIteratorFreeAndGetParent(JsonIterator *it)
+{
+	JsonIterator *parent = it->parent;
+
+	pfree(it);
+
+	return parent;
+}
+
+/*
+ * Free the entire stack of JsonIterators.
+ */
+void
+JsonIteratorFree(JsonIterator *it)
+{
+	while (it)
+		it = JsonIteratorFreeAndGetParent(it);
+}
+
+/*
+ * Get next JsonbValue while iterating through JsonContainer.
+ *
+ * For more details, see JsonbIteratorNext().
+ */
+JsonbIteratorToken
+JsonIteratorNext(JsonIterator **pit, JsonbValue *val, bool skipNested)
+{
+	JsonIterator *it;
+
+	if (*pit == NULL)
+		return WJB_DONE;
+
+recurse:
+	it = *pit;
+
+	/* parse by recursive descent */
+	switch (it->state)
+	{
+		case JTI_ARRAY_START:
+			val->type = jbvArray;
+			val->val.array.nElems = it->isScalar ? 1 : -1;
+			val->val.array.rawScalar = it->isScalar;
+			val->val.array.elems = NULL;
+			it->state = it->isScalar ? JTI_ARRAY_ELEM_SCALAR : JTI_ARRAY_ELEM;
+			return WJB_BEGIN_ARRAY;
+
+		case JTI_ARRAY_ELEM_SCALAR:
+		{
+			(void) jsonFillValue(pit, val, skipNested, JTI_ARRAY_END);
+			it->state = JTI_ARRAY_END;
+			return WJB_ELEM;
+		}
+
+		case JTI_ARRAY_END:
+			if (!it->parent && lex_peek(it->lex) != JSON_TOKEN_END)
+				report_parse_error(JSON_PARSE_END, it->lex);
+			*pit = JsonIteratorFreeAndGetParent(*pit);
+			return WJB_END_ARRAY;
+
+		case JTI_ARRAY_ELEM:
+			if (lex_accept(it->lex, JSON_TOKEN_ARRAY_END, NULL))
+			{
+				it->state = JTI_ARRAY_END;
+				goto recurse;
+			}
+
+			if (jsonFillValue(pit, val, skipNested, JTI_ARRAY_ELEM_AFTER))
+				goto recurse;
+
+			/* fall through */
+
+		case JTI_ARRAY_ELEM_AFTER:
+			if (!lex_accept(it->lex, JSON_TOKEN_COMMA, NULL))
+			{
+				if (lex_peek(it->lex) != JSON_TOKEN_ARRAY_END)
+					report_parse_error(JSON_PARSE_ARRAY_NEXT, it->lex);
+			}
+
+			if (it->state == JTI_ARRAY_ELEM_AFTER)
+			{
+				it->state = JTI_ARRAY_ELEM;
+				goto recurse;
+			}
+
+			return WJB_ELEM;
+
+		case JTI_OBJECT_START:
+			val->type = jbvObject;
+			val->val.object.nPairs = -1;
+			val->val.object.pairs = NULL;
+			val->val.object.uniquify = false;
+			it->state = JTI_OBJECT_KEY;
+			return WJB_BEGIN_OBJECT;
+
+		case JTI_OBJECT_KEY:
+			if (lex_accept(it->lex, JSON_TOKEN_OBJECT_END, NULL))
+			{
+				if (!it->parent && lex_peek(it->lex) != JSON_TOKEN_END)
+					report_parse_error(JSON_PARSE_END, it->lex);
+				*pit = JsonIteratorFreeAndGetParent(*pit);
+				return WJB_END_OBJECT;
+			}
+
+			if (lex_peek(it->lex) != JSON_TOKEN_STRING)
+				report_parse_error(JSON_PARSE_OBJECT_START, it->lex);
+
+			(void) jsonFillValue(pit, val, true, JTI_OBJECT_VALUE);
+
+			if (!lex_accept(it->lex, JSON_TOKEN_COLON, NULL))
+				report_parse_error(JSON_PARSE_OBJECT_LABEL, it->lex);
+
+			it->state = JTI_OBJECT_VALUE;
+			return WJB_KEY;
+
+		case JTI_OBJECT_VALUE:
+			if (jsonFillValue(pit, val, skipNested, JTI_OBJECT_VALUE_AFTER))
+				goto recurse;
+
+			/* fall through */
+
+		case JTI_OBJECT_VALUE_AFTER:
+			if (!lex_accept(it->lex, JSON_TOKEN_COMMA, NULL))
+			{
+				if (lex_peek(it->lex) != JSON_TOKEN_OBJECT_END)
+					report_parse_error(JSON_PARSE_OBJECT_NEXT, it->lex);
+			}
+
+			if (it->state == JTI_OBJECT_VALUE_AFTER)
+			{
+				it->state = JTI_OBJECT_KEY;
+				goto recurse;
+			}
+
+			it->state = JTI_OBJECT_KEY;
+			return WJB_VALUE;
+
+		default:
+			break;
+	}
+
+	return WJB_DONE;
+}
+
+/* Initialize JsonIterator from json lexer which  onto the first token. */
+static JsonIterator *
+JsonIteratorInitFromLex(JsonContainer *jc, JsonLexContext *lex,
+						JsonIterator *parent)
+{
+	JsonIterator *it = palloc(sizeof(JsonIterator));
+	JsonTokenType tok;
+
+	it->container = jc;
+	it->parent = parent;
+	it->lex = lex;
+
+	tok = lex_peek(it->lex);
+
+	switch (tok)
+	{
+		case JSON_TOKEN_OBJECT_START:
+			it->isScalar = false;
+			it->state = JTI_OBJECT_START;
+			lex_accept(it->lex, tok, NULL);
+			break;
+		case JSON_TOKEN_ARRAY_START:
+			it->isScalar = false;
+			it->state = JTI_ARRAY_START;
+			lex_accept(it->lex, tok, NULL);
+			break;
+		case JSON_TOKEN_STRING:
+		case JSON_TOKEN_NUMBER:
+		case JSON_TOKEN_TRUE:
+		case JSON_TOKEN_FALSE:
+		case JSON_TOKEN_NULL:
+			it->isScalar = true;
+			it->state = JTI_ARRAY_START;
+			break;
+		default:
+			report_parse_error(JSON_PARSE_VALUE, it->lex);
+	}
+
+	return it;
+}
+
+/*
+ * Given a JsonContainer, expand to JsonIterator to iterate over items
+ * fully expanded to in-memory representation for manipulation.
+ *
+ * See JsonbIteratorNext() for notes on memory management.
+ */
+JsonIterator *
+JsonIteratorInit(JsonContainer *jc)
+{
+	JsonLexContext *lex = makeJsonLexContextCstringLen(jc->data, jc->len, true);
+	json_lex(lex);
+	return JsonIteratorInitFromLex(jc, lex, NULL);
+}
+
+/*
+ * Serialize a single JsonbValue into text buffer.
+ */
+static void
+JsonEncodeJsonbValue(StringInfo buf, JsonbValue *jbv)
+{
+	check_stack_depth();
+
+	switch (jbv->type)
+	{
+		case jbvNull:
+			appendBinaryStringInfo(buf, "null", 4);
+			break;
+
+		case jbvBool:
+			if (jbv->val.boolean)
+				appendBinaryStringInfo(buf, "true", 4);
+			else
+				appendBinaryStringInfo(buf, "false", 5);
+			break;
+
+		case jbvNumeric:
+			/* replace numeric NaN with string "NaN" */
+			if (numeric_is_nan(jbv->val.numeric))
+				appendBinaryStringInfo(buf, "\"NaN\"", 5);
+			else
+			{
+				Datum		str = DirectFunctionCall1(numeric_out,
+													  NumericGetDatum(jbv->val.numeric));
+
+				appendStringInfoString(buf, DatumGetCString(str));
+			}
+			break;
+
+		case jbvString:
+		{
+			char	   *str = jbv->val.string.len < 0 ? jbv->val.string.val :
+				pnstrdup(jbv->val.string.val, jbv->val.string.len);
+
+			escape_json(buf, str);
+
+			if (jbv->val.string.len >= 0)
+				pfree(str);
+
+			break;
+		}
+
+		case jbvArray:
+			{
+				int			i;
+
+				if (!jbv->val.array.rawScalar)
+					appendStringInfoChar(buf, '[');
+
+				for (i = 0; i < jbv->val.array.nElems; i++)
+				{
+					if (i > 0)
+						appendBinaryStringInfo(buf, ", ", 2);
+
+					JsonEncodeJsonbValue(buf, &jbv->val.array.elems[i]);
+				}
+
+				if (!jbv->val.array.rawScalar)
+					appendStringInfoChar(buf, ']');
+
+				break;
+			}
+
+		case jbvObject:
+			{
+				int			i;
+
+				appendStringInfoChar(buf, '{');
+
+				for (i = 0; i < jbv->val.object.nPairs; i++)
+				{
+					if (i > 0)
+						appendBinaryStringInfo(buf, ", ", 2);
+
+					JsonEncodeJsonbValue(buf, &jbv->val.object.pairs[i].key);
+					appendBinaryStringInfo(buf, ": ", 2);
+					JsonEncodeJsonbValue(buf, &jbv->val.object.pairs[i].value);
+				}
+
+				appendStringInfoChar(buf, '}');
+				break;
+			}
+
+		case jbvBinary:
+			{
+				JsonContainer *json = (JsonContainer *) jbv->val.binary.data;
+
+				appendBinaryStringInfo(buf, json->data, json->len);
+				break;
+			}
+
+		default:
+			elog(ERROR, "unknown jsonb value type: %d", jbv->type);
+			break;
+	}
+}
+
+/*
+ * Turn an in-memory JsonbValue into a json for on-disk storage.
+ */
+Json *
+JsonbValueToJson(JsonbValue *jbv)
+{
+	StringInfoData buf;
+	Json	   *json = palloc0(sizeof(*json));
+	int			type;
+	int			size;
+
+	if (jbv->type == jbvBinary)
+	{
+		/* simply copy the whole container and its data */
+		JsonContainer *src = (JsonContainer *) jbv->val.binary.data;
+		JsonContainerData *dst = (JsonContainerData *) &json->root;
+
+		*dst = *src;
+		dst->data = memcpy(palloc(src->len), src->data, src->len);
+
+		return json;
+	}
+
+	initStringInfo(&buf);
+
+	JsonEncodeJsonbValue(&buf, jbv);
+
+	switch (jbv->type)
+	{
+		case jbvArray:
+			type = JB_FARRAY;
+			size = jbv->val.array.nElems;
+			break;
+
+		case jbvObject:
+			type = JB_FOBJECT;
+			size = jbv->val.object.nPairs;
+			break;
+
+		default:	/* scalar */
+			type = JB_FARRAY | JB_FSCALAR;
+			size = 1;
+			break;
+	}
+
+	jsonInitContainer((JsonContainerData *) &json->root,
+					  buf.data, buf.len, type, size);
+
+	return json;
+}
+
+/* Context and semantic actions for JsonGetArraySize() */
+typedef struct JsonGetArraySizeState
+{
+	int		level;
+	uint32	size;
+} JsonGetArraySizeState;
+
+static void
+JsonGetArraySize_array_start(void *state)
+{
+	((JsonGetArraySizeState *) state)->level++;
+}
+
+static void
+JsonGetArraySize_array_end(void *state)
+{
+	((JsonGetArraySizeState *) state)->level--;
+}
+
+static void
+JsonGetArraySize_array_element_start(void *state, bool isnull)
+{
+	JsonGetArraySizeState *s = state;
+	if (s->level == 1)
+		s->size++;
+}
+
+/*
+ * Calculate the size of a json array by iterating through its elements.
+ */
+uint32
+JsonGetArraySize(JsonContainer *jc)
+{
+	JsonLexContext *lex = makeJsonLexContextCstringLen(jc->data, jc->len, false);
+	JsonSemAction	sem;
+	JsonGetArraySizeState state;
+
+	state.level = 0;
+	state.size = 0;
+
+	memset(&sem, 0, sizeof(sem));
+	sem.semstate = &state;
+	sem.array_start			= JsonGetArraySize_array_start;
+	sem.array_end 			= JsonGetArraySize_array_end;
+	sem.array_element_end	= JsonGetArraySize_array_element_start;
+
+	json_lex(lex);
+	parse_array(lex, &sem);
+
+	return state.size;
+}
+
+/*
+ * Find last key in a json object by name. Returns palloc()'d copy of the
+ * corresponding value, or NULL if is not found.
+ */
+static inline JsonbValue *
+jsonFindLastKeyInObject(JsonContainer *obj, const JsonbValue *key)
+{
+	JsonbValue *res = NULL;
+	JsonbValue	jbv;
+	JsonIterator *it;
+	JsonbIteratorToken tok;
+
+	Assert(JsonContainerIsObject(obj));
+	Assert(key->type == jbvString);
+
+	it = JsonIteratorInit(obj);
+
+	while ((tok = JsonIteratorNext(&it, &jbv, true)) != WJB_DONE)
+	{
+		if (tok == WJB_KEY && !lengthCompareJsonbStringValue(key, &jbv))
+		{
+			if (!res)
+				res = palloc(sizeof(*res));
+
+			tok = JsonIteratorNext(&it, res, true);
+			Assert(tok == WJB_VALUE);
+		}
+	}
+
+	return res;
+}
+
+/*
+ * Find scalar element in a array.  Returns palloc()'d copy of value or NULL.
+ */
+static JsonbValue *
+jsonFindValueInArray(JsonContainer *array, const JsonbValue *elem)
+{
+	JsonbValue *val = palloc(sizeof(*val));
+	JsonIterator *it;
+	JsonbIteratorToken tok;
+
+	Assert(JsonContainerIsArray(array));
+	Assert(IsAJsonbScalar(elem));
+
+	it = JsonIteratorInit(array);
+
+	while ((tok = JsonIteratorNext(&it, val, true)) != WJB_DONE)
+	{
+		if (tok == WJB_ELEM && val->type == elem->type &&
+			equalsJsonbScalarValue(val, (JsonbValue *) elem))
+		{
+			JsonIteratorFree(it);
+			return val;
+		}
+	}
+
+	pfree(val);
+	return NULL;
+}
+
+/*
+ * Find value in object (i.e. the "value" part of some key/value pair in an
+ * object), or find a matching element if we're looking through an array.
+ * The "flags" argument allows the caller to specify which container types are
+ * of interest.  If we cannot find the value, return NULL.  Otherwise, return
+ * palloc()'d copy of value.
+ *
+ * For more details, see findJsonbValueFromContainer().
+ */
+JsonbValue *
+findJsonValueFromContainer(JsonContainer *jc, uint32 flags, JsonbValue *key)
+{
+	Assert((flags & ~(JB_FARRAY | JB_FOBJECT)) == 0);
+
+	if (!JsonContainerSize(jc))
+		return NULL;
+
+	if ((flags & JB_FARRAY) && JsonContainerIsArray(jc))
+		return jsonFindValueInArray(jc, key);
+
+	if ((flags & JB_FOBJECT) && JsonContainerIsObject(jc))
+		return jsonFindLastKeyInObject(jc, key);
+
+	/* Not found */
+	return NULL;
+}
+
+/*
+ * Get i-th element of a json array.
+ *
+ * Returns palloc()'d copy of the value, or NULL if it does not exist.
+ */
+JsonbValue *
+getIthJsonValueFromContainer(JsonContainer *array, uint32 index)
+{
+	JsonbValue *val = palloc(sizeof(JsonbValue));
+	JsonIterator *it;
+	JsonbIteratorToken tok;
+
+	Assert(JsonContainerIsArray(array));
+
+	it = JsonIteratorInit(array);
+
+	while ((tok = JsonIteratorNext(&it, val, true)) != WJB_DONE)
+	{
+		if (tok == WJB_ELEM)
+		{
+			if (index-- == 0)
+			{
+				JsonIteratorFree(it);
+				return val;
+			}
+		}
+	}
+
+	pfree(val);
+
+	return NULL;
+}
+
+/*
+ * Push json JsonbValue into JsonbParseState.
+ *
+ * Used for converting an in-memory JsonbValue to a json. For more details,
+ * see pushJsonbValue(). This function differs from pushJsonbValue() only by
+ * resetting "uniquify" flag in objects.
+ */
+JsonbValue *
+pushJsonValue(JsonbParseState **pstate, JsonbIteratorToken seq,
+			  JsonbValue *jbval)
+{
+	JsonIterator *it;
+	JsonbValue *res = NULL;
+	JsonbValue	v;
+	JsonbIteratorToken tok;
+
+	if (!jbval || (seq != WJB_ELEM && seq != WJB_VALUE) ||
+		jbval->type != jbvBinary)
+	{
+		/* drop through */
+		res = pushJsonbValueScalar(pstate, seq, jbval);
+
+		/* reset "uniquify" flag of objects */
+		if (seq == WJB_BEGIN_OBJECT)
+			(*pstate)->contVal.val.object.uniquify = false;
+
+		return res;
+	}
+
+	/* unpack the binary and add each piece to the pstate */
+	it = JsonIteratorInit((JsonContainer *) jbval->val.binary.data);
+	while ((tok = JsonIteratorNext(&it, &v, false)) != WJB_DONE)
+	{
+		res = pushJsonbValueScalar(pstate, tok,
+								   tok < WJB_BEGIN_ARRAY ? &v : NULL);
+
+		/* reset "uniquify" flag of objects */
+		if (tok == WJB_BEGIN_OBJECT)
+			(*pstate)->contVal.val.object.uniquify = false;
+	}
+
+	return res;
+}
+
+/*
+ * Extract scalar JsonbValue from a scalar json.
+ */
+bool
+JsonExtractScalar(JsonContainer *jbc, JsonbValue *res)
+{
+	JsonIterator *it = JsonIteratorInit(jbc);
+	JsonbIteratorToken tok PG_USED_FOR_ASSERTS_ONLY;
+	JsonbValue	tmp;
+
+	if (!JsonContainerIsScalar(jbc))
+		return false;
+
+	tok = JsonIteratorNext(&it, &tmp, true);
+	Assert(tok == WJB_BEGIN_ARRAY);
+	Assert(tmp.val.array.nElems == 1 && tmp.val.array.rawScalar);
+
+	tok = JsonIteratorNext(&it, res, true);
+	Assert(tok == WJB_ELEM);
+	Assert(IsAJsonbScalar(res));
+
+	tok = JsonIteratorNext(&it, &tmp, true);
+	Assert(tok == WJB_END_ARRAY);
+
+	return true;
+}
+
+/*
+ * Turn a Json into its C-string representation with stripping quotes from
+ * scalar strings.
+ */
+char *
+JsonUnquote(Json *jb)
+{
+	if (JsonContainerIsScalar(&jb->root))
+	{
+		JsonbValue	v;
+
+		JsonExtractScalar(&jb->root, &v);
+
+		if (v.type == jbvString)
+			return pnstrdup(v.val.string.val, v.val.string.len);
+	}
+
+	return JsonToCString(NULL, &jb->root, 0);
+}
+
+/*
+ * Turn a JsonContainer into its C-string representation.
+ */
+char *
+JsonToCString(StringInfo out, JsonContainer *jc, int estimated_len)
+{
+	if (out)
+	{
+		appendBinaryStringInfo(out, jc->data, jc->len);
+		return out->data;
+	}
+	else
+	{
+		char *str = palloc(jc->len + 1);
+
+		memcpy(str, jc->data, jc->len);
+		str[jc->len] = 0;
+
+		return str;
+	}
+}
diff --git a/src/backend/utils/adt/jsonb.c b/src/backend/utils/adt/jsonb.c
index 87d3a8d..71f0679 100644
--- a/src/backend/utils/adt/jsonb.c
+++ b/src/backend/utils/adt/jsonb.c
@@ -206,24 +206,6 @@ JsonbTypeName(JsonbValue *jbv)
 			return "boolean";
 		case jbvNull:
 			return "null";
-		case jbvDatetime:
-			switch (jbv->val.datetime.typid)
-			{
-				case DATEOID:
-					return "date";
-				case TIMEOID:
-					return "time without time zone";
-				case TIMETZOID:
-					return "time with time zone";
-				case TIMESTAMPOID:
-					return "timestamp without time zone";
-				case TIMESTAMPTZOID:
-					return "timestamp with time zone";
-				default:
-					elog(ERROR, "unrecognized jsonb value datetime type: %d",
-						 jbv->val.datetime.typid);
-			}
-			return "unknown";
 		default:
 			elog(ERROR, "unrecognized jsonb value type: %d", jbv->type);
 			return "unknown";
diff --git a/src/backend/utils/adt/jsonb_util.c b/src/backend/utils/adt/jsonb_util.c
index 5618d39..def7c8f 100644
--- a/src/backend/utils/adt/jsonb_util.c
+++ b/src/backend/utils/adt/jsonb_util.c
@@ -39,7 +39,6 @@
 static void fillJsonbValue(JsonbContainer *container, int index,
 			   char *base_addr, uint32 offset,
 			   JsonbValue *result);
-static bool equalsJsonbScalarValue(JsonbValue *a, JsonbValue *b);
 static int	compareJsonbScalarValue(JsonbValue *a, JsonbValue *b);
 static Jsonb *convertToJsonb(JsonbValue *val);
 static void convertJsonbValue(StringInfo buffer, JEntry *header, JsonbValue *val, int level);
@@ -58,12 +57,8 @@ static JsonbParseState *pushState(JsonbParseState **pstate);
 static void appendKey(JsonbParseState *pstate, JsonbValue *scalarVal);
 static void appendValue(JsonbParseState *pstate, JsonbValue *scalarVal);
 static void appendElement(JsonbParseState *pstate, JsonbValue *scalarVal);
-static int	lengthCompareJsonbStringValue(const void *a, const void *b);
 static int	lengthCompareJsonbPair(const void *a, const void *b, void *arg);
 static void uniqueifyJsonbObject(JsonbValue *object);
-static JsonbValue *pushJsonbValueScalar(JsonbParseState **pstate,
-					 JsonbIteratorToken seq,
-					 JsonbValue *scalarVal);
 
 /*
  * Turn an in-memory JsonbValue into a Jsonb for on-disk storage.
@@ -244,7 +239,6 @@ compareJsonbContainers(JsonbContainer *a, JsonbContainer *b)
 							res = (va.val.object.nPairs > vb.val.object.nPairs) ? 1 : -1;
 						break;
 					case jbvBinary:
-					case jbvDatetime:
 						elog(ERROR, "unexpected jbvBinary value");
 				}
 			}
@@ -546,7 +540,7 @@ pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq,
  * Do the actual pushing, with only scalar or pseudo-scalar-array values
  * accepted.
  */
-static JsonbValue *
+JsonbValue *
 pushJsonbValueScalar(JsonbParseState **pstate, JsonbIteratorToken seq,
 					 JsonbValue *scalarVal)
 {
@@ -584,6 +578,7 @@ pushJsonbValueScalar(JsonbParseState **pstate, JsonbIteratorToken seq,
 			(*pstate)->size = 4;
 			(*pstate)->contVal.val.object.pairs = palloc(sizeof(JsonbPair) *
 														 (*pstate)->size);
+			(*pstate)->contVal.val.object.uniquify = true;
 			break;
 		case WJB_KEY:
 			Assert(scalarVal->type == jbvString);
@@ -826,6 +821,7 @@ recurse:
 			/* Set v to object on first object call */
 			val->type = jbvObject;
 			val->val.object.nPairs = (*it)->nElems;
+			val->val.object.uniquify = true;
 
 			/*
 			 * v->val.object.pairs is not actually set, because we aren't
@@ -1299,7 +1295,7 @@ JsonbHashScalarValueExtended(const JsonbValue *scalarVal, uint64 *hash,
 /*
  * Are two scalar JsonbValues of the same type a and b equal?
  */
-static bool
+bool
 equalsJsonbScalarValue(JsonbValue *aScalar, JsonbValue *bScalar)
 {
 	if (aScalar->type == bScalar->type)
@@ -1753,22 +1749,6 @@ convertJsonbScalar(StringInfo buffer, JEntry *jentry, JsonbValue *scalarVal)
 				JENTRY_ISBOOL_TRUE : JENTRY_ISBOOL_FALSE;
 			break;
 
-		case jbvDatetime:
-			{
-				char		buf[MAXDATELEN + 1];
-				size_t		len;
-
-				JsonEncodeDateTime(buf,
-								   scalarVal->val.datetime.value,
-								   scalarVal->val.datetime.typid,
-								   &scalarVal->val.datetime.tz);
-				len = strlen(buf);
-				appendToBuffer(buffer, buf, len);
-
-				*jentry = JENTRY_ISSTRING | len;
-			}
-			break;
-
 		default:
 			elog(ERROR, "invalid jsonb scalar type");
 	}
@@ -1786,7 +1766,7 @@ convertJsonbScalar(StringInfo buffer, JEntry *jentry, JsonbValue *scalarVal)
  * a and b are first sorted based on their length.  If a tie-breaker is
  * required, only then do we consider string binary equality.
  */
-static int
+int
 lengthCompareJsonbStringValue(const void *a, const void *b)
 {
 	const JsonbValue *va = (const JsonbValue *) a;
@@ -1850,6 +1830,9 @@ uniqueifyJsonbObject(JsonbValue *object)
 
 	Assert(object->type == jbvObject);
 
+	if (!object->val.object.uniquify)
+		return;
+
 	if (object->val.object.nPairs > 1)
 		qsort_arg(object->val.object.pairs, object->val.object.nPairs, sizeof(JsonbPair),
 				  lengthCompareJsonbPair, &hasNonUniq);
diff --git a/src/backend/utils/adt/jsonpath_exec.c b/src/backend/utils/adt/jsonpath_exec.c
index 7d84ef9..68668ea 100644
--- a/src/backend/utils/adt/jsonpath_exec.c
+++ b/src/backend/utils/adt/jsonpath_exec.c
@@ -72,12 +72,12 @@
 #include "utils/float.h"
 #include "utils/guc.h"
 #include "utils/json.h"
+#include "utils/jsonapi.h"
 #include "utils/jsonpath.h"
 #include "utils/date.h"
 #include "utils/timestamp.h"
 #include "utils/varlena.h"
 
-
 /* Standard error message for SQL/JSON errors */
 #define ERRMSG_JSON_ARRAY_NOT_FOUND			"SQL/JSON array not found"
 #define ERRMSG_JSON_OBJECT_NOT_FOUND		"SQL/JSON object not found"
@@ -90,23 +90,128 @@
 #define ERRMSG_INVALID_ARGUMENT_FOR_JSON_DATETIME_FUNCTION	\
 	"invalid argument for SQL/JSON datetime function"
 
+typedef enum JsonItemType
+{
+	/* Scalar types */
+	jsiNull = jbvNull,
+	jsiString = jbvString,
+	jsiNumeric = jbvNumeric,
+	jsiBool = jbvBool,
+	/* Composite types */
+	jsiArray = jbvArray,
+	jsiObject = jbvObject,
+	/* Binary (i.e. struct Jsonb) jbvArray/jbvObject */
+	jsiBinary = jbvBinary,
+
+	/*
+	 * Virtual types.
+	 *
+	 * These types are used only for in-memory JSON processing and serialized
+	 * into JSON strings when outputted to json/jsonb.
+	 */
+	jsiDatetime = 0x20
+} JsonItemType;
+
+/* SQL/JSON item */
+typedef struct JsonItem
+{
+	struct JsonItem *next;
+
+	union
+	{
+		int			type;	/* XXX JsonItemType */
+
+		JsonbValue	jbv;
+
+		struct
+		{
+			int			type;
+			Datum		value;
+			Oid			typid;
+			int32		typmod;
+			int			tz;
+		}			datetime;
+	} val;
+} JsonItem;
+
+#define JsonItemJbv(jsi)			(&(jsi)->val.jbv)
+#define JsonItemBool(jsi)			(JsonItemJbv(jsi)->val.boolean)
+#define JsonItemNumeric(jsi)		(JsonItemJbv(jsi)->val.numeric)
+#define JsonItemNumericDatum(jsi)	NumericGetDatum(JsonItemNumeric(jsi))
+#define JsonItemString(jsi)			(JsonItemJbv(jsi)->val.string)
+#define JsonItemBinary(jsi)			(JsonItemJbv(jsi)->val.binary)
+#define JsonItemArray(jsi)			(JsonItemJbv(jsi)->val.array)
+#define JsonItemObject(jsi)			(JsonItemJbv(jsi)->val.object)
+#define JsonItemDatetime(jsi)		((jsi)->val.datetime)
+
+#define JsonItemGetType(jsi)		((jsi)->val.type)
+#define JsonItemIsNull(jsi)			(JsonItemGetType(jsi) == jsiNull)
+#define JsonItemIsBool(jsi)			(JsonItemGetType(jsi) == jsiBool)
+#define JsonItemIsNumeric(jsi)		(JsonItemGetType(jsi) == jsiNumeric)
+#define JsonItemIsString(jsi)		(JsonItemGetType(jsi) == jsiString)
+#define JsonItemIsBinary(jsi)		(JsonItemGetType(jsi) == jsiBinary)
+#define JsonItemIsArray(jsi)		(JsonItemGetType(jsi) == jsiArray)
+#define JsonItemIsObject(jsi)		(JsonItemGetType(jsi) == jsiObject)
+#define JsonItemIsDatetime(jsi)		(JsonItemGetType(jsi) == jsiDatetime)
+#define JsonItemIsScalar(jsi)		(IsAJsonbScalar(JsonItemJbv(jsi)) || \
+									 JsonItemIsDatetime(jsi))
+
+typedef union Jsonx
+{
+	Jsonb		jb;
+	Json		js;
+} Jsonx;
+
+#define DatumGetJsonxP(datum, isJsonb) \
+	((isJsonb) ? (Jsonx *) DatumGetJsonbP(datum) : (Jsonx *) DatumGetJsonP(datum))
+
+typedef JsonbContainer JsonxContainer;
+
+typedef struct JsonxIterator
+{
+	bool		isJsonb;
+	union
+	{
+		JsonbIterator *jb;
+		JsonIterator *js;
+	}			it;
+} JsonxIterator;
+
 /*
  * Represents "base object" and it's "id" for .keyvalue() evaluation.
  */
 typedef struct JsonBaseObjectInfo
 {
-	JsonbContainer *jbc;
+	JsonxContainer *jbc;
 	int			id;
 } JsonBaseObjectInfo;
 
 /*
+ * Special data structure representing stack of current items.  We use it
+ * instead of regular list in order to evade extra memory allocation.  These
+ * items are always allocated in local variables.
+ */
+typedef struct JsonItemStackEntry
+{
+	JsonItem   *item;
+	struct JsonItemStackEntry *parent;
+} JsonItemStackEntry;
+
+typedef JsonItemStackEntry *JsonItemStack;
+
+typedef int (*JsonPathVarCallback) (void *vars, bool isJsonb,
+									char *varName, int varNameLen,
+									JsonItem *val, JsonbValue *baseObject);
+
+/*
  * Context of jsonpath execution.
  */
 typedef struct JsonPathExecContext
 {
-	Jsonb	   *vars;			/* variables to substitute into jsonpath */
-	JsonbValue *root;			/* for $ evaluation */
-	JsonbValue *current;		/* for @ evaluation */
+	void	   *vars;			/* variables to substitute into jsonpath */
+	JsonPathVarCallback getVar;
+	JsonItem   *root;			/* for $ evaluation */
+	JsonItemStack stack;		/* for @ evaluation */
 	JsonBaseObjectInfo baseObject;	/* "base object" for .keyvalue()
 									 * evaluation */
 	int			lastGeneratedObjectId;	/* "id" counter for .keyvalue()
@@ -120,6 +225,7 @@ typedef struct JsonPathExecContext
 										 * ignored */
 	bool		throwErrors;	/* with "false" all suppressible errors are
 								 * suppressed */
+	bool		isJsonb;
 } JsonPathExecContext;
 
 /* Context for LIKE_REGEX execution. */
@@ -148,20 +254,34 @@ typedef enum JsonPathExecResult
 #define jperIsError(jper)			((jper) == jperError)
 
 /*
- * List of jsonb values with shortcut for single-value list.
+ * List of SQL/JSON items with shortcut for single-value list.
  */
 typedef struct JsonValueList
 {
-	JsonbValue *singleton;
-	List	   *list;
+	JsonItem   *head;
+	JsonItem   *tail;
+	int			length;
 } JsonValueList;
 
 typedef struct JsonValueListIterator
 {
-	JsonbValue *value;
-	ListCell   *next;
+	JsonItem   *next;
 } JsonValueListIterator;
 
+/*
+ * Context for execution of jsonb_path_*(jsonb, jsonpath [, vars jsonb]) user
+ * functions.
+ */
+typedef struct JsonPathUserFuncContext
+{
+	FunctionCallInfo fcinfo;
+	void	   *js;				/* first jsonb function argument */
+	Json	   *json;
+	JsonPath   *jp;				/* second jsonpath function argument */
+	void	   *vars;			/* third vars function argument */
+	JsonValueList found;		/* resulting item list */
+} JsonPathUserFuncContext;
+
 /* strict/lax flags is decomposed into four [un]wrap/error flags */
 #define jspStrictAbsenseOfErrors(cxt)	(!(cxt)->laxMode)
 #define jspAutoUnwrap(cxt)				((cxt)->laxMode)
@@ -178,86 +298,131 @@ do { \
 } while (0)
 
 typedef JsonPathBool (*JsonPathPredicateCallback) (JsonPathItem *jsp,
-												   JsonbValue *larg,
-												   JsonbValue *rarg,
+												   JsonItem *larg,
+												   JsonItem *rarg,
 												   void *param);
 
 typedef Numeric (*BinaryArithmFunc) (Numeric num1, Numeric num2, bool *error);
 
-static JsonPathExecResult executeJsonPath(JsonPath *path, Jsonb *vars,
-				Jsonb *json, bool throwErrors, JsonValueList *result);
+typedef JsonbValue *(*JsonBuilderFunc) (JsonbParseState **,
+										JsonbIteratorToken,
+										JsonbValue *);
+
+static void freeUserFuncContext(JsonPathUserFuncContext *cxt);
+static JsonPathExecResult executeUserFunc(FunctionCallInfo fcinfo,
+				JsonPathUserFuncContext *cxt, bool isJsonb, bool invertSilent,
+				bool copy);
+
+static JsonPathExecResult executeJsonPath(JsonPath *path, void *vars,
+				JsonPathVarCallback getVar, Jsonx *json, bool isJsonb,
+				bool throwErrors, JsonValueList *result);
 static JsonPathExecResult recursiveExecute(JsonPathExecContext *cxt,
-				 JsonPathItem *jsp, JsonbValue *jb, JsonValueList *found);
+				 JsonPathItem *jsp, JsonItem *jb, JsonValueList *found);
 static JsonPathExecResult recursiveExecuteUnwrap(JsonPathExecContext *cxt,
-					   JsonPathItem *jsp, JsonbValue *jb, bool unwrap, JsonValueList *found);
+					   JsonPathItem *jsp, JsonItem *jb, bool unwrap,
+					   JsonValueList *found);
+
 static JsonPathExecResult recursiveExecuteUnwrapArray(JsonPathExecContext *cxt,
-							JsonPathItem *jsp, JsonbValue *jb,
+							JsonPathItem *jsp, JsonItem *jb,
 							JsonValueList *found, bool unwrapElements);
 static JsonPathExecResult recursiveExecuteNext(JsonPathExecContext *cxt,
 					 JsonPathItem *cur, JsonPathItem *next,
-					 JsonbValue *v, JsonValueList *found, bool copy);
+					 JsonItem *v, JsonValueList *found, bool copy);
 static JsonPathExecResult recursiveExecuteAndUnwrap(JsonPathExecContext *cxt,
-						  JsonPathItem *jsp, JsonbValue *jb, bool unwrap, JsonValueList *found);
+						  JsonPathItem *jsp, JsonItem *jb, bool unwrap, JsonValueList *found);
 static JsonPathExecResult recursiveExecuteAndUnwrapNoThrow(
 								 JsonPathExecContext *cxt, JsonPathItem *jsp,
-								 JsonbValue *jb, bool unwrap, JsonValueList *found);
+								 JsonItem *jb, bool unwrap, JsonValueList *found);
 static JsonPathBool recursiveExecuteBool(JsonPathExecContext *cxt,
-					 JsonPathItem *jsp, JsonbValue *jb, bool canHaveNext);
+					 JsonPathItem *jsp, JsonItem *jb, bool canHaveNext);
 static JsonPathBool recursiveExecuteBoolNested(JsonPathExecContext *cxt,
-						   JsonPathItem *jsp, JsonbValue *jb);
+						   JsonPathItem *jsp, JsonItem *jb);
 static JsonPathExecResult recursiveAny(JsonPathExecContext *cxt,
 			 JsonPathItem *jsp, JsonbContainer *jbc, JsonValueList *found,
 			 uint32 level, uint32 first, uint32 last,
 			 bool ignoreStructuralErrors, bool unwrapNext);
 static JsonPathBool executePredicate(JsonPathExecContext *cxt,
 				 JsonPathItem *pred, JsonPathItem *larg, JsonPathItem *rarg,
-				 JsonbValue *jb, bool unwrapRightArg,
+				 JsonItem *jb, bool unwrapRightArg,
 				 JsonPathPredicateCallback exec, void *param);
 static JsonPathExecResult executeBinaryArithmExpr(JsonPathExecContext *cxt,
-						JsonPathItem *jsp, JsonbValue *jb, BinaryArithmFunc func,
+						JsonPathItem *jsp, JsonItem *jb, BinaryArithmFunc func,
 						JsonValueList *found);
 static JsonPathExecResult executeUnaryArithmExpr(JsonPathExecContext *cxt,
-					   JsonPathItem *jsp, JsonbValue *jb, PGFunction func,
+					   JsonPathItem *jsp, JsonItem *jb, PGFunction func,
 					   JsonValueList *found);
 static JsonPathBool executeStartsWith(JsonPathItem *jsp,
-				  JsonbValue *whole, JsonbValue *initial, void *param);
-static JsonPathBool executeLikeRegex(JsonPathItem *jsp, JsonbValue *str,
-				 JsonbValue *rarg, void *param);
+				  JsonItem *whole, JsonItem *initial, void *param);
+static JsonPathBool executeLikeRegex(JsonPathItem *jsp, JsonItem *str,
+				 JsonItem *rarg, void *param);
 static JsonPathExecResult executeNumericItemMethod(JsonPathExecContext *cxt,
-						 JsonPathItem *jsp, JsonbValue *jb, bool unwrap, PGFunction func,
+						 JsonPathItem *jsp, JsonItem *jb, bool unwrap, PGFunction func,
 						 JsonValueList *found);
 static JsonPathExecResult executeKeyValueMethod(JsonPathExecContext *cxt,
-					  JsonPathItem *jsp, JsonbValue *jb, JsonValueList *found);
+					  JsonPathItem *jsp, JsonItem *jb, JsonValueList *found);
 static JsonPathExecResult appendBoolResult(JsonPathExecContext *cxt,
 				 JsonPathItem *jsp, JsonValueList *found, JsonPathBool res);
 static void getJsonPathItem(JsonPathExecContext *cxt, JsonPathItem *item,
-				JsonbValue *value);
+				JsonItem *value);
 static void getJsonPathVariable(JsonPathExecContext *cxt,
-					JsonPathItem *variable, Jsonb *vars, JsonbValue *value);
-static int	JsonbArraySize(JsonbValue *jb);
-static JsonPathBool executeComparison(JsonPathItem *cmp, JsonbValue *lv,
-				  JsonbValue *rv, void *p);
-static JsonPathBool compareItems(int32 op, JsonbValue *jb1, JsonbValue *jb2);
+					JsonPathItem *variable, JsonItem *value);
+static int getJsonPathVariableFromJsonx(void *varsJsonb, bool isJsonb,
+							 char *varName, int varNameLen, JsonItem *val,
+							 JsonbValue *baseObject);
+static int	JsonxArraySize(JsonItem *jb, bool isJsonb);
+static JsonPathBool executeComparison(JsonPathItem *cmp, JsonItem *lv,
+				  JsonItem *rv, void *p);
+static JsonPathBool compareItems(int32 op, JsonItem *jb1, JsonItem *jb2);
 static int	compareNumeric(Numeric a, Numeric b);
-static JsonbValue *copyJsonbValue(JsonbValue *src);
+
+static void JsonItemInitNull(JsonItem *item);
+static void JsonItemInitBool(JsonItem *item, bool val);
+static void JsonItemInitNumeric(JsonItem *item, Numeric val);
+#define JsonItemInitNumericDatum(item, val) \
+		JsonItemInitNumeric(item, DatumGetNumeric(val))
+static void JsonItemInitString(JsonItem *item, char *str, int len);
+static void JsonItemInitDatetime(JsonItem *item, Datum val, Oid typid,
+					 int32 typmod, int tz);
+
+static JsonItem *copyJsonItem(JsonItem *src);
+static JsonItem *JsonbValueToJsonItem(JsonbValue *jbv, JsonItem *jsi);
+static JsonbValue *JsonItemToJsonbValue(JsonItem *jsi, JsonbValue *jbv);
+static Jsonb *JsonItemToJsonb(JsonItem *jsi);
+static const char *JsonItemTypeName(JsonItem *jsi);
 static JsonPathExecResult getArrayIndex(JsonPathExecContext *cxt,
-			  JsonPathItem *jsp, JsonbValue *jb, int32 *index);
+			  JsonPathItem *jsp, JsonItem *jb, int32 *index);
 static JsonBaseObjectInfo setBaseObject(JsonPathExecContext *cxt,
-			  JsonbValue *jbv, int32 id);
-static void JsonValueListAppend(JsonValueList *jvl, JsonbValue *jbv);
+			  JsonItem *jsi, int32 id);
+static void JsonValueListAppend(JsonValueList *jvl, JsonItem *jbv);
 static int	JsonValueListLength(const JsonValueList *jvl);
 static bool JsonValueListIsEmpty(JsonValueList *jvl);
-static JsonbValue *JsonValueListHead(JsonValueList *jvl);
+static JsonItem *JsonValueListHead(JsonValueList *jvl);
 static List *JsonValueListGetList(JsonValueList *jvl);
 static void JsonValueListInitIterator(const JsonValueList *jvl,
 						  JsonValueListIterator *it);
-static JsonbValue *JsonValueListNext(const JsonValueList *jvl,
+static JsonItem *JsonValueListNext(const JsonValueList *jvl,
 				  JsonValueListIterator *it);
-static int	JsonbType(JsonbValue *jb);
+static int	JsonbType(JsonItem *jb);
 static JsonbValue *JsonbInitBinary(JsonbValue *jbv, Jsonb *jb);
-static int	JsonbType(JsonbValue *jb);
-static JsonbValue *getScalar(JsonbValue *scalar, enum jbvType type);
-static JsonbValue *wrapItemsInArray(const JsonValueList *items);
+static inline JsonbValue *JsonInitBinary(JsonbValue *jbv, Json *js);
+static JsonItem *getScalar(JsonItem *scalar, enum jbvType type);
+static JsonbValue *wrapItemsInArray(const JsonValueList *items, bool isJsonb);
+static text *JsonItemUnquoteText(JsonItem *jsi, bool isJsonb);
+
+static JsonItem *getJsonObjectKey(JsonItem *jb, char *keystr, int keylen,
+				 bool isJsonb, JsonItem *val);
+static JsonItem *getJsonArrayElement(JsonItem *jb, uint32 index, bool isJsonb,
+					JsonItem *elem);
+
+static void JsonxIteratorInit(JsonxIterator *it, JsonxContainer *jxc,
+				  bool isJsonb);
+static JsonbIteratorToken JsonxIteratorNext(JsonxIterator *it, JsonbValue *jbv,
+				  bool skipNested);
+static JsonbValue *JsonItemToJsonbValue(JsonItem *jsi, JsonbValue *jbv);
+static Json *JsonItemToJson(JsonItem *jsi);
+static Jsonx *JsonbValueToJsonx(JsonbValue *jbv, bool isJsonb);
+static Datum JsonbValueToJsonxDatum(JsonbValue *jbv, bool isJsonb);
+static Datum JsonItemToJsonxDatum(JsonItem *jsi, bool isJsonb);
 
 static bool tryToParseDatetime(text *fmt, text *datetime, char *tzname,
 				   bool strict, Datum *value, Oid *typid,
@@ -266,10 +431,14 @@ static int compareDatetime(Datum val1, Oid typid1, int tz1,
 				Datum val2, Oid typid2, int tz2,
 				bool *error);
 
+static void pushJsonItem(JsonItemStack *stack,
+			 JsonItemStackEntry *entry, JsonItem *item);
+static void popJsonItem(JsonItemStack *stack);
+
 /****************** User interface to JsonPath executor ********************/
 
 /*
- * jsonb_path_exists
+ * json[b]_path_exists
  *		Returns true if jsonpath returns at least one item for the specified
  *		jsonb value.  This function and jsonb_path_match() are used to
  *		implement @? and @@ operators, which in turn are intended to have an
@@ -280,25 +449,10 @@ static int compareDatetime(Datum val1, Oid typid1, int tz1,
  *		SQL/JSON.  Regarding jsonb_path_match(), this function doesn't have
  *		an analogy in SQL/JSON, so we define its behavior on our own.
  */
-Datum
-jsonb_path_exists(PG_FUNCTION_ARGS)
+static Datum
+jsonx_path_exists(PG_FUNCTION_ARGS, bool isJsonb)
 {
-	Jsonb	   *jb = PG_GETARG_JSONB_P(0);
-	JsonPath   *jp = PG_GETARG_JSONPATH_P(1);
-	JsonPathExecResult res;
-	Jsonb	   *vars = NULL;
-	bool		silent = true;
-
-	if (PG_NARGS() == 4)
-	{
-		vars = PG_GETARG_JSONB_P(2);
-		silent = !PG_GETARG_BOOL(3);
-	}
-
-	res = executeJsonPath(jp, vars, jb, !silent, NULL);
-
-	PG_FREE_IF_COPY(jb, 0);
-	PG_FREE_IF_COPY(jp, 1);
+	JsonPathExecResult res = executeUserFunc(fcinfo, NULL, isJsonb, true, false);
 
 	if (jperIsError(res))
 		PG_RETURN_NULL();
@@ -306,99 +460,121 @@ jsonb_path_exists(PG_FUNCTION_ARGS)
 	PG_RETURN_BOOL(res == jperOk);
 }
 
+Datum
+jsonb_path_exists(PG_FUNCTION_ARGS)
+{
+	return jsonx_path_exists(fcinfo, true);
+}
+
+Datum
+json_path_exists(PG_FUNCTION_ARGS)
+{
+	return jsonx_path_exists(fcinfo, false);
+}
+
 /*
- * jsonb_path_exists_novars
- *		Implements the 2-argument version of jsonb_path_exists
+ * json[b]_path_exists_opr
+ *		Implements the 2-argument version of json[b]_path_exists
  */
 Datum
 jsonb_path_exists_opr(PG_FUNCTION_ARGS)
 {
-	/* just call the other one -- it can handle both cases */
-	return jsonb_path_exists(fcinfo);
+	return jsonx_path_exists(fcinfo, true);
+}
+
+Datum
+json_path_exists_opr(PG_FUNCTION_ARGS)
+{
+	return jsonx_path_exists(fcinfo, false);
 }
 
 /*
- * jsonb_path_match
+ * json[b]_path_match
  *		Returns jsonpath predicate result item for the specified jsonb value.
  *		See jsonb_path_exists() comment for details regarding error handling.
  */
-Datum
-jsonb_path_match(PG_FUNCTION_ARGS)
+static Datum
+jsonx_path_match(PG_FUNCTION_ARGS, bool isJsonb)
 {
-	Jsonb	   *jb = PG_GETARG_JSONB_P(0);
-	JsonPath   *jp = PG_GETARG_JSONPATH_P(1);
-	JsonbValue *jbv;
-	JsonValueList found = {0};
-	Jsonb	   *vars = NULL;
-	bool		silent = true;
+	JsonPathUserFuncContext cxt;
+	JsonItem   *res;
 
-	if (PG_NARGS() == 4)
-	{
-		vars = PG_GETARG_JSONB_P(2);
-		silent = !PG_GETARG_BOOL(3);
-	}
-
-	(void) executeJsonPath(jp, vars, jb, !silent, &found);
+	(void) executeUserFunc(fcinfo, &cxt, isJsonb, true, false);
 
-	if (JsonValueListLength(&found) < 1)
+	if (JsonValueListLength(&cxt.found) < 1)
 		PG_RETURN_NULL();
 
-	jbv = JsonValueListHead(&found);
+	res = JsonValueListHead(&cxt.found);
 
-	PG_FREE_IF_COPY(jb, 0);
-	PG_FREE_IF_COPY(jp, 1);
+	freeUserFuncContext(&cxt);
 
-	if (jbv->type != jbvBool)
+	if (!JsonItemIsBool(res))
 		PG_RETURN_NULL();
 
-	PG_RETURN_BOOL(jbv->val.boolean);
+	PG_RETURN_BOOL(JsonItemBool(res));
+}
+
+Datum
+jsonb_path_match(PG_FUNCTION_ARGS)
+{
+	return jsonx_path_match(fcinfo, true);
+}
+
+Datum
+json_path_match(PG_FUNCTION_ARGS)
+{
+	return jsonx_path_match(fcinfo, false);
 }
 
 /*
- * jsonb_path_match_novars
- *		Implements the 2-argument version of jsonb_path_match
+ * json[b]_path_match_opr
+ *		Implements the 2-argument version of json[b]_path_match
  */
 Datum
 jsonb_path_match_opr(PG_FUNCTION_ARGS)
 {
 	/* just call the other one -- it can handle both cases */
-	return jsonb_path_match(fcinfo);
+	return jsonx_path_match(fcinfo, true);
+}
+
+Datum
+json_path_match_opr(PG_FUNCTION_ARGS)
+{
+	/* just call the other one -- it can handle both cases */
+	return jsonx_path_match(fcinfo, false);
 }
 
 /*
- * jsonb_path_query
+ * json[b]_path_query
  *		Executes jsonpath for given jsonb document and returns result as
  *		rowset.
  */
-Datum
-jsonb_path_query(PG_FUNCTION_ARGS)
+static Datum
+jsonx_path_query(PG_FUNCTION_ARGS, bool isJsonb)
 {
 	FuncCallContext *funcctx;
 	List	   *found;
-	JsonbValue *v;
+	JsonItem   *v;
 	ListCell   *c;
+	Datum		res;
 
 	if (SRF_IS_FIRSTCALL())
 	{
-		JsonPath   *jp;
-		Jsonb	   *jb;
+		JsonPathUserFuncContext jspcxt;
 		MemoryContext oldcontext;
-		Jsonb	   *vars;
-		bool		silent;
-		JsonValueList found = {0};
 
 		funcctx = SRF_FIRSTCALL_INIT();
 		oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
 
-		jb = PG_GETARG_JSONB_P_COPY(0);
-		jp = PG_GETARG_JSONPATH_P_COPY(1);
-		vars = PG_GETARG_JSONB_P_COPY(2);
-		silent = PG_GETARG_BOOL(3);
+		/* jsonb and jsonpath arguments are copied into SRF context. */
+		(void) executeUserFunc(fcinfo, &jspcxt, isJsonb, false, true);
 
-		(void) executeJsonPath(jp, vars, jb, !silent, &found);
-
-		funcctx->user_fctx = JsonValueListGetList(&found);
+		/*
+		 * Don't free jspcxt because items in jspcxt.found can reference
+		 * untoasted copies of jsonb and jsonpath arguments.
+		 */
 
+		funcctx->user_fctx = JsonValueListGetList(&jspcxt.found);
 		MemoryContextSwitchTo(oldcontext);
 	}
 
@@ -413,50 +589,214 @@ jsonb_path_query(PG_FUNCTION_ARGS)
 	v = lfirst(c);
 	funcctx->user_fctx = list_delete_first(found);
 
-	SRF_RETURN_NEXT(funcctx, JsonbPGetDatum(JsonbValueToJsonb(v)));
+	res = isJsonb ?
+		JsonbPGetDatum(JsonItemToJsonb(v)) :
+		JsonPGetDatum(JsonItemToJson(v));
+
+	SRF_RETURN_NEXT(funcctx, res);
+}
+
+Datum
+jsonb_path_query(PG_FUNCTION_ARGS)
+{
+	return jsonx_path_query(fcinfo, true);
+}
+
+Datum
+json_path_query(PG_FUNCTION_ARGS)
+{
+	return jsonx_path_query(fcinfo, false);
 }
 
 /*
- * jsonb_path_query_array
+ * json[b]_path_query_array
  *		Executes jsonpath for given jsonb document and returns result as
  *		jsonb array.
  */
-Datum
-jsonb_path_query_array(FunctionCallInfo fcinfo)
+static Datum
+jsonx_path_query_array(PG_FUNCTION_ARGS, bool isJsonb)
 {
-	Jsonb	   *jb = PG_GETARG_JSONB_P(0);
-	JsonPath   *jp = PG_GETARG_JSONPATH_P(1);
-	JsonValueList found = {0};
-	Jsonb	   *vars = PG_GETARG_JSONB_P(2);
-	bool		silent = PG_GETARG_BOOL(3);
+	JsonPathUserFuncContext cxt;
+	Datum		res;
 
-	(void) executeJsonPath(jp, vars, jb, !silent, &found);
+	(void) executeUserFunc(fcinfo, &cxt, isJsonb, false, false);
 
-	PG_RETURN_JSONB_P(JsonbValueToJsonb(wrapItemsInArray(&found)));
+	res = JsonbValueToJsonxDatum(wrapItemsInArray(&cxt.found, isJsonb), isJsonb);
+
+	freeUserFuncContext(&cxt);
+
+	PG_RETURN_DATUM(res);
+}
+
+Datum
+jsonb_path_query_array(PG_FUNCTION_ARGS)
+{
+	return jsonx_path_query_array(fcinfo, true);
+}
+
+Datum
+json_path_query_array(PG_FUNCTION_ARGS)
+{
+	return jsonx_path_query_array(fcinfo, false);
 }
 
 /*
- * jsonb_path_query_first
+ * json[b]_path_query_first
  *		Executes jsonpath for given jsonb document and returns first result
  *		item.  If there are no items, NULL returned.
  */
+static Datum
+jsonx_path_query_first(PG_FUNCTION_ARGS, bool isJsonb)
+{
+	JsonPathUserFuncContext cxt;
+	Datum		res;
+
+	(void) executeUserFunc(fcinfo, &cxt, isJsonb, false, false);
+
+	if (JsonValueListLength(&cxt.found) >= 1)
+		res = JsonItemToJsonxDatum(JsonValueListHead(&cxt.found), isJsonb);
+	else
+		res = (Datum) 0;
+
+	freeUserFuncContext(&cxt);
+
+	if (res)
+		PG_RETURN_DATUM(res);
+	else
+		PG_RETURN_NULL();
+}
+
 Datum
-jsonb_path_query_first(FunctionCallInfo fcinfo)
+jsonb_path_query_first(PG_FUNCTION_ARGS)
 {
-	Jsonb	   *jb = PG_GETARG_JSONB_P(0);
-	JsonPath   *jp = PG_GETARG_JSONPATH_P(1);
-	JsonValueList found = {0};
-	Jsonb	   *vars = PG_GETARG_JSONB_P(2);
-	bool		silent = PG_GETARG_BOOL(3);
+	return jsonx_path_query_first(fcinfo, true);
+}
 
-	(void) executeJsonPath(jp, vars, jb, !silent, &found);
+Datum
+json_path_query_first(PG_FUNCTION_ARGS)
+{
+	return jsonx_path_query_first(fcinfo, false);
+}
 
-	if (JsonValueListLength(&found) >= 1)
-		PG_RETURN_JSONB_P(JsonbValueToJsonb(JsonValueListHead(&found)));
+/*
+ * json[b]_path_query_first_text
+ *		Executes jsonpath for given jsonb document and returns first result
+ *		item as text.  If there are no items, NULL returned.
+ */
+static Datum
+jsonx_path_query_first_text(PG_FUNCTION_ARGS, bool isJsonb)
+{
+	JsonPathUserFuncContext cxt;
+	text	   *txt;
+
+	(void) executeUserFunc(fcinfo, &cxt, isJsonb, false, false);
+
+	if (JsonValueListLength(&cxt.found) >= 1)
+		txt = JsonItemUnquoteText(JsonValueListHead(&cxt.found), isJsonb);
+	else
+		txt = NULL;
+
+	freeUserFuncContext(&cxt);
+
+	if (txt)
+		PG_RETURN_TEXT_P(txt);
 	else
 		PG_RETURN_NULL();
 }
 
+Datum
+jsonb_path_query_first_text(PG_FUNCTION_ARGS)
+{
+	return jsonx_path_query_first_text(fcinfo, true);
+}
+
+Datum
+json_path_query_first_text(PG_FUNCTION_ARGS)
+{
+	return jsonx_path_query_first_text(fcinfo, false);
+}
+
+/* Free untoasted copies of jsonb and jsonpath arguments. */
+static void
+freeUserFuncContext(JsonPathUserFuncContext *cxt)
+{
+	FunctionCallInfo fcinfo = cxt->fcinfo;
+
+	PG_FREE_IF_COPY(cxt->js, 0);
+	PG_FREE_IF_COPY(cxt->jp, 1);
+	if (cxt->vars)
+		PG_FREE_IF_COPY(cxt->vars, 2);
+	if (cxt->json)
+		pfree(cxt->json);
+}
+
+/*
+ * Common code for jsonb_path_*(jsonb, jsonpath [, vars jsonb, silent bool])
+ * user functions.
+ *
+ * 'copy' flag enables copying of first three arguments into the current memory
+ * context.
+ */
+static JsonPathExecResult
+executeUserFunc(FunctionCallInfo fcinfo, JsonPathUserFuncContext *cxt,
+				bool isJsonb, bool invertSilent, bool copy)
+{
+	Datum		js_toasted = PG_GETARG_DATUM(0);
+	struct varlena *js_detoasted = copy ?
+		PG_DETOAST_DATUM(js_toasted) :
+		PG_DETOAST_DATUM_COPY(js_toasted);
+	Jsonx	   *js = DatumGetJsonxP(js_detoasted, isJsonb);
+	JsonPath   *jp = copy ? PG_GETARG_JSONPATH_P_COPY(1) : PG_GETARG_JSONPATH_P(1);
+	struct varlena *vars_detoasted = NULL;
+	Jsonx	   *vars = NULL;
+	bool		silent = true;
+	JsonPathExecResult res;
+
+	if (PG_NARGS() == 4)
+	{
+		Datum		vars_toasted = PG_GETARG_DATUM(2);
+
+		vars_detoasted = copy ?
+			PG_DETOAST_DATUM(vars_toasted) :
+			PG_DETOAST_DATUM_COPY(vars_toasted);
+
+		vars = DatumGetJsonxP(vars_detoasted, isJsonb);
+
+		silent = PG_GETARG_BOOL(3) ^ invertSilent;
+	}
+
+	if (cxt)
+	{
+		cxt->fcinfo = fcinfo;
+		cxt->js = js_detoasted;
+		cxt->jp = jp;
+		cxt->vars = vars_detoasted;
+		cxt->json = isJsonb ? NULL : &js->js;
+		memset(&cxt->found, 0, sizeof(cxt->found));
+	}
+
+	res = executeJsonPath(jp, vars, getJsonPathVariableFromJsonx,
+						  js, isJsonb, !silent, cxt ? &cxt->found : NULL);
+
+	if (!cxt && !copy)
+	{
+		PG_FREE_IF_COPY(js_detoasted, 0);
+		PG_FREE_IF_COPY(jp, 1);
+
+		if (vars_detoasted)
+			PG_FREE_IF_COPY(vars_detoasted, 2);
+
+		if (!isJsonb)
+		{
+			pfree(js);
+			if (vars)
+				pfree(vars);
+		}
+	}
+
+	return res;
+}
+
 /********************Execute functions for JsonPath**************************/
 
 /*
@@ -478,37 +818,45 @@ jsonb_path_query_first(FunctionCallInfo fcinfo)
  * In other case it tries to find all the satisfied result items.
  */
 static JsonPathExecResult
-executeJsonPath(JsonPath *path, Jsonb *vars, Jsonb *json, bool throwErrors,
+executeJsonPath(JsonPath *path, void *vars, JsonPathVarCallback getVar,
+				Jsonx *json, bool isJsonb, bool throwErrors,
 				JsonValueList *result)
 {
 	JsonPathExecContext cxt;
 	JsonPathExecResult res;
 	JsonPathItem jsp;
-	JsonbValue	jbv;
+	JsonItem	jsi;
+	JsonbValue *jbv = JsonItemJbv(&jsi);
+	JsonItemStackEntry root;
 
 	jspInit(&jsp, path);
 
-	if (!JsonbExtractScalar(&json->root, &jbv))
-		JsonbInitBinary(&jbv, json);
-
-	if (vars && !JsonContainerIsObject(&vars->root))
+	if (isJsonb)
 	{
-		ereport(ERROR,
-				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-				 errmsg("jsonb containing jsonpath variables "
-						"is not an object")));
+		if (!JsonbExtractScalar(&json->jb.root, jbv))
+			JsonbInitBinary(jbv, &json->jb);
+	}
+	else
+	{
+		if (!JsonExtractScalar(&json->js.root, jbv))
+			JsonInitBinary(jbv, &json->js);
 	}
 
 	cxt.vars = vars;
+	cxt.getVar = getVar;
 	cxt.laxMode = (path->header & JSONPATH_LAX) != 0;
 	cxt.ignoreStructuralErrors = cxt.laxMode;
-	cxt.root = &jbv;
-	cxt.current = &jbv;
+	cxt.root = &jsi;
+	cxt.stack = NULL;
 	cxt.baseObject.jbc = NULL;
 	cxt.baseObject.id = 0;
-	cxt.lastGeneratedObjectId = vars ? 2 : 1;
+	/* 1 + number of base objects in vars */
+	cxt.lastGeneratedObjectId = 1 + getVar(vars, isJsonb, NULL, 0, NULL, NULL);
 	cxt.innermostArraySize = -1;
 	cxt.throwErrors = throwErrors;
+	cxt.isJsonb = isJsonb;
+
+	pushJsonItem(&cxt.stack, &root, cxt.root);
 
 	if (jspStrictAbsenseOfErrors(&cxt) && !result)
 	{
@@ -520,7 +868,7 @@ executeJsonPath(JsonPath *path, Jsonb *vars, Jsonb *json, bool throwErrors,
 
 		Assert(!throwErrors);
 
-		res = recursiveExecute(&cxt, &jsp, &jbv, &vals);
+		res = recursiveExecute(&cxt, &jsp, &jsi, &vals);
 
 		if (jperIsError(res))
 			return res;
@@ -528,7 +876,7 @@ executeJsonPath(JsonPath *path, Jsonb *vars, Jsonb *json, bool throwErrors,
 		return JsonValueListIsEmpty(&vals) ? jperNotFound : jperOk;
 	}
 
-	res = recursiveExecute(&cxt, &jsp, &jbv, result);
+	res = recursiveExecute(&cxt, &jsp, &jsi, result);
 
 	Assert(!throwErrors || !jperIsError(res));
 
@@ -540,7 +888,7 @@ executeJsonPath(JsonPath *path, Jsonb *vars, Jsonb *json, bool throwErrors,
  */
 static JsonPathExecResult
 recursiveExecute(JsonPathExecContext *cxt, JsonPathItem *jsp,
-				 JsonbValue *jb, JsonValueList *found)
+				 JsonItem *jb, JsonValueList *found)
 {
 	return recursiveExecuteUnwrap(cxt, jsp, jb, jspAutoUnwrap(cxt), found);
 }
@@ -552,7 +900,7 @@ recursiveExecute(JsonPathExecContext *cxt, JsonPathItem *jsp,
  */
 static JsonPathExecResult
 recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
-					   JsonbValue *jb, bool unwrap, JsonValueList *found)
+					   JsonItem *jb, bool unwrap, JsonValueList *found)
 {
 	JsonPathItem elem;
 	JsonPathExecResult res = jperNotFound;
@@ -587,23 +935,16 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 		case jpiKey:
 			if (JsonbType(jb) == jbvObject)
 			{
-				JsonbValue *v;
-				JsonbValue	key;
-
-				key.type = jbvString;
-				key.val.string.val = jspGetString(jsp, &key.val.string.len);
+				JsonItem	val;
+				int			keylen;
+				char	   *key = jspGetString(jsp, &keylen);
 
-				v = findJsonbValueFromContainer(jb->val.binary.data,
-												JB_FOBJECT, &key);
+				jb = getJsonObjectKey(jb, key, keylen, cxt->isJsonb, &val);
 
-				if (v != NULL)
+				if (jb != NULL)
 				{
 					res = recursiveExecuteNext(cxt, jsp, NULL,
-											   v, found, false);
-
-					/* free value if it was not added to found list */
-					if (jspHasNext(jsp) || !found)
-						pfree(v);
+											   jb, found, true);
 				}
 				else if (!jspIgnoreStructuralErrors(cxt))
 				{
@@ -617,7 +958,7 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 
 					initStringInfo(&keybuf);
 
-					keystr = pnstrdup(key.val.string.val, key.val.string.len);
+					keystr = pnstrdup(key, keylen);
 					escape_json(&keybuf, keystr);
 
 					ereport(ERROR,
@@ -648,7 +989,7 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 			break;
 
 		case jpiCurrent:
-			res = recursiveExecuteNext(cxt, jsp, NULL, cxt->current,
+			res = recursiveExecuteNext(cxt, jsp, NULL, cxt->stack->item,
 									   found, true);
 			break;
 
@@ -675,7 +1016,7 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 			{
 				int			innermostArraySize = cxt->innermostArraySize;
 				int			i;
-				int			size = JsonbArraySize(jb);
+				int			size = JsonxArraySize(jb, cxt->isJsonb);
 				bool		singleton = size < 0;
 				bool		hasNext = jspGetNext(jsp, &elem);
 
@@ -729,30 +1070,27 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 
 					for (index = index_from; index <= index_to; index++)
 					{
-						JsonbValue *v;
-						bool		copy;
+						JsonItem	jsibuf;
+						JsonItem   *jsi;
 
 						if (singleton)
 						{
-							v = jb;
-							copy = true;
+							jsi = jb;
 						}
 						else
 						{
-							v = getIthJsonbValueFromContainer(jb->val.binary.data,
-															  (uint32) index);
+							jsi = getJsonArrayElement(jb, (uint32) index,
+													  cxt->isJsonb, &jsibuf);
 
-							if (v == NULL)
+							if (jsi == NULL)
 								continue;
-
-							copy = false;
 						}
 
 						if (!hasNext && !found)
 							return jperOk;
 
-						res = recursiveExecuteNext(cxt, jsp, &elem, v, found,
-												   copy);
+						res = recursiveExecuteNext(cxt, jsp, &elem, jsi, found,
+												   true);
 
 						if (jperIsError(res))
 							break;
@@ -782,8 +1120,8 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 
 		case jpiLast:
 			{
-				JsonbValue	tmpjbv;
-				JsonbValue *lastjbv;
+				JsonItem	tmpjsi;
+				JsonItem   *lastjsi;
 				int			last;
 				bool		hasNext = jspGetNext(jsp, &elem);
 
@@ -799,15 +1137,14 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 
 				last = cxt->innermostArraySize - 1;
 
-				lastjbv = hasNext ? &tmpjbv : palloc(sizeof(*lastjbv));
+				lastjsi = hasNext ? &tmpjsi : palloc(sizeof(*lastjsi));
 
-				lastjbv->type = jbvNumeric;
-				lastjbv->val.numeric =
-					DatumGetNumeric(DirectFunctionCall1(int4_numeric,
-														Int32GetDatum(last)));
+				JsonItemInitNumericDatum(lastjsi,
+										 DirectFunctionCall1(int4_numeric,
+															 Int32GetDatum(last)));
 
 				res = recursiveExecuteNext(cxt, jsp, &elem,
-										   lastjbv, found, hasNext);
+										   lastjsi, found, hasNext);
 			}
 			break;
 
@@ -816,11 +1153,12 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 			{
 				bool		hasNext = jspGetNext(jsp, &elem);
 
-				if (jb->type != jbvBinary)
-					elog(ERROR, "invalid jsonb object type: %d", jb->type);
+				if (!JsonItemIsBinary(jb))
+					elog(ERROR, "invalid jsonb object type: %d",
+						 JsonItemGetType(jb));
 
 				return recursiveAny(cxt, hasNext ? &elem : NULL,
-									jb->val.binary.data, found, 1, 1, 1,
+									JsonItemBinary(jb).data, found, 1, 1, 1,
 									false, jspAutoUnwrap(cxt));
 			}
 			else if (unwrap && JsonbType(jb) == jbvArray)
@@ -900,9 +1238,9 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 						break;
 				}
 
-				if (jb->type == jbvBinary)
+				if (JsonItemIsBinary(jb))
 					res = recursiveAny(cxt, hasNext ? &elem : NULL,
-									   jb->val.binary.data, found,
+									   JsonItemBinary(jb).data, found,
 									   1,
 									   jsp->content.anybounds.first,
 									   jsp->content.anybounds.last,
@@ -916,8 +1254,8 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 		case jpiString:
 		case jpiVariable:
 			{
-				JsonbValue	vbuf;
-				JsonbValue *v;
+				JsonItem	vbuf;
+				JsonItem   *v;
 				bool		hasNext = jspGetNext(jsp, &elem);
 
 				if (!hasNext && !found)
@@ -925,7 +1263,6 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 					res = jperOk;	/* skip evaluation */
 					break;
 				}
-
 				v = hasNext ? &vbuf : palloc(sizeof(*v));
 
 				baseObject = cxt->baseObject;
@@ -939,20 +1276,18 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 
 		case jpiType:
 			{
-				JsonbValue *jbv = palloc(sizeof(*jbv));
+				JsonItem	jsi;
+				const char *typname = JsonItemTypeName(jb);
 
-				jbv->type = jbvString;
-				jbv->val.string.val = pstrdup(JsonbTypeName(jb));
-				jbv->val.string.len = strlen(jbv->val.string.val);
+				JsonItemInitString(&jsi, pstrdup(typname), strlen(typname));
 
-				res = recursiveExecuteNext(cxt, jsp, NULL, jbv,
-										   found, false);
+				res = recursiveExecuteNext(cxt, jsp, NULL, &jsi, found, true);
 			}
 			break;
 
 		case jpiSize:
 			{
-				int			size = JsonbArraySize(jb);
+				int			size = JsonxArraySize(jb, cxt->isJsonb);
 
 				if (size < 0)
 				{
@@ -973,10 +1308,8 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 
 				jb = palloc(sizeof(*jb));
 
-				jb->type = jbvNumeric;
-				jb->val.numeric =
-					DatumGetNumeric(DirectFunctionCall1(int4_numeric,
-														Int32GetDatum(size)));
+				JsonItemInitNumericDatum(jb, DirectFunctionCall1(int4_numeric,
+																 Int32GetDatum(size)));
 
 				res = recursiveExecuteNext(cxt, jsp, NULL, jb, found, false);
 			}
@@ -996,16 +1329,16 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 
 		case jpiDouble:
 			{
-				JsonbValue	jbv;
+				JsonItem	jsi;
 
 				if (unwrap && JsonbType(jb) == jbvArray)
 					return recursiveExecuteUnwrapArray(cxt, jsp, jb, found,
 													   false);
 
-				if (jb->type == jbvNumeric)
+				if (JsonItemIsNumeric(jb))
 				{
 					char	   *tmp = DatumGetCString(DirectFunctionCall1(numeric_out,
-																		  NumericGetDatum(jb->val.numeric)));
+																		  NumericGetDatum(JsonItemNumeric(jb))));
 					bool		error = false;
 
 					(void) float8in_internal_error(tmp,
@@ -1024,13 +1357,13 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 
 					res = jperOk;
 				}
-				else if (jb->type == jbvString)
+				else if (JsonItemIsString(jb))
 				{
 					/* cast string as double */
 					bool		error = false;
 					double		val;
-					char	   *tmp = pnstrdup(jb->val.string.val,
-											   jb->val.string.len);
+					char	   *tmp = pnstrdup(JsonItemString(jb).val,
+											   JsonItemString(jb).len);
 
 					val = float8in_internal_error(tmp,
 												  NULL,
@@ -1046,10 +1379,9 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 														"applied to not a numeric value",
 														jspOperationName(jsp->type)))));
 
-					jb = &jbv;
-					jb->type = jbvNumeric;
-					jb->val.numeric = DatumGetNumeric(DirectFunctionCall1(float8_numeric,
-																		  Float8GetDatum(val)));
+					jb = &jsi;
+					JsonItemInitNumericDatum(jb, DirectFunctionCall1(float8_numeric,
+																	 Float8GetDatum(val)));
 					res = jperOk;
 				}
 
@@ -1089,8 +1421,8 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 													"applied to not a string",
 													jspOperationName(jsp->type)))));
 
-				datetime = cstring_to_text_with_len(jb->val.string.val,
-													jb->val.string.len);
+				datetime = cstring_to_text_with_len(JsonItemString(jb).val,
+													JsonItemString(jb).len);
 
 				if (jsp->content.args.left)
 				{
@@ -1110,7 +1442,7 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 					{
 						JsonValueList tzlist = {0};
 						JsonPathExecResult tzres;
-						JsonbValue *tzjbv;
+						JsonItem   *tzjsi;
 
 						jspGetRightArg(jsp, &elem);
 						tzres = recursiveExecute(cxt, &elem, jb, &tzlist);
@@ -1118,8 +1450,8 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 							return tzres;
 
 						if (JsonValueListLength(&tzlist) != 1 ||
-							((tzjbv = JsonValueListHead(&tzlist))->type != jbvString &&
-							 tzjbv->type != jbvNumeric))
+							(!JsonItemIsString((tzjsi = JsonValueListHead(&tzlist))) &&
+							 !JsonItemIsNumeric(tzjsi)))
 							RETURN_ERROR(ereport(ERROR,
 												 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_JSON_DATETIME_FUNCTION),
 												  errmsg(ERRMSG_INVALID_ARGUMENT_FOR_JSON_DATETIME_FUNCTION),
@@ -1128,14 +1460,14 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 															"is not a singleton string or number",
 															jspOperationName(jsp->type)))));
 
-						if (tzjbv->type == jbvString)
-							tzname = pnstrdup(tzjbv->val.string.val,
-											  tzjbv->val.string.len);
+						if (JsonItemIsString(tzjsi))
+							tzname = pnstrdup(JsonItemString(tzjsi).val,
+											  JsonItemString(tzjsi).len);
 						else
 						{
 							bool		error = false;
 
-							tz = numeric_int4_error(tzjbv->val.numeric, &error);
+							tz = numeric_int4_error(JsonItemNumeric(tzjsi), &error);
 
 							if (error || tz == PG_INT32_MIN)
 								RETURN_ERROR(ereport(ERROR,
@@ -1227,11 +1559,7 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 
 				jb = hasNext ? &jbvbuf : palloc(sizeof(*jb));
 
-				jb->type = jbvDatetime;
-				jb->val.datetime.value = value;
-				jb->val.datetime.typid = typid;
-				jb->val.datetime.typmod = typmod;
-				jb->val.datetime.tz = tz;
+				JsonItemInitDatetime(jb, value, typid, typmod, tz);
 
 				res = recursiveExecuteNext(cxt, jsp, &elem, jb, found, hasNext);
 			}
@@ -1255,16 +1583,16 @@ recursiveExecuteUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
  */
 static JsonPathExecResult
 recursiveExecuteUnwrapArray(JsonPathExecContext *cxt, JsonPathItem *jsp,
-							JsonbValue *jb, JsonValueList *found,
+							JsonItem *jb, JsonValueList *found,
 							bool unwrapElements)
 {
-	if (jb->type != jbvBinary)
+	if (!JsonItemIsBinary(jb))
 	{
-		Assert(jb->type != jbvArray);
-		elog(ERROR, "invalid jsonb array value type: %d", jb->type);
+		Assert(!JsonItemIsArray(jb));
+		elog(ERROR, "invalid jsonb array value type: %d", JsonItemGetType(jb));
 	}
 
-	return recursiveAny(cxt, jsp, jb->val.binary.data, found, 1, 1, 1,
+	return recursiveAny(cxt, jsp, JsonItemBinary(jb).data, found, 1, 1, 1,
 						false, unwrapElements);
 }
 
@@ -1274,7 +1602,7 @@ recursiveExecuteUnwrapArray(JsonPathExecContext *cxt, JsonPathItem *jsp,
 static JsonPathExecResult
 recursiveExecuteNext(JsonPathExecContext *cxt,
 					 JsonPathItem *cur, JsonPathItem *next,
-					 JsonbValue *v, JsonValueList *found, bool copy)
+					 JsonItem *v, JsonValueList *found, bool copy)
 {
 	JsonPathItem elem;
 	bool		hasNext;
@@ -1293,7 +1621,7 @@ recursiveExecuteNext(JsonPathExecContext *cxt,
 		return recursiveExecute(cxt, next, v, found);
 
 	if (found)
-		JsonValueListAppend(found, copy ? copyJsonbValue(v) : v);
+		JsonValueListAppend(found, copy ? copyJsonItem(v) : v);
 
 	return jperOk;
 }
@@ -1304,22 +1632,40 @@ recursiveExecuteNext(JsonPathExecContext *cxt,
  */
 static JsonPathExecResult
 recursiveExecuteAndUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
-						  JsonbValue *jb, bool unwrap, JsonValueList *found)
+						  JsonItem *jb, bool unwrap, JsonValueList *found)
 {
 	if (unwrap && jspAutoUnwrap(cxt))
 	{
 		JsonValueList seq = {0};
 		JsonValueListIterator it;
 		JsonPathExecResult res = recursiveExecute(cxt, jsp, jb, &seq);
-		JsonbValue *item;
+		JsonItem   *item;
+		int			count;
 
 		if (jperIsError(res))
 			return res;
 
+		count = JsonValueListLength(&seq);
+
+		if (!count)
+			return jperNotFound;
+
+		/* Optimize copying of singleton item into empty list */
+		if (count == 1 &&
+			JsonbType((item = JsonValueListHead(&seq))) != jbvArray)
+		{
+			if (JsonValueListIsEmpty(found))
+				*found = seq;
+			else
+				JsonValueListAppend(found, item);
+
+			return jperOk;
+		}
+
 		JsonValueListInitIterator(&seq, &it);
 		while ((item = JsonValueListNext(&seq, &it)))
 		{
-			Assert(item->type != jbvArray);
+			Assert(!JsonItemIsArray(item));
 
 			if (JsonbType(item) == jbvArray)
 				recursiveExecuteUnwrapArray(cxt, NULL, item, found, false);
@@ -1335,7 +1681,7 @@ recursiveExecuteAndUnwrap(JsonPathExecContext *cxt, JsonPathItem *jsp,
 
 static JsonPathExecResult
 recursiveExecuteAndUnwrapNoThrow(JsonPathExecContext *cxt, JsonPathItem *jsp,
-								 JsonbValue *jb, bool unwrap,
+								 JsonItem *jb, bool unwrap,
 								 JsonValueList *found)
 {
 	JsonPathExecResult res;
@@ -1351,7 +1697,7 @@ recursiveExecuteAndUnwrapNoThrow(JsonPathExecContext *cxt, JsonPathItem *jsp,
 /* Execute boolean-valued jsonpath expression. */
 static JsonPathBool
 recursiveExecuteBool(JsonPathExecContext *cxt, JsonPathItem *jsp,
-					 JsonbValue *jb, bool canHaveNext)
+					 JsonItem *jb, bool canHaveNext)
 {
 	JsonPathItem larg;
 	JsonPathItem rarg;
@@ -1482,15 +1828,14 @@ recursiveExecuteBool(JsonPathExecContext *cxt, JsonPathItem *jsp,
  */
 static JsonPathBool
 recursiveExecuteBoolNested(JsonPathExecContext *cxt, JsonPathItem *jsp,
-						   JsonbValue *jb)
+						   JsonItem *jb)
 {
-	JsonbValue *prev;
+	JsonItemStackEntry current;
 	JsonPathBool res;
 
-	prev = cxt->current;
-	cxt->current = jb;
+	pushJsonItem(&cxt->stack, &current, jb);
 	res = recursiveExecuteBool(cxt, jsp, jb, false);
-	cxt->current = prev;
+	popJsonItem(&cxt->stack);
 
 	return res;
 }
@@ -1507,25 +1852,26 @@ recursiveAny(JsonPathExecContext *cxt, JsonPathItem *jsp, JsonbContainer *jbc,
 			 bool ignoreStructuralErrors, bool unwrapNext)
 {
 	JsonPathExecResult res = jperNotFound;
-	JsonbIterator *it;
+	JsonxIterator it;
 	int32		r;
-	JsonbValue	v;
+	JsonItem	v;
 
 	check_stack_depth();
 
 	if (level > last)
 		return res;
 
-	it = JsonbIteratorInit(jbc);
+
+	JsonxIteratorInit(&it, jbc, cxt->isJsonb);
 
 	/*
 	 * Recursively iterate over jsonb objects/arrays
 	 */
-	while ((r = JsonbIteratorNext(&it, &v, true)) != WJB_DONE)
+	while ((r = JsonxIteratorNext(&it, JsonItemJbv(&v), true)) != WJB_DONE)
 	{
 		if (r == WJB_KEY)
 		{
-			r = JsonbIteratorNext(&it, &v, true);
+			r = JsonxIteratorNext(&it, JsonItemJbv(&v), true);
 			Assert(r == WJB_VALUE);
 		}
 
@@ -1534,7 +1880,7 @@ recursiveAny(JsonPathExecContext *cxt, JsonPathItem *jsp, JsonbContainer *jbc,
 
 			if (level >= first ||
 				(first == PG_UINT32_MAX && last == PG_UINT32_MAX &&
-				 v.type != jbvBinary))	/* leaves only requested */
+				 !JsonItemIsBinary(&v)))	/* leaves only requested */
 			{
 				/* check expression */
 				if (jsp)
@@ -1558,14 +1904,14 @@ recursiveAny(JsonPathExecContext *cxt, JsonPathItem *jsp, JsonbContainer *jbc,
 						break;
 				}
 				else if (found)
-					JsonValueListAppend(found, copyJsonbValue(&v));
+					JsonValueListAppend(found, copyJsonItem(&v));
 				else
 					return jperOk;
 			}
 
-			if (level < last && v.type == jbvBinary)
+			if (level < last && JsonItemIsBinary(&v))
 			{
-				res = recursiveAny(cxt, jsp, v.val.binary.data, found,
+				res = recursiveAny(cxt, jsp, JsonItemBinary(&v).data, found,
 								   level + 1, first, last,
 								   ignoreStructuralErrors, unwrapNext);
 
@@ -1593,7 +1939,7 @@ recursiveAny(JsonPathExecContext *cxt, JsonPathItem *jsp, JsonbContainer *jbc,
  */
 static JsonPathBool
 executePredicate(JsonPathExecContext *cxt, JsonPathItem *pred,
-				 JsonPathItem *larg, JsonPathItem *rarg, JsonbValue *jb,
+				 JsonPathItem *larg, JsonPathItem *rarg, JsonItem *jb,
 				 bool unwrapRightArg, JsonPathPredicateCallback exec,
 				 void *param)
 {
@@ -1601,7 +1947,7 @@ executePredicate(JsonPathExecContext *cxt, JsonPathItem *pred,
 	JsonValueListIterator lseqit;
 	JsonValueList lseq = {0};
 	JsonValueList rseq = {0};
-	JsonbValue *lval;
+	JsonItem *lval;
 	bool		error = false;
 	bool		found = false;
 
@@ -1623,7 +1969,7 @@ executePredicate(JsonPathExecContext *cxt, JsonPathItem *pred,
 	while ((lval = JsonValueListNext(&lseq, &lseqit)))
 	{
 		JsonValueListIterator rseqit;
-		JsonbValue *rval;
+		JsonItem   *rval;
 		bool		first = true;
 
 		if (rarg)
@@ -1633,6 +1979,7 @@ executePredicate(JsonPathExecContext *cxt, JsonPathItem *pred,
 		}
 		else
 		{
+			rseqit.next = NULL;
 			rval = NULL;
 		}
 
@@ -1677,15 +2024,15 @@ executePredicate(JsonPathExecContext *cxt, JsonPathItem *pred,
  */
 static JsonPathExecResult
 executeBinaryArithmExpr(JsonPathExecContext *cxt, JsonPathItem *jsp,
-						JsonbValue *jb, BinaryArithmFunc func,
+						JsonItem *jb, BinaryArithmFunc func,
 						JsonValueList *found)
 {
 	JsonPathExecResult jper;
 	JsonPathItem elem;
 	JsonValueList lseq = {0};
 	JsonValueList rseq = {0};
-	JsonbValue *lval;
-	JsonbValue *rval;
+	JsonItem   *lval;
+	JsonItem   *rval;
 	Numeric		res;
 
 	jspGetLeftArg(jsp, &elem);
@@ -1724,13 +2071,13 @@ executeBinaryArithmExpr(JsonPathExecContext *cxt, JsonPathItem *jsp,
 
 	if (jspThrowErrors(cxt))
 	{
-		res = func(lval->val.numeric, rval->val.numeric, NULL);
+		res = func(JsonItemNumeric(lval), JsonItemNumeric(rval), NULL);
 	}
 	else
 	{
 		bool	error = false;
 
-		res = func(lval->val.numeric, rval->val.numeric, &error);
+		res = func(JsonItemNumeric(lval), JsonItemNumeric(rval), &error);
 
 		if (error)
 			return jperError;
@@ -1740,8 +2087,7 @@ executeBinaryArithmExpr(JsonPathExecContext *cxt, JsonPathItem *jsp,
 		return jperOk;
 
 	lval = palloc(sizeof(*lval));
-	lval->type = jbvNumeric;
-	lval->val.numeric = res;
+	JsonItemInitNumeric(lval, res);
 
 	return recursiveExecuteNext(cxt, jsp, &elem, lval, found, false);
 }
@@ -1752,14 +2098,14 @@ executeBinaryArithmExpr(JsonPathExecContext *cxt, JsonPathItem *jsp,
  */
 static JsonPathExecResult
 executeUnaryArithmExpr(JsonPathExecContext *cxt, JsonPathItem *jsp,
-					   JsonbValue *jb, PGFunction func, JsonValueList *found)
+					   JsonItem *jb, PGFunction func, JsonValueList *found)
 {
 	JsonPathExecResult jper;
 	JsonPathExecResult jper2;
 	JsonPathItem elem;
 	JsonValueList seq = {0};
 	JsonValueListIterator it;
-	JsonbValue *val;
+	JsonItem   *val;
 	bool		hasNext;
 
 	jspGetArg(jsp, &elem);
@@ -1794,9 +2140,9 @@ executeUnaryArithmExpr(JsonPathExecContext *cxt, JsonPathItem *jsp,
 		}
 
 		if (func)
-			val->val.numeric =
+			JsonItemNumeric(val) =
 				DatumGetNumeric(DirectFunctionCall1(func,
-													NumericGetDatum(val->val.numeric)));
+													NumericGetDatum(JsonItemNumeric(val))));
 
 		jper2 = recursiveExecuteNext(cxt, jsp, &elem, val, found, false);
 
@@ -1820,7 +2166,7 @@ executeUnaryArithmExpr(JsonPathExecContext *cxt, JsonPathItem *jsp,
  * Check if the 'whole' string starts from 'initial' string.
  */
 static JsonPathBool
-executeStartsWith(JsonPathItem *jsp, JsonbValue *whole, JsonbValue *initial,
+executeStartsWith(JsonPathItem *jsp, JsonItem *whole, JsonItem *initial,
 				  void *param)
 {
 	if (!(whole = getScalar(whole, jbvString)))
@@ -1829,10 +2175,10 @@ executeStartsWith(JsonPathItem *jsp, JsonbValue *whole, JsonbValue *initial,
 	if (!(initial = getScalar(initial, jbvString)))
 		return jpbUnknown;		/* error */
 
-	if (whole->val.string.len >= initial->val.string.len &&
-		!memcmp(whole->val.string.val,
-				initial->val.string.val,
-				initial->val.string.len))
+	if (JsonItemString(whole).len >= JsonItemString(initial).len &&
+		!memcmp(JsonItemString(whole).val,
+				JsonItemString(initial).val,
+				JsonItemString(initial).len))
 		return jpbTrue;
 
 	return jpbFalse;
@@ -1844,7 +2190,7 @@ executeStartsWith(JsonPathItem *jsp, JsonbValue *whole, JsonbValue *initial,
  * Check if the string matches regex pattern.
  */
 static JsonPathBool
-executeLikeRegex(JsonPathItem *jsp, JsonbValue *str, JsonbValue *rarg,
+executeLikeRegex(JsonPathItem *jsp, JsonItem *str, JsonItem *rarg,
 				 void *param)
 {
 	JsonLikeRegexContext *cxt = param;
@@ -1874,8 +2220,8 @@ executeLikeRegex(JsonPathItem *jsp, JsonbValue *str, JsonbValue *rarg,
 			cxt->cflags |= REG_EXPANDED;
 	}
 
-	if (RE_compile_and_execute(cxt->regex, str->val.string.val,
-							   str->val.string.len,
+	if (RE_compile_and_execute(cxt->regex, JsonItemString(str).val,
+							   JsonItemString(str).len,
 							   cxt->cflags, DEFAULT_COLLATION_OID, 0, NULL))
 		return jpbTrue;
 
@@ -1884,7 +2230,7 @@ executeLikeRegex(JsonPathItem *jsp, JsonbValue *str, JsonbValue *rarg,
 
 static JsonPathExecResult
 executeNumericItemMethod(JsonPathExecContext *cxt, JsonPathItem *jsp,
-						 JsonbValue *jb, bool unwrap, PGFunction func,
+						 JsonItem *jb, bool unwrap, PGFunction func,
 						 JsonValueList *found)
 {
 	JsonPathItem next;
@@ -1901,15 +2247,14 @@ executeNumericItemMethod(JsonPathExecContext *cxt, JsonPathItem *jsp,
 										"not a numeric value",
 										jspOperationName(jsp->type)))));
 
-	datum = NumericGetDatum(jb->val.numeric);
+	datum = NumericGetDatum(JsonItemNumeric(jb));
 	datum = DirectFunctionCall1(func, datum);
 
 	if (!jspGetNext(jsp, &next) && !found)
 		return jperOk;
 
 	jb = palloc(sizeof(*jb));
-	jb->type = jbvNumeric;
-	jb->val.numeric = DatumGetNumeric(datum);
+	JsonItemInitNumericDatum(jb, datum);
 
 	return recursiveExecuteNext(cxt, jsp, &next, jb, found, false);
 }
@@ -1939,7 +2284,7 @@ executeNumericItemMethod(JsonPathExecContext *cxt, JsonPathItem *jsp,
  */
 static JsonPathExecResult
 executeKeyValueMethod(JsonPathExecContext *cxt, JsonPathItem *jsp,
-					  JsonbValue *jb, JsonValueList *found)
+					  JsonItem *jb, JsonValueList *found)
 {
 	JsonPathExecResult res = jperNotFound;
 	JsonPathItem next;
@@ -1950,12 +2295,13 @@ executeKeyValueMethod(JsonPathExecContext *cxt, JsonPathItem *jsp,
 	JsonbValue	keystr;
 	JsonbValue	valstr;
 	JsonbValue	idstr;
-	JsonbIterator *it;
+	JsonxIterator it;
 	JsonbIteratorToken tok;
+	JsonBuilderFunc push;
 	int64		id;
 	bool		hasNext;
 
-	if (JsonbType(jb) != jbvObject || jb->type != jbvBinary)
+	if (JsonbType(jb) != jbvObject || !JsonItemIsBinary(jb))
 		RETURN_ERROR(ereport(ERROR,
 							 (errcode(ERRCODE_JSON_OBJECT_NOT_FOUND),
 							  errmsg(ERRMSG_JSON_OBJECT_NOT_FOUND),
@@ -1963,7 +2309,7 @@ executeKeyValueMethod(JsonPathExecContext *cxt, JsonPathItem *jsp,
 										"to not an object",
 										jspOperationName(jsp->type)))));
 
-	jbc = jb->val.binary.data;
+	jbc = JsonItemBinary(jb).data;
 
 	if (!JsonContainerSize(jbc))
 		return jperNotFound;	/* no key-value pairs */
@@ -1983,23 +2329,29 @@ executeKeyValueMethod(JsonPathExecContext *cxt, JsonPathItem *jsp,
 	idstr.val.string.len = 2;
 
 	/* construct object id from its base object and offset inside that */
-	id = jb->type != jbvBinary ? 0 :
-		(int64) ((char *) jbc - (char *) cxt->baseObject.jbc);
+	id = cxt->isJsonb ?
+		(int64) ((char *)(JsonContainer *) jbc -
+				 (char *)(JsonContainer *) cxt->baseObject.jbc) :
+		(int64) (((JsonContainer *) jbc)->data -
+				 ((JsonContainer *) cxt->baseObject.jbc)->data);
+
 	id += (int64) cxt->baseObject.id * INT64CONST(10000000000);
 
 	idval.type = jbvNumeric;
 	idval.val.numeric = DatumGetNumeric(DirectFunctionCall1(int8_numeric,
 															Int64GetDatum(id)));
 
-	it = JsonbIteratorInit(jbc);
+	push = cxt->isJsonb ? pushJsonbValue : pushJsonValue;
 
-	while ((tok = JsonbIteratorNext(&it, &key, true)) != WJB_DONE)
+	JsonxIteratorInit(&it, jbc, cxt->isJsonb);
+
+	while ((tok = JsonxIteratorNext(&it, &key, true)) != WJB_DONE)
 	{
 		JsonBaseObjectInfo baseObject;
-		JsonbValue	obj;
+		JsonItem	obj;
 		JsonbParseState *ps;
 		JsonbValue *keyval;
-		Jsonb	   *jsonb;
+		Jsonx	   *jsonx;
 
 		if (tok != WJB_KEY)
 			continue;
@@ -2009,26 +2361,29 @@ executeKeyValueMethod(JsonPathExecContext *cxt, JsonPathItem *jsp,
 		if (!hasNext && !found)
 			break;
 
-		tok = JsonbIteratorNext(&it, &val, true);
+		tok = JsonxIteratorNext(&it, &val, true);
 		Assert(tok == WJB_VALUE);
 
 		ps = NULL;
-		pushJsonbValue(&ps, WJB_BEGIN_OBJECT, NULL);
+		push(&ps, WJB_BEGIN_OBJECT, NULL);
 
 		pushJsonbValue(&ps, WJB_KEY, &keystr);
 		pushJsonbValue(&ps, WJB_VALUE, &key);
 
 		pushJsonbValue(&ps, WJB_KEY, &valstr);
-		pushJsonbValue(&ps, WJB_VALUE, &val);
+		push(&ps, WJB_VALUE, &val);
 
 		pushJsonbValue(&ps, WJB_KEY, &idstr);
 		pushJsonbValue(&ps, WJB_VALUE, &idval);
 
 		keyval = pushJsonbValue(&ps, WJB_END_OBJECT, NULL);
 
-		jsonb = JsonbValueToJsonb(keyval);
+		jsonx = JsonbValueToJsonx(keyval, cxt->isJsonb);
 
-		JsonbInitBinary(&obj, jsonb);
+		if (cxt->isJsonb)
+			JsonbInitBinary(JsonItemJbv(&obj), &jsonx->jb);
+		else
+			JsonInitBinary(JsonItemJbv(&obj), &jsonx->js);
 
 		baseObject = setBaseObject(cxt, &obj, cxt->lastGeneratedObjectId++);
 
@@ -2055,22 +2410,17 @@ appendBoolResult(JsonPathExecContext *cxt, JsonPathItem *jsp,
 				 JsonValueList *found, JsonPathBool res)
 {
 	JsonPathItem next;
-	JsonbValue	jbv;
+	JsonItem	jsi;
 
 	if (!jspGetNext(jsp, &next) && !found)
 		return jperOk;			/* found singleton boolean value */
 
 	if (res == jpbUnknown)
-	{
-		jbv.type = jbvNull;
-	}
+		JsonItemInitNull(&jsi);
 	else
-	{
-		jbv.type = jbvBool;
-		jbv.val.boolean = res == jpbTrue;
-	}
+		JsonItemInitBool(&jsi, res == jpbTrue);
 
-	return recursiveExecuteNext(cxt, jsp, &next, &jbv, found, true);
+	return recursiveExecuteNext(cxt, jsp, &next, &jsi, found, true);
 }
 
 /*
@@ -2080,28 +2430,29 @@ appendBoolResult(JsonPathExecContext *cxt, JsonPathItem *jsp,
  */
 static void
 getJsonPathItem(JsonPathExecContext *cxt, JsonPathItem *item,
-				JsonbValue *value)
+				JsonItem *value)
 {
 	switch (item->type)
 	{
 		case jpiNull:
-			value->type = jbvNull;
+			JsonItemInitNull(value);
 			break;
 		case jpiBool:
-			value->type = jbvBool;
-			value->val.boolean = jspGetBool(item);
+			JsonItemInitBool(value, jspGetBool(item));
 			break;
 		case jpiNumeric:
-			value->type = jbvNumeric;
-			value->val.numeric = jspGetNumeric(item);
+			JsonItemInitNumeric(value, jspGetNumeric(item));
 			break;
 		case jpiString:
-			value->type = jbvString;
-			value->val.string.val = jspGetString(item,
-												 &value->val.string.len);
-			break;
+			{
+				int			len;
+				char	   *str = jspGetString(item, &len);
+
+				JsonItemInitString(value, str, len);
+				break;
+			}
 		case jpiVariable:
-			getJsonPathVariable(cxt, item, cxt->vars, value);
+			getJsonPathVariable(cxt, item, value);
 			return;
 		default:
 			elog(ERROR, "unexpected jsonpath item type");
@@ -2113,42 +2464,86 @@ getJsonPathItem(JsonPathExecContext *cxt, JsonPathItem *item,
  */
 static void
 getJsonPathVariable(JsonPathExecContext *cxt, JsonPathItem *variable,
-					Jsonb *vars, JsonbValue *value)
+					JsonItem *value)
 {
 	char	   *varName;
 	int			varNameLength;
-	JsonbValue	tmp;
-	JsonbValue *v;
+	JsonItem	baseObject;
+	int			baseObjectId;
 
-	if (!vars)
+	Assert(variable->type == jpiVariable);
+	varName = jspGetString(variable, &varNameLength);
+
+	if (!cxt->vars ||
+		(baseObjectId = cxt->getVar(cxt->vars, cxt->isJsonb,
+									varName, varNameLength,
+									value, JsonItemJbv(&baseObject))) < 0)
+		ereport(ERROR,
+				(errcode(ERRCODE_UNDEFINED_OBJECT),
+				 errmsg("cannot find jsonpath variable '%s'",
+						pnstrdup(varName, varNameLength))));
+
+	if (baseObjectId > 0)
+		setBaseObject(cxt, &baseObject, baseObjectId);
+}
+
+static int
+getJsonPathVariableFromJsonx(void *varsJsonx, bool isJsonb,
+							 char *varName, int varNameLength,
+							 JsonItem *value, JsonbValue *baseObject)
+{
+	Jsonx	   *vars = varsJsonx;
+	JsonbValue *val;
+	JsonbValue	key;
+
+	if (!varName)
 	{
-		value->type = jbvNull;
-		return;
+		if (vars &&
+			!(isJsonb ?
+			  JsonContainerIsObject(&vars->jb.root) :
+			  JsonContainerIsObject(&vars->js.root)))
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+					 errmsg("%s containing jsonpath variables is not an object",
+							isJsonb ? "jsonb" : "json")));
+
+		return vars ? 1 : 0;	/* count of base objects */
 	}
 
-	Assert(variable->type == jpiVariable);
-	varName = jspGetString(variable, &varNameLength);
-	tmp.type = jbvString;
-	tmp.val.string.val = varName;
-	tmp.val.string.len = varNameLength;
+	if (!vars)
+		return -1;
 
-	v = findJsonbValueFromContainer(&vars->root, JB_FOBJECT, &tmp);
+	key.type = jbvString;
+	key.val.string.val = varName;
+	key.val.string.len = varNameLength;
 
-	if (v)
+	if (isJsonb)
 	{
-		*value = *v;
-		pfree(v);
+		Jsonb	   *jb = &vars->jb;
+
+		val = findJsonbValueFromContainer(&jb->root, JB_FOBJECT, &key);
+
+		if (!val)
+			return -1;
+
+		JsonbInitBinary(baseObject, jb);
 	}
 	else
 	{
-		ereport(ERROR,
-				(errcode(ERRCODE_UNDEFINED_OBJECT),
-				 errmsg("cannot find jsonpath variable '%s'",
-						pnstrdup(varName, varNameLength))));
+		Json	   *js = &vars->js;
+
+		val = findJsonValueFromContainer(&js->root, JB_FOBJECT, &key);
+
+		if (!val)
+			return -1;
+
+		JsonInitBinary(baseObject, js);
 	}
 
-	JsonbInitBinary(&tmp, vars);
-	setBaseObject(cxt, &tmp, 1);
+	*JsonItemJbv(value) = *val;
+	pfree(val);
+
+	return 1;
 }
 
 /**************** Support functions for JsonPath execution *****************/
@@ -2157,16 +2552,26 @@ getJsonPathVariable(JsonPathExecContext *cxt, JsonPathItem *variable,
  * Returns the size of an array item, or -1 if item is not an array.
  */
 static int
-JsonbArraySize(JsonbValue *jb)
+JsonxArraySize(JsonItem *jb, bool isJsonb)
 {
-	Assert(jb->type != jbvArray);
+	Assert(!JsonItemIsArray(jb));
 
-	if (jb->type == jbvBinary)
+	if (JsonItemIsBinary(jb))
 	{
-		JsonbContainer *jbc = jb->val.binary.data;
+		if (isJsonb)
+		{
+			JsonbContainer *jbc = JsonItemBinary(jb).data;
 
-		if (JsonContainerIsArray(jbc) && !JsonContainerIsScalar(jbc))
-			return JsonContainerSize(jbc);
+			if (JsonContainerIsArray(jbc) && !JsonContainerIsScalar(jbc))
+				return JsonContainerSize(jbc);
+		}
+		else
+		{
+			JsonContainer *jc = (JsonContainer *) JsonItemBinary(jb).data;
+
+			if (JsonContainerIsArray(jc) && !JsonContainerIsScalar(jc))
+				return JsonTextContainerSize(jc);
+		}
 	}
 
 	return -1;
@@ -2174,7 +2579,7 @@ JsonbArraySize(JsonbValue *jb)
 
 /* Comparison predicate callback. */
 static JsonPathBool
-executeComparison(JsonPathItem *cmp, JsonbValue *lv, JsonbValue *rv, void *p)
+executeComparison(JsonPathItem *cmp, JsonItem *lv, JsonItem *rv, void *p)
 {
 	return compareItems(cmp->type, lv, rv);
 }
@@ -2183,14 +2588,16 @@ executeComparison(JsonPathItem *cmp, JsonbValue *lv, JsonbValue *rv, void *p)
  * Compare two SQL/JSON items using comparison operation 'op'.
  */
 static JsonPathBool
-compareItems(int32 op, JsonbValue *jb1, JsonbValue *jb2)
+compareItems(int32 op, JsonItem *jsi1, JsonItem *jsi2)
 {
+	JsonbValue *jb1 = JsonItemJbv(jsi1);
+	JsonbValue *jb2 = JsonItemJbv(jsi2);
 	int			cmp;
 	bool		res;
 
-	if (jb1->type != jb2->type)
+	if (JsonItemGetType(jsi1) != JsonItemGetType(jsi2))
 	{
-		if (jb1->type == jbvNull || jb2->type == jbvNull)
+		if (JsonItemIsNull(jsi1) || JsonItemIsNull(jsi2))
 
 			/*
 			 * Equality and order comparison of nulls to non-nulls returns
@@ -2202,7 +2609,7 @@ compareItems(int32 op, JsonbValue *jb1, JsonbValue *jb2)
 		return jpbUnknown;
 	}
 
-	switch (jb1->type)
+	switch (JsonItemGetType(jsi1))
 	{
 		case jbvNull:
 			cmp = 0;
@@ -2225,16 +2632,16 @@ compareItems(int32 op, JsonbValue *jb1, JsonbValue *jb2)
 							 jb2->val.string.val, jb2->val.string.len,
 							 DEFAULT_COLLATION_OID);
 			break;
-		case jbvDatetime:
+		case jsiDatetime:
 			{
 				bool		error = false;
 
-				cmp = compareDatetime(jb1->val.datetime.value,
-									  jb1->val.datetime.typid,
-									  jb1->val.datetime.tz,
-									  jb2->val.datetime.value,
-									  jb2->val.datetime.typid,
-									  jb2->val.datetime.tz,
+				cmp = compareDatetime(JsonItemDatetime(jsi1).value,
+									  JsonItemDatetime(jsi1).typid,
+									  JsonItemDatetime(jsi1).tz,
+									  JsonItemDatetime(jsi2).value,
+									  JsonItemDatetime(jsi2).typid,
+									  JsonItemDatetime(jsi2).tz,
 									  &error);
 
 				if (error)
@@ -2248,7 +2655,7 @@ compareItems(int32 op, JsonbValue *jb1, JsonbValue *jb2)
 			return jpbUnknown;	/* non-scalars are not comparable */
 
 		default:
-			elog(ERROR, "invalid jsonb value type %d", jb1->type);
+			elog(ERROR, "invalid jsonb value type %d", JsonItemGetType(jsi1));
 	}
 
 	switch (op)
@@ -2288,25 +2695,88 @@ compareNumeric(Numeric a, Numeric b)
 											 PointerGetDatum(b)));
 }
 
-static JsonbValue *
-copyJsonbValue(JsonbValue *src)
+static JsonItem *
+copyJsonItem(JsonItem *src)
 {
-	JsonbValue *dst = palloc(sizeof(*dst));
+	JsonItem *dst = palloc(sizeof(*dst));
 
 	*dst = *src;
 
 	return dst;
 }
 
+static JsonItem *
+JsonbValueToJsonItem(JsonbValue *jbv, JsonItem *jsi)
+{
+	*JsonItemJbv(jsi) = *jbv;
+	return jsi;
+}
+
+static JsonbValue *
+JsonItemToJsonbValue(JsonItem *jsi, JsonbValue *jbv)
+{
+	switch (JsonItemGetType(jsi))
+	{
+		case jsiDatetime:
+			jbv->type = jbvString;
+			jbv->val.string.val = JsonEncodeDateTime(NULL,
+													 JsonItemDatetime(jsi).value,
+													 JsonItemDatetime(jsi).typid,
+													 &JsonItemDatetime(jsi).tz);
+			jbv->val.string.len = strlen(jbv->val.string.val);
+			return jbv;
+
+		default:
+			return JsonItemJbv(jsi);
+	}
+}
+
+static Jsonb *
+JsonItemToJsonb(JsonItem *jsi)
+{
+	JsonbValue	jbv;
+
+	return JsonbValueToJsonb(JsonItemToJsonbValue(jsi, &jbv));
+}
+
+static const char *
+JsonItemTypeName(JsonItem *jsi)
+{
+	switch (JsonItemGetType(jsi))
+	{
+		case jsiDatetime:
+			switch (JsonItemDatetime(jsi).typid)
+			{
+				case DATEOID:
+					return "date";
+				case TIMEOID:
+					return "time without time zone";
+				case TIMETZOID:
+					return "time with time zone";
+				case TIMESTAMPOID:
+					return "timestamp without time zone";
+				case TIMESTAMPTZOID:
+					return "timestamp with time zone";
+				default:
+					elog(ERROR, "unrecognized jsonb value datetime type: %d",
+						 JsonItemDatetime(jsi).typid);
+					return "unknown";
+			}
+
+		default:
+			return JsonbTypeName(JsonItemJbv(jsi));
+	}
+}
+
 /*
  * Execute array subscript expression and convert resulting numeric item to
  * the integer type with truncation.
  */
 static JsonPathExecResult
-getArrayIndex(JsonPathExecContext *cxt, JsonPathItem *jsp, JsonbValue *jb,
+getArrayIndex(JsonPathExecContext *cxt, JsonPathItem *jsp, JsonItem *jb,
 			  int32 *index)
 {
-	JsonbValue *jbv;
+	JsonItem   *jbv;
 	JsonValueList found = {0};
 	JsonPathExecResult res = recursiveExecute(cxt, jsp, jb, &found);
 	Datum		numeric_index;
@@ -2324,7 +2794,7 @@ getArrayIndex(JsonPathExecContext *cxt, JsonPathItem *jsp, JsonbValue *jb,
 										"singleton numeric value"))));
 
 	numeric_index = DirectFunctionCall2(numeric_trunc,
-										NumericGetDatum(jbv->val.numeric),
+										NumericGetDatum(JsonItemNumeric(jbv)),
 										Int32GetDatum(0));
 
 	*index = numeric_int4_error(DatumGetNumeric(numeric_index), &error);
@@ -2341,95 +2811,82 @@ getArrayIndex(JsonPathExecContext *cxt, JsonPathItem *jsp, JsonbValue *jb,
 
 /* Save base object and its id needed for the execution of .keyvalue(). */
 static JsonBaseObjectInfo
-setBaseObject(JsonPathExecContext *cxt, JsonbValue *jbv, int32 id)
+setBaseObject(JsonPathExecContext *cxt, JsonItem *jbv, int32 id)
 {
 	JsonBaseObjectInfo baseObject = cxt->baseObject;
 
-	cxt->baseObject.jbc = jbv->type != jbvBinary ? NULL :
-		(JsonbContainer *) jbv->val.binary.data;
+	cxt->baseObject.jbc = !JsonItemIsBinary(jbv) ? NULL :
+		(JsonbContainer *) JsonItemBinary(jbv).data;
 	cxt->baseObject.id = id;
 
 	return baseObject;
 }
 
 static void
-JsonValueListAppend(JsonValueList *jvl, JsonbValue *jbv)
+JsonValueListAppend(JsonValueList *jvl, JsonItem *jsi)
 {
-	if (jvl->singleton)
+	jsi->next = NULL;
+
+	if (jvl->tail)
 	{
-		jvl->list = list_make2(jvl->singleton, jbv);
-		jvl->singleton = NULL;
+		jvl->tail->next = jsi;
+		jvl->tail = jsi;
 	}
-	else if (!jvl->list)
-		jvl->singleton = jbv;
 	else
-		jvl->list = lappend(jvl->list, jbv);
+	{
+		Assert(!jvl->head);
+		jvl->head = jvl->tail = jsi;
+	}
+
+	jvl->length++;
 }
 
 static int
 JsonValueListLength(const JsonValueList *jvl)
 {
-	return jvl->singleton ? 1 : list_length(jvl->list);
+	return jvl->length;
 }
 
 static bool
 JsonValueListIsEmpty(JsonValueList *jvl)
 {
-	return !jvl->singleton && list_length(jvl->list) <= 0;
+	return !jvl->length;
 }
 
-static JsonbValue *
+static JsonItem *
 JsonValueListHead(JsonValueList *jvl)
 {
-	return jvl->singleton ? jvl->singleton : linitial(jvl->list);
+	return jvl->head;
 }
 
 static List *
 JsonValueListGetList(JsonValueList *jvl)
 {
-	if (jvl->singleton)
-		return list_make1(jvl->singleton);
+	List	   *list = NIL;
+	JsonItem   *jsi;
 
-	return jvl->list;
+	for (jsi = jvl->head; jsi; jsi = jsi->next)
+		list = lappend(list, jsi);
+
+	return list;
 }
 
 static void
 JsonValueListInitIterator(const JsonValueList *jvl, JsonValueListIterator *it)
 {
-	if (jvl->singleton)
-	{
-		it->value = jvl->singleton;
-		it->next = NULL;
-	}
-	else if (list_head(jvl->list) != NULL)
-	{
-		it->value = (JsonbValue *) linitial(jvl->list);
-		it->next = lnext(list_head(jvl->list));
-	}
-	else
-	{
-		it->value = NULL;
-		it->next = NULL;
-	}
+	it->next = jvl->head;
 }
 
 /*
  * Get the next item from the sequence advancing iterator.
  */
-static JsonbValue *
+static JsonItem *
 JsonValueListNext(const JsonValueList *jvl, JsonValueListIterator *it)
 {
-	JsonbValue *result = it->value;
+	JsonItem   *result = it->next;
 
-	if (it->next)
-	{
-		it->value = lfirst(it->next);
-		it->next = lnext(it->next);
-	}
-	else
-	{
-		it->value = NULL;
-	}
+	if (result)
+		it->next = result->next;
 
 	return result;
 }
@@ -2448,16 +2905,29 @@ JsonbInitBinary(JsonbValue *jbv, Jsonb *jb)
 }
 
 /*
+ * Initialize a binary JsonbValue with the given json container.
+ */
+static inline JsonbValue *
+JsonInitBinary(JsonbValue *jbv, Json *js)
+{
+	jbv->type = jbvBinary;
+	jbv->val.binary.data = (void *) &js->root;
+	jbv->val.binary.len = js->root.len;
+
+	return jbv;
+}
+
+/*
  * Returns jbv* type of of JsonbValue. Note, it never returns jbvBinary as is.
  */
 static int
-JsonbType(JsonbValue *jb)
+JsonbType(JsonItem *jb)
 {
-	int			type = jb->type;
+	int			type = JsonItemGetType(jb);
 
-	if (jb->type == jbvBinary)
+	if (type == jbvBinary)
 	{
-		JsonbContainer *jbc = (void *) jb->val.binary.data;
+		JsonbContainer *jbc = (void *) JsonItemBinary(jb).data;
 
 		/* Scalars should be always extracted during jsonpath execution. */
 		Assert(!JsonContainerIsScalar(jbc));
@@ -2473,32 +2943,204 @@ JsonbType(JsonbValue *jb)
 	return type;
 }
 
+/*
+ * Convert jsonb to a C-string stripping quotes from scalar strings.
+ */
+static char *
+JsonbValueUnquote(JsonbValue *jbv, int *len, bool isJsonb)
+{
+	switch (jbv->type)
+	{
+		case jbvString:
+			*len = jbv->val.string.len;
+			return jbv->val.string.val;
+
+		case jbvBool:
+			*len = jbv->val.boolean ? 4 : 5;
+			return jbv->val.boolean ? "true" : "false";
+
+		case jbvNumeric:
+			*len = -1;
+			return DatumGetCString(DirectFunctionCall1(numeric_out,
+													   PointerGetDatum(jbv->val.numeric)));
+
+		case jbvNull:
+			*len = 4;
+			return "null";
+
+		case jbvBinary:
+			{
+				JsonbValue	jbvbuf;
+
+				if (isJsonb ?
+					JsonbExtractScalar(jbv->val.binary.data, &jbvbuf) :
+					JsonExtractScalar((JsonContainer *) jbv->val.binary.data, &jbvbuf))
+					return JsonbValueUnquote(&jbvbuf, len, isJsonb);
+
+				*len = -1;
+				return isJsonb ?
+					JsonbToCString(NULL, jbv->val.binary.data, jbv->val.binary.len) :
+					JsonToCString(NULL, (JsonContainer *) jbv->val.binary.data, jbv->val.binary.len);
+			}
+
+		default:
+			elog(ERROR, "unexpected jsonb value type: %d", jbv->type);
+			return NULL;
+	}
+}
+
+static char *
+JsonItemUnquote(JsonItem *jsi, int *len, bool isJsonb)
+{
+	switch (JsonItemGetType(jsi))
+	{
+		case jsiDatetime:
+			*len = -1;
+			return JsonEncodeDateTime(NULL,
+									  JsonItemDatetime(jsi).value,
+									  JsonItemDatetime(jsi).typid,
+									  &JsonItemDatetime(jsi).tz);
+
+		default:
+			return JsonbValueUnquote(JsonItemJbv(jsi), len, isJsonb);
+	}
+}
+
+static text *
+JsonItemUnquoteText(JsonItem *jsi, bool isJsonb)
+{
+	int			len;
+	char	   *str = JsonItemUnquote(jsi, &len, isJsonb);
+
+	if (len < 0)
+		return cstring_to_text(str);
+	else
+		return cstring_to_text_with_len(str, len);
+}
+
+static JsonItem *
+getJsonObjectKey(JsonItem *jsi, char *keystr, int keylen, bool isJsonb,
+				 JsonItem *res)
+{
+	JsonbContainer *jbc = JsonItemBinary(jsi).data;
+	JsonbValue *val;
+	JsonbValue	key;
+
+	key.type = jbvString;
+	key.val.string.val = keystr;
+	key.val.string.len = keylen;
+
+	val = isJsonb ?
+		findJsonbValueFromContainer(jbc, JB_FOBJECT, &key) :
+		findJsonValueFromContainer((JsonContainer *) jbc, JB_FOBJECT, &key);
+
+	return val ? JsonbValueToJsonItem(val, res) : NULL;
+}
+
+static JsonItem *
+getJsonArrayElement(JsonItem *jb, uint32 index, bool isJsonb, JsonItem *res)
+{
+	JsonbContainer *jbc = JsonItemBinary(jb).data;
+	JsonbValue *elem = isJsonb ?
+		getIthJsonbValueFromContainer(jbc, index) :
+		getIthJsonValueFromContainer((JsonContainer *) jbc, index);
+
+	return elem ? JsonbValueToJsonItem(elem, res) : NULL;
+}
+
+static inline void
+JsonxIteratorInit(JsonxIterator *it, JsonxContainer *jxc, bool isJsonb)
+{
+	it->isJsonb = isJsonb;
+	if (isJsonb)
+		it->it.jb = JsonbIteratorInit((JsonbContainer *) jxc);
+	else
+		it->it.js = JsonIteratorInit((JsonContainer *) jxc);
+}
+
+static JsonbIteratorToken
+JsonxIteratorNext(JsonxIterator *it, JsonbValue *jbv, bool skipNested)
+{
+	return it->isJsonb ?
+		JsonbIteratorNext(&it->it.jb, jbv, skipNested) :
+		JsonIteratorNext(&it->it.js, jbv, skipNested);
+}
+
+static Json *
+JsonItemToJson(JsonItem *jsi)
+{
+	JsonbValue	jbv;
+
+	return JsonbValueToJson(JsonItemToJsonbValue(jsi, &jbv));
+}
+
+static Jsonx *
+JsonbValueToJsonx(JsonbValue *jbv, bool isJsonb)
+{
+	return isJsonb ?
+		(Jsonx *) JsonbValueToJsonb(jbv) :
+		(Jsonx *) JsonbValueToJson(jbv);
+}
+
+static Datum
+JsonbValueToJsonxDatum(JsonbValue *jbv, bool isJsonb)
+{
+	return isJsonb ?
+		JsonbPGetDatum(JsonbValueToJsonb(jbv)) :
+		JsonPGetDatum(JsonbValueToJson(jbv));
+}
+
+static Datum
+JsonItemToJsonxDatum(JsonItem *jsi, bool isJsonb)
+{
+	JsonbValue	jbv;
+
+	return JsonbValueToJsonxDatum(JsonItemToJsonbValue(jsi, &jbv), isJsonb);
+}
+
 /* Get scalar of given type or NULL on type mismatch */
-static JsonbValue *
-getScalar(JsonbValue *scalar, enum jbvType type)
+static JsonItem *
+getScalar(JsonItem *scalar, enum jbvType type)
 {
 	/* Scalars should be always extracted during jsonpath execution. */
-	Assert(scalar->type != jbvBinary ||
-		   !JsonContainerIsScalar(scalar->val.binary.data));
+	Assert(!JsonItemIsBinary(scalar) ||
+		   !JsonContainerIsScalar(JsonItemBinary(scalar).data));
 
-	return scalar->type == type ? scalar : NULL;
+	return JsonItemGetType(scalar) == type ? scalar : NULL;
 }
 
 /* Construct a JSON array from the item list */
 static JsonbValue *
-wrapItemsInArray(const JsonValueList *items)
+wrapItemsInArray(const JsonValueList *items, bool isJsonb)
 {
 	JsonbParseState *ps = NULL;
 	JsonValueListIterator it;
-	JsonbValue *jbv;
+	JsonItem   *jsi;
+	JsonbValue	jbv;
+	JsonBuilderFunc push = isJsonb ? pushJsonbValue : pushJsonValue;
 
-	pushJsonbValue(&ps, WJB_BEGIN_ARRAY, NULL);
+	push(&ps, WJB_BEGIN_ARRAY, NULL);
 
 	JsonValueListInitIterator(items, &it);
-	while ((jbv = JsonValueListNext(items, &it)))
-		pushJsonbValue(&ps, WJB_ELEM, jbv);
 
-	return pushJsonbValue(&ps, WJB_END_ARRAY, NULL);
+	while ((jsi = JsonValueListNext(items, &it)))
+		push(&ps, WJB_ELEM, JsonItemToJsonbValue(jsi, &jbv));
+
+	return push(&ps, WJB_END_ARRAY, NULL);
+}
+
+static void
+pushJsonItem(JsonItemStack *stack, JsonItemStackEntry *entry, JsonItem *item)
+{
+	entry->item = item;
+	entry->parent = *stack;
+	*stack = entry;
+}
+
+static void
+popJsonItem(JsonItemStack *stack)
+{
+	*stack = (*stack)->parent;
 }
 
 static inline Datum
@@ -2739,3 +3381,43 @@ tryToParseDatetime(text *fmt, text *datetime, char *tzname, bool strict,
 
 	return !error;
 }
+
+static void
+JsonItemInitNull(JsonItem *item)
+{
+	item->val.type = jbvNull;
+}
+
+static void
+JsonItemInitBool(JsonItem *item, bool val)
+{
+	item->val.type = jbvBool;
+	JsonItemBool(item) = val;
+}
+
+static void
+JsonItemInitNumeric(JsonItem *item, Numeric val)
+{
+	item->val.type = jbvNumeric;
+	JsonItemNumeric(item) = val;
+}
+
+#define JsonItemInitNumericDatum(item, val) JsonItemInitNumeric(item, DatumGetNumeric(val))
+
+static void
+JsonItemInitString(JsonItem *item, char *str, int len)
+{
+	item->val.type = jbvString;
+	JsonItemString(item).val = str;
+	JsonItemString(item).len = len;
+}
+
+static void
+JsonItemInitDatetime(JsonItem *item, Datum val, Oid typid, int32 typmod, int tz)
+{
+	item->val.type = jsiDatetime;
+	JsonItemDatetime(item).value = val;
+	JsonItemDatetime(item).typid = typid;
+	JsonItemDatetime(item).typmod = typmod;
+	JsonItemDatetime(item).tz = tz;
+}
diff --git a/src/include/catalog/pg_operator.dat b/src/include/catalog/pg_operator.dat
index 1c7af92..5e249dd 100644
--- a/src/include/catalog/pg_operator.dat
+++ b/src/include/catalog/pg_operator.dat
@@ -3263,5 +3263,13 @@
   oprname => '@@', oprleft => 'jsonb', oprright => 'jsonpath',
   oprresult => 'bool', oprcode => 'jsonb_path_match(jsonb,jsonpath)',
   oprrest => 'contsel', oprjoin => 'contjoinsel' },
+{ oid => '6071', descr => 'jsonpath exists',
+  oprname => '@?', oprleft => 'json', oprright => 'jsonpath',
+  oprresult => 'bool', oprcode => 'json_path_exists(json,jsonpath)',
+  oprrest => 'contsel', oprjoin => 'contjoinsel' },
+{ oid => '6108', descr => 'jsonpath predicate',
+  oprname => '@@', oprleft => 'json', oprright => 'jsonpath',
+  oprresult => 'bool', oprcode => 'json_path_match(json,jsonpath)',
+  oprrest => 'contsel', oprjoin => 'contjoinsel' },
 
 ]
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 9a7a5db..4f80b95 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -9213,6 +9213,10 @@
 { oid => '6057', descr => 'jsonpath query first item',
   proname => 'jsonb_path_query_first', prorettype => 'jsonb',
   proargtypes => 'jsonb jsonpath jsonb bool', prosrc => 'jsonb_path_query_first' },
+{ oid => '6127', descr => 'jsonpath query first item text',
+  proname => 'jsonb_path_query_first_text', prorettype => 'text',
+  proargtypes => 'jsonb jsonpath jsonb bool',
+  prosrc => 'jsonb_path_query_first_text' },
 { oid => '6058', descr => 'jsonpath match', proname => 'jsonb_path_match',
   prorettype => 'bool', proargtypes => 'jsonb jsonpath jsonb bool',
   prosrc => 'jsonb_path_match' },
@@ -9224,6 +9228,36 @@
   proname => 'jsonb_path_match', prorettype => 'bool',
   proargtypes => 'jsonb jsonpath', prosrc => 'jsonb_path_match_opr' },
 
+{ oid => '6043', descr => 'implementation of @? operator',
+  proname => 'json_path_exists', prorettype => 'bool',
+  proargtypes => 'json jsonpath', prosrc => 'json_path_exists_opr' },
+{ oid => '6047', descr => 'implementation of @@ operator',
+  proname => 'json_path_match', prorettype => 'bool',
+  proargtypes => 'json jsonpath', prosrc => 'json_path_match_opr' },
+
+{ oid => '6045', descr => 'jsonpath exists test',
+  proname => 'json_path_exists', prorettype => 'bool',
+  proargtypes => 'json jsonpath json bool', prosrc => 'json_path_exists' },
+{ oid => '6046', descr => 'jsonpath query',
+  proname => 'json_path_query', prorows => '1000', proretset => 't',
+  prorettype => 'json', proargtypes => 'json jsonpath json bool',
+  prosrc => 'json_path_query' },
+{ oid => '6129', descr => 'jsonpath query with conditional wrapper',
+  proname => 'json_path_query_array', prorettype => 'json',
+  proargtypes => 'json jsonpath json bool',
+  prosrc => 'json_path_query_array' },
+{ oid => '6069', descr => 'jsonpath match test',
+  proname => 'json_path_match', prorettype => 'bool',
+  proargtypes => 'json jsonpath json bool', prosrc => 'json_path_match' },
+{ oid => '6109', descr => 'jsonpath query first item',
+  proname => 'json_path_query_first', prorettype => 'json',
+  proargtypes => 'json jsonpath json bool',
+  prosrc => 'json_path_query_first' },
+{ oid => '6044', descr => 'jsonpath query first item text',
+  proname => 'json_path_query_first_text', prorettype => 'text',
+  proargtypes => 'json jsonpath json bool',
+  prosrc => 'json_path_query_first_text' },
+
 # txid
 { oid => '2939', descr => 'I/O',
   proname => 'txid_snapshot_in', prorettype => 'txid_snapshot',
diff --git a/src/include/utils/jsonapi.h b/src/include/utils/jsonapi.h
index 9eda9a3..5535aba2 100644
--- a/src/include/utils/jsonapi.h
+++ b/src/include/utils/jsonapi.h
@@ -15,6 +15,7 @@
 #define JSONAPI_H
 
 #include "jsonb.h"
+#include "access/htup.h"
 #include "lib/stringinfo.h"
 
 typedef enum
@@ -93,6 +94,56 @@ typedef struct JsonSemAction
 	json_scalar_action scalar;
 } JsonSemAction;
 
+typedef enum
+{
+	JTI_ARRAY_START,
+	JTI_ARRAY_ELEM,
+	JTI_ARRAY_ELEM_SCALAR,
+	JTI_ARRAY_ELEM_AFTER,
+	JTI_ARRAY_END,
+	JTI_OBJECT_START,
+	JTI_OBJECT_KEY,
+	JTI_OBJECT_VALUE,
+	JTI_OBJECT_VALUE_AFTER,
+} JsontIterState;
+
+typedef struct JsonContainerData
+{
+	uint32		header;
+	int			len;
+	char	   *data;
+} JsonContainerData;
+
+typedef const JsonContainerData JsonContainer;
+
+#define JsonTextContainerSize(jc) \
+	(((jc)->header & JB_CMASK) == JB_CMASK && JsonContainerIsArray(jc) \
+	 ? JsonGetArraySize(jc) : (jc)->header & JB_CMASK)
+
+typedef struct Json
+{
+	JsonContainer root;
+} Json;
+
+typedef struct JsonIterator
+{
+	struct JsonIterator	*parent;
+	JsonContainer *container;
+	JsonLexContext *lex;
+	JsontIterState state;
+	bool		isScalar;
+} JsonIterator;
+
+#define DatumGetJsonP(datum) JsonCreate(DatumGetTextP(datum))
+#define DatumGetJsonPCopy(datum) JsonCreate(DatumGetTextPCopy(datum))
+
+#define JsonPGetDatum(json) \
+	PointerGetDatum(cstring_to_text_with_len((json)->root.data, (json)->root.len))
+
+#define PG_GETARG_JSON_P(n)			DatumGetJsonP(PG_GETARG_DATUM(n))
+#define PG_GETARG_JSON_P_COPY(n)	DatumGetJsonPCopy(PG_GETARG_DATUM(n))
+#define PG_RETURN_JSON_P(json)		PG_RETURN_DATUM(JsonPGetDatum(json))
+
 /*
  * parse_json will parse the string in the lex calling the
  * action functions in sem at the appropriate points. It is
@@ -164,4 +215,22 @@ extern text *transform_json_string_values(text *json, void *action_state,
 extern char *JsonEncodeDateTime(char *buf, Datum value, Oid typid,
 				   const int *tzp);
 
+extern Json *JsonCreate(text *json);
+extern JsonbIteratorToken JsonIteratorNext(JsonIterator **pit, JsonbValue *val,
+				 bool skipNested);
+extern JsonIterator *JsonIteratorInit(JsonContainer *jc);
+extern void JsonIteratorFree(JsonIterator *it);
+extern uint32 JsonGetArraySize(JsonContainer *jc);
+extern Json *JsonbValueToJson(JsonbValue *jbv);
+extern bool JsonExtractScalar(JsonContainer *jbc, JsonbValue *res);
+extern char *JsonUnquote(Json *jb);
+extern char *JsonToCString(StringInfo out, JsonContainer *jc,
+			  int estimated_len);
+extern JsonbValue *pushJsonValue(JsonbParseState **pstate,
+			  JsonbIteratorToken tok, JsonbValue *jbv);
+extern JsonbValue *findJsonValueFromContainer(JsonContainer *jc, uint32 flags,
+						   JsonbValue *key);
+extern JsonbValue *getIthJsonValueFromContainer(JsonContainer *array,
+							 uint32 index);
+
 #endif							/* JSONAPI_H */
diff --git a/src/include/utils/jsonb.h b/src/include/utils/jsonb.h
index 9698c46..a5d1df4 100644
--- a/src/include/utils/jsonb.h
+++ b/src/include/utils/jsonb.h
@@ -221,10 +221,10 @@ typedef struct
 } Jsonb;
 
 /* convenience macros for accessing the root container in a Jsonb datum */
-#define JB_ROOT_COUNT(jbp_)		(*(uint32 *) VARDATA(jbp_) & JB_CMASK)
-#define JB_ROOT_IS_SCALAR(jbp_) ((*(uint32 *) VARDATA(jbp_) & JB_FSCALAR) != 0)
-#define JB_ROOT_IS_OBJECT(jbp_) ((*(uint32 *) VARDATA(jbp_) & JB_FOBJECT) != 0)
-#define JB_ROOT_IS_ARRAY(jbp_)	((*(uint32 *) VARDATA(jbp_) & JB_FARRAY) != 0)
+#define JB_ROOT_COUNT(jbp_)		JsonContainerSize(&(jbp_)->root)
+#define JB_ROOT_IS_SCALAR(jbp_) JsonContainerIsScalar(&(jbp_)->root)
+#define JB_ROOT_IS_OBJECT(jbp_) JsonContainerIsObject(&(jbp_)->root)
+#define JB_ROOT_IS_ARRAY(jbp_)	JsonContainerIsArray(&(jbp_)->root)
 
 
 enum jbvType
@@ -239,14 +239,6 @@ enum jbvType
 	jbvObject,
 	/* Binary (i.e. struct Jsonb) jbvArray/jbvObject */
 	jbvBinary,
-
-	/*
-	 * Virtual types.
-	 *
-	 * These types are used only for in-memory JSON processing and serialized
-	 * into JSON strings when outputted to json/jsonb.
-	 */
-	jbvDatetime = 0x20,
 };
 
 /*
@@ -280,6 +272,8 @@ struct JsonbValue
 		{
 			int			nPairs; /* 1 pair, 2 elements */
 			JsonbPair  *pairs;
+			bool		uniquify;	/* Should we sort pairs by key name and
+									 * remove duplicate keys? */
 		}			object;		/* Associative container type */
 
 		struct
@@ -287,20 +281,11 @@ struct JsonbValue
 			int			len;
 			JsonbContainer *data;
 		}			binary;		/* Array or object, in on-disk format */
-
-		struct
-		{
-			Datum		value;
-			Oid			typid;
-			int32		typmod;
-			int			tz;
-		}			datetime;
 	}			val;
 };
 
 #define IsAJsonbScalar(jsonbval)	(((jsonbval)->type >= jbvNull && \
-									  (jsonbval)->type <= jbvBool) || \
-									  (jsonbval)->type == jbvDatetime)
+									  (jsonbval)->type <= jbvBool))
 
 /*
  * Key/value pair within an Object.
@@ -374,6 +359,8 @@ typedef struct JsonbIterator
 /* Support functions */
 extern uint32 getJsonbOffset(const JsonbContainer *jc, int index);
 extern uint32 getJsonbLength(const JsonbContainer *jc, int index);
+extern int lengthCompareJsonbStringValue(const void *a, const void *b);
+extern bool equalsJsonbScalarValue(JsonbValue *a, JsonbValue *b);
 extern int	compareJsonbContainers(JsonbContainer *a, JsonbContainer *b);
 extern JsonbValue *findJsonbValueFromContainer(JsonbContainer *sheader,
 							uint32 flags,
@@ -382,6 +369,8 @@ extern JsonbValue *getIthJsonbValueFromContainer(JsonbContainer *sheader,
 							  uint32 i);
 extern JsonbValue *pushJsonbValue(JsonbParseState **pstate,
 			   JsonbIteratorToken seq, JsonbValue *jbVal);
+extern JsonbValue *pushJsonbValueScalar(JsonbParseState **pstate,
+					 JsonbIteratorToken seq,JsonbValue *scalarVal);
 extern JsonbIterator *JsonbIteratorInit(JsonbContainer *container);
 extern JsonbIteratorToken JsonbIteratorNext(JsonbIterator **it, JsonbValue *val,
 				  bool skipNested);
diff --git a/src/test/regress/expected/json_jsonpath.out b/src/test/regress/expected/json_jsonpath.out
new file mode 100644
index 0000000..220025d
--- /dev/null
+++ b/src/test/regress/expected/json_jsonpath.out
@@ -0,0 +1,2120 @@
+select json '{"a": 12}' @? '$';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"a": 12}' @? '1';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"a": 12}' @? '$.a.b';
+ ?column? 
+----------
+ f
+(1 row)
+
+select json '{"a": 12}' @? '$.b';
+ ?column? 
+----------
+ f
+(1 row)
+
+select json '{"a": 12}' @? '$.a + 2';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"a": 12}' @? '$.b + 2';
+ ?column? 
+----------
+ 
+(1 row)
+
+select json '{"a": {"a": 12}}' @? '$.a.a';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"a": {"a": 12}}' @? '$.*.a';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"b": {"a": 12}}' @? '$.*.a';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"b": {"a": 12}}' @? '$.*.b';
+ ?column? 
+----------
+ f
+(1 row)
+
+select json '{"b": {"a": 12}}' @? 'strict $.*.b';
+ ?column? 
+----------
+ 
+(1 row)
+
+select json '{}' @? '$.*';
+ ?column? 
+----------
+ f
+(1 row)
+
+select json '{"a": 1}' @? '$.*';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"a": {"b": 1}}' @? 'lax $.**{1}';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"a": {"b": 1}}' @? 'lax $.**{2}';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"a": {"b": 1}}' @? 'lax $.**{3}';
+ ?column? 
+----------
+ f
+(1 row)
+
+select json '[]' @? '$[*]';
+ ?column? 
+----------
+ f
+(1 row)
+
+select json '[1]' @? '$[*]';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '[1]' @? '$[1]';
+ ?column? 
+----------
+ f
+(1 row)
+
+select json '[1]' @? 'strict $[1]';
+ ?column? 
+----------
+ 
+(1 row)
+
+select json_path_query('[1]', 'strict $[1]');
+ERROR:  invalid SQL/JSON subscript
+DETAIL:  jsonpath array subscript is out of bounds
+select json '[1]' @? 'lax $[10000000000000000]';
+ ?column? 
+----------
+ 
+(1 row)
+
+select json '[1]' @? 'strict $[10000000000000000]';
+ ?column? 
+----------
+ 
+(1 row)
+
+select json_path_query('[1]', 'lax $[10000000000000000]');
+ERROR:  invalid SQL/JSON subscript
+DETAIL:  jsonpath array subscript is out of integer range
+select json_path_query('[1]', 'strict $[10000000000000000]');
+ERROR:  invalid SQL/JSON subscript
+DETAIL:  jsonpath array subscript is out of integer range
+select json '[1]' @? '$[0]';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '[1]' @? '$[0.3]';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '[1]' @? '$[0.5]';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '[1]' @? '$[0.9]';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '[1]' @? '$[1.2]';
+ ?column? 
+----------
+ f
+(1 row)
+
+select json '[1]' @? 'strict $[1.2]';
+ ?column? 
+----------
+ 
+(1 row)
+
+select json '{"a": [1,2,3], "b": [3,4,5]}' @? '$ ? (@.a[*] >  @.b[*])';
+ ?column? 
+----------
+ f
+(1 row)
+
+select json '{"a": [1,2,3], "b": [3,4,5]}' @? '$ ? (@.a[*] >= @.b[*])';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"a": [1,2,3], "b": [3,4,"5"]}' @? '$ ? (@.a[*] >= @.b[*])';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"a": [1,2,3], "b": [3,4,"5"]}' @? 'strict $ ? (@.a[*] >= @.b[*])';
+ ?column? 
+----------
+ f
+(1 row)
+
+select json '{"a": [1,2,3], "b": [3,4,null]}' @? '$ ? (@.a[*] >= @.b[*])';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '1' @? '$ ? ((@ == "1") is unknown)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '1' @? '$ ? ((@ == 1) is unknown)';
+ ?column? 
+----------
+ f
+(1 row)
+
+select json '[{"a": 1}, {"a": 2}]' @? '$[0 to 1] ? (@.a > 1)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json_path_query('1', 'lax $.a');
+ json_path_query 
+-----------------
+(0 rows)
+
+select json_path_query('1', 'strict $.a');
+ERROR:  SQL/JSON member not found
+DETAIL:  jsonpath member accessor is applied to not an object
+select json_path_query('1', 'strict $.*');
+ERROR:  SQL/JSON object not found
+DETAIL:  jsonpath wildcard member accessor is applied to not an object
+select json_path_query('[]', 'lax $.a');
+ json_path_query 
+-----------------
+(0 rows)
+
+select json_path_query('[]', 'strict $.a');
+ERROR:  SQL/JSON member not found
+DETAIL:  jsonpath member accessor is applied to not an object
+select json_path_query('{}', 'lax $.a');
+ json_path_query 
+-----------------
+(0 rows)
+
+select json_path_query('{}', 'strict $.a');
+ERROR:  SQL/JSON member not found
+DETAIL:  JSON object does not contain key "a"
+select json_path_query('1', 'strict $[1]');
+ERROR:  SQL/JSON array not found
+DETAIL:  jsonpath array accessor is applied to not an array
+select json_path_query('1', 'strict $[*]');
+ERROR:  SQL/JSON array not found
+DETAIL:  jsonpath wildcard array accessor is applied to not an array
+select json_path_query('[]', 'strict $[1]');
+ERROR:  invalid SQL/JSON subscript
+DETAIL:  jsonpath array subscript is out of bounds
+select json_path_query('[]', 'strict $["a"]');
+ERROR:  invalid SQL/JSON subscript
+DETAIL:  jsonpath array subscript is not a singleton numeric value
+select json_path_query('{"a": 12, "b": {"a": 13}}', '$.a');
+ json_path_query 
+-----------------
+ 12
+(1 row)
+
+select json_path_query('{"a": 12, "b": {"a": 13}}', '$.b');
+ json_path_query 
+-----------------
+ {"a": 13}
+(1 row)
+
+select json_path_query('{"a": 12, "b": {"a": 13}}', '$.*');
+ json_path_query 
+-----------------
+ 12
+ {"a": 13}
+(2 rows)
+
+select json_path_query('{"a": 12, "b": {"a": 13}}', 'lax $.*.a');
+ json_path_query 
+-----------------
+ 13
+(1 row)
+
+select json_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[*].a');
+ json_path_query 
+-----------------
+ 13
+(1 row)
+
+select json_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[*].*');
+ json_path_query 
+-----------------
+ 13
+ 14
+(2 rows)
+
+select json_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[0].a');
+ json_path_query 
+-----------------
+(0 rows)
+
+select json_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[1].a');
+ json_path_query 
+-----------------
+ 13
+(1 row)
+
+select json_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[2].a');
+ json_path_query 
+-----------------
+(0 rows)
+
+select json_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[0,1].a');
+ json_path_query 
+-----------------
+ 13
+(1 row)
+
+select json_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[0 to 10].a');
+ json_path_query 
+-----------------
+ 13
+(1 row)
+
+select json_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[0 to 10 / 0].a');
+ERROR:  division by zero
+select json_path_query('[12, {"a": 13}, {"b": 14}, "ccc", true]', '$[2.5 - 1 to $.size() - 2]');
+ json_path_query 
+-----------------
+ {"a": 13}
+ {"b": 14}
+ "ccc"
+(3 rows)
+
+select json_path_query('1', 'lax $[0]');
+ json_path_query 
+-----------------
+ 1
+(1 row)
+
+select json_path_query('1', 'lax $[*]');
+ json_path_query 
+-----------------
+ 1
+(1 row)
+
+select json_path_query('[1]', 'lax $[0]');
+ json_path_query 
+-----------------
+ 1
+(1 row)
+
+select json_path_query('[1]', 'lax $[*]');
+ json_path_query 
+-----------------
+ 1
+(1 row)
+
+select json_path_query('[1,2,3]', 'lax $[*]');
+ json_path_query 
+-----------------
+ 1
+ 2
+ 3
+(3 rows)
+
+select json_path_query('[1,2,3]', 'strict $[*].a');
+ERROR:  SQL/JSON member not found
+DETAIL:  jsonpath member accessor is applied to not an object
+select json_path_query('[]', '$[last]');
+ json_path_query 
+-----------------
+(0 rows)
+
+select json_path_query('[]', '$[last ? (exists(last))]');
+ json_path_query 
+-----------------
+(0 rows)
+
+select json_path_query('[]', 'strict $[last]');
+ERROR:  invalid SQL/JSON subscript
+DETAIL:  jsonpath array subscript is out of bounds
+select json_path_query('[1]', '$[last]');
+ json_path_query 
+-----------------
+ 1
+(1 row)
+
+select json_path_query('[1,2,3]', '$[last]');
+ json_path_query 
+-----------------
+ 3
+(1 row)
+
+select json_path_query('[1,2,3]', '$[last - 1]');
+ json_path_query 
+-----------------
+ 2
+(1 row)
+
+select json_path_query('[1,2,3]', '$[last ? (@.type() == "number")]');
+ json_path_query 
+-----------------
+ 3
+(1 row)
+
+select json_path_query('[1,2,3]', '$[last ? (@.type() == "string")]');
+ERROR:  invalid SQL/JSON subscript
+DETAIL:  jsonpath array subscript is not a singleton numeric value
+select * from json_path_query('{"a": 10}', '$');
+ json_path_query 
+-----------------
+ {"a": 10}
+(1 row)
+
+select * from json_path_query('{"a": 10}', '$ ? (@.a < $value)');
+ERROR:  cannot find jsonpath variable 'value'
+select * from json_path_query('{"a": 10}', '$ ? (@.a < $value)', '1');
+ERROR:  json containing jsonpath variables is not an object
+select * from json_path_query('{"a": 10}', '$ ? (@.a < $value)', '[{"value" : 13}]');
+ERROR:  json containing jsonpath variables is not an object
+select * from json_path_query('{"a": 10}', '$ ? (@.a < $value)', '{"value" : 13}');
+ json_path_query 
+-----------------
+ {"a": 10}
+(1 row)
+
+select * from json_path_query('{"a": 10}', '$ ? (@.a < $value)', '{"value" : 8}');
+ json_path_query 
+-----------------
+(0 rows)
+
+select * from json_path_query('{"a": 10}', '$.a ? (@ < $value)', '{"value" : 13}');
+ json_path_query 
+-----------------
+ 10
+(1 row)
+
+select * from json_path_query('[10,11,12,13,14,15]', '$[*] ? (@ < $value)', '{"value" : 13}');
+ json_path_query 
+-----------------
+ 10
+ 11
+ 12
+(3 rows)
+
+select * from json_path_query('[10,11,12,13,14,15]', '$[0,1] ? (@ < $x.value)', '{"x": {"value" : 13}}');
+ json_path_query 
+-----------------
+ 10
+ 11
+(2 rows)
+
+select * from json_path_query('[10,11,12,13,14,15]', '$[0 to 2] ? (@ < $value)', '{"value" : 15}');
+ json_path_query 
+-----------------
+ 10
+ 11
+ 12
+(3 rows)
+
+select * from json_path_query('[1,"1",2,"2",null]', '$[*] ? (@ == "1")');
+ json_path_query 
+-----------------
+ "1"
+(1 row)
+
+select * from json_path_query('[1,"1",2,"2",null]', '$[*] ? (@ == $value)', '{"value" : "1"}');
+ json_path_query 
+-----------------
+ "1"
+(1 row)
+
+select * from json_path_query('[1,"1",2,"2",null]', '$[*] ? (@ == $value)', '{"value" : null}');
+ json_path_query 
+-----------------
+ null
+(1 row)
+
+select * from json_path_query('[1, "2", null]', '$[*] ? (@ != null)');
+ json_path_query 
+-----------------
+ 1
+ "2"
+(2 rows)
+
+select * from json_path_query('[1, "2", null]', '$[*] ? (@ == null)');
+ json_path_query 
+-----------------
+ null
+(1 row)
+
+select * from json_path_query('{}', '$ ? (@ == @)');
+ json_path_query 
+-----------------
+(0 rows)
+
+select * from json_path_query('[]', 'strict $ ? (@ == @)');
+ json_path_query 
+-----------------
+(0 rows)
+
+select json_path_query('{"a": {"b": 1}}', 'lax $.**');
+ json_path_query 
+-----------------
+ {"a": {"b": 1}}
+ {"b": 1}
+ 1
+(3 rows)
+
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{0}');
+ json_path_query 
+-----------------
+ {"a": {"b": 1}}
+(1 row)
+
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{0 to last}');
+ json_path_query 
+-----------------
+ {"a": {"b": 1}}
+ {"b": 1}
+ 1
+(3 rows)
+
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{1}');
+ json_path_query 
+-----------------
+ {"b": 1}
+(1 row)
+
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{1 to last}');
+ json_path_query 
+-----------------
+ {"b": 1}
+ 1
+(2 rows)
+
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{2}');
+ json_path_query 
+-----------------
+ 1
+(1 row)
+
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{2 to last}');
+ json_path_query 
+-----------------
+ 1
+(1 row)
+
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{3 to last}');
+ json_path_query 
+-----------------
+(0 rows)
+
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{last}');
+ json_path_query 
+-----------------
+ 1
+(1 row)
+
+select json_path_query('{"a": {"b": 1}}', 'lax $.**.b ? (@ > 0)');
+ json_path_query 
+-----------------
+ 1
+(1 row)
+
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{0}.b ? (@ > 0)');
+ json_path_query 
+-----------------
+(0 rows)
+
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{1}.b ? (@ > 0)');
+ json_path_query 
+-----------------
+ 1
+(1 row)
+
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{0 to last}.b ? (@ > 0)');
+ json_path_query 
+-----------------
+ 1
+(1 row)
+
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{1 to last}.b ? (@ > 0)');
+ json_path_query 
+-----------------
+ 1
+(1 row)
+
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{1 to 2}.b ? (@ > 0)');
+ json_path_query 
+-----------------
+ 1
+(1 row)
+
+select json_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**.b ? (@ > 0)');
+ json_path_query 
+-----------------
+ 1
+(1 row)
+
+select json_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{0}.b ? (@ > 0)');
+ json_path_query 
+-----------------
+(0 rows)
+
+select json_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{1}.b ? (@ > 0)');
+ json_path_query 
+-----------------
+(0 rows)
+
+select json_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{0 to last}.b ? (@ > 0)');
+ json_path_query 
+-----------------
+ 1
+(1 row)
+
+select json_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{1 to last}.b ? (@ > 0)');
+ json_path_query 
+-----------------
+ 1
+(1 row)
+
+select json_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{1 to 2}.b ? (@ > 0)');
+ json_path_query 
+-----------------
+ 1
+(1 row)
+
+select json_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{2 to 3}.b ? (@ > 0)');
+ json_path_query 
+-----------------
+ 1
+(1 row)
+
+select json '{"a": {"b": 1}}' @? '$.**.b ? ( @ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"a": {"b": 1}}' @? '$.**{0}.b ? ( @ > 0)';
+ ?column? 
+----------
+ f
+(1 row)
+
+select json '{"a": {"b": 1}}' @? '$.**{1}.b ? ( @ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"a": {"b": 1}}' @? '$.**{0 to last}.b ? ( @ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"a": {"b": 1}}' @? '$.**{1 to last}.b ? ( @ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"a": {"b": 1}}' @? '$.**{1 to 2}.b ? ( @ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"a": {"c": {"b": 1}}}' @? '$.**.b ? ( @ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"a": {"c": {"b": 1}}}' @? '$.**{0}.b ? ( @ > 0)';
+ ?column? 
+----------
+ f
+(1 row)
+
+select json '{"a": {"c": {"b": 1}}}' @? '$.**{1}.b ? ( @ > 0)';
+ ?column? 
+----------
+ f
+(1 row)
+
+select json '{"a": {"c": {"b": 1}}}' @? '$.**{0 to last}.b ? ( @ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"a": {"c": {"b": 1}}}' @? '$.**{1 to last}.b ? ( @ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"a": {"c": {"b": 1}}}' @? '$.**{1 to 2}.b ? ( @ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"a": {"c": {"b": 1}}}' @? '$.**{2 to 3}.b ? ( @ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json_path_query('{"g": {"x": 2}}', '$.g ? (exists (@.x))');
+ json_path_query 
+-----------------
+ {"x": 2}
+(1 row)
+
+select json_path_query('{"g": {"x": 2}}', '$.g ? (exists (@.y))');
+ json_path_query 
+-----------------
+(0 rows)
+
+select json_path_query('{"g": {"x": 2}}', '$.g ? (exists (@.x ? (@ >= 2) ))');
+ json_path_query 
+-----------------
+ {"x": 2}
+(1 row)
+
+select json_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'lax $.g ? (exists (@.x))');
+ json_path_query 
+-----------------
+ {"x": 2}
+(1 row)
+
+select json_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'lax $.g ? (exists (@.x + "3"))');
+ json_path_query 
+-----------------
+(0 rows)
+
+select json_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'lax $.g ? ((exists (@.x + "3")) is unknown)');
+ json_path_query 
+-----------------
+ {"x": 2}
+ {"y": 3}
+(2 rows)
+
+select json_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'strict $.g[*] ? (exists (@.x))');
+ json_path_query 
+-----------------
+ {"x": 2}
+(1 row)
+
+select json_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'strict $.g[*] ? ((exists (@.x)) is unknown)');
+ json_path_query 
+-----------------
+ {"y": 3}
+(1 row)
+
+select json_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'strict $.g ? (exists (@[*].x))');
+ json_path_query 
+-----------------
+(0 rows)
+
+select json_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'strict $.g ? ((exists (@[*].x)) is unknown)');
+   json_path_query    
+----------------------
+ [{"x": 2}, {"y": 3}]
+(1 row)
+
+--test ternary logic
+select
+	x, y,
+	json_path_query(
+		'[true, false, null]',
+		'$[*] ? (@ == true  &&  ($x == true && $y == true) ||
+				 @ == false && !($x == true && $y == true) ||
+				 @ == null  &&  ($x == true && $y == true) is unknown)',
+		json_build_object('x', x, 'y', y)
+	) as "x && y"
+from
+	(values (json 'true'), ('false'), ('"null"')) x(x),
+	(values (json 'true'), ('false'), ('"null"')) y(y);
+   x    |   y    | x && y 
+--------+--------+--------
+ true   | true   | true
+ true   | false  | false
+ true   | "null" | null
+ false  | true   | false
+ false  | false  | false
+ false  | "null" | false
+ "null" | true   | null
+ "null" | false  | false
+ "null" | "null" | null
+(9 rows)
+
+select
+	x, y,
+	json_path_query(
+		'[true, false, null]',
+		'$[*] ? (@ == true  &&  ($x == true || $y == true) ||
+				 @ == false && !($x == true || $y == true) ||
+				 @ == null  &&  ($x == true || $y == true) is unknown)',
+		json_build_object('x', x, 'y', y)
+	) as "x || y"
+from
+	(values (json 'true'), ('false'), ('"null"')) x(x),
+	(values (json 'true'), ('false'), ('"null"')) y(y);
+   x    |   y    | x || y 
+--------+--------+--------
+ true   | true   | true
+ true   | false  | true
+ true   | "null" | true
+ false  | true   | true
+ false  | false  | false
+ false  | "null" | null
+ "null" | true   | true
+ "null" | false  | null
+ "null" | "null" | null
+(9 rows)
+
+select json '{"a": 1, "b":1}' @? '$ ? (@.a == @.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"c": {"a": 1, "b":1}}' @? '$ ? (@.a == @.b)';
+ ?column? 
+----------
+ f
+(1 row)
+
+select json '{"c": {"a": 1, "b":1}}' @? '$.c ? (@.a == @.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"c": {"a": 1, "b":1}}' @? '$.c ? ($.c.a == @.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"c": {"a": 1, "b":1}}' @? '$.* ? (@.a == @.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"a": 1, "b":1}' @? '$.** ? (@.a == @.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"c": {"a": 1, "b":1}}' @? '$.** ? (@.a == @.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json_path_query('{"c": {"a": 2, "b":1}}', '$.** ? (@.a == 1 + 1)');
+ json_path_query 
+-----------------
+ {"a": 2, "b":1}
+(1 row)
+
+select json_path_query('{"c": {"a": 2, "b":1}}', '$.** ? (@.a == (1 + 1))');
+ json_path_query 
+-----------------
+ {"a": 2, "b":1}
+(1 row)
+
+select json_path_query('{"c": {"a": 2, "b":1}}', '$.** ? (@.a == @.b + 1)');
+ json_path_query 
+-----------------
+ {"a": 2, "b":1}
+(1 row)
+
+select json_path_query('{"c": {"a": 2, "b":1}}', '$.** ? (@.a == (@.b + 1))');
+ json_path_query 
+-----------------
+ {"a": 2, "b":1}
+(1 row)
+
+select json '{"c": {"a": -1, "b":1}}' @? '$.** ? (@.a == - 1)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"c": {"a": -1, "b":1}}' @? '$.** ? (@.a == -1)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"c": {"a": -1, "b":1}}' @? '$.** ? (@.a == -@.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"c": {"a": -1, "b":1}}' @? '$.** ? (@.a == - @.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"c": {"a": 0, "b":1}}' @? '$.** ? (@.a == 1 - @.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"c": {"a": 2, "b":1}}' @? '$.** ? (@.a == 1 - - @.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"c": {"a": 0, "b":1}}' @? '$.** ? (@.a == 1 - +@.b)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '[1,2,3]' @? '$ ? (+@[*] > +2)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '[1,2,3]' @? '$ ? (+@[*] > +3)';
+ ?column? 
+----------
+ f
+(1 row)
+
+select json '[1,2,3]' @? '$ ? (-@[*] < -2)';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '[1,2,3]' @? '$ ? (-@[*] < -3)';
+ ?column? 
+----------
+ f
+(1 row)
+
+select json '1' @? '$ ? ($ > 0)';
+ ?column? 
+----------
+ t
+(1 row)
+
+-- arithmetic errors
+select json_path_query('[1,2,0,3]', '$[*] ? (2 / @ > 0)');
+ json_path_query 
+-----------------
+ 1
+ 2
+ 3
+(3 rows)
+
+select json_path_query('[1,2,0,3]', '$[*] ? ((2 / @ > 0) is unknown)');
+ json_path_query 
+-----------------
+ 0
+(1 row)
+
+select json_path_query('0', '1 / $');
+ERROR:  division by zero
+select json_path_query('0', '1 / $ + 2');
+ERROR:  division by zero
+select json_path_query('0', '-(3 + 1 % $)');
+ERROR:  division by zero
+select json_path_query('1', '$ + "2"');
+ERROR:  singleton SQL/JSON item required
+DETAIL:  right operand of binary jsonpath operator + is not a singleton numeric value
+select json_path_query('[1, 2]', '3 * $');
+ERROR:  singleton SQL/JSON item required
+DETAIL:  right operand of binary jsonpath operator * is not a singleton numeric value
+select json_path_query('"a"', '-$');
+ERROR:  SQL/JSON number not found
+DETAIL:  operand of unary jsonpath operator - is not a numeric value
+select json_path_query('[1,"2",3]', '+$');
+ERROR:  SQL/JSON number not found
+DETAIL:  operand of unary jsonpath operator + is not a numeric value
+select json '["1",2,0,3]' @? '-$[*]';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '[1,"2",0,3]' @? '-$[*]';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '["1",2,0,3]' @? 'strict -$[*]';
+ ?column? 
+----------
+ 
+(1 row)
+
+select json '[1,"2",0,3]' @? 'strict -$[*]';
+ ?column? 
+----------
+ 
+(1 row)
+
+-- unwrapping of operator arguments in lax mode
+select json_path_query('{"a": [2]}', 'lax $.a * 3');
+ json_path_query 
+-----------------
+ 6
+(1 row)
+
+select json_path_query('{"a": [2]}', 'lax $.a + 3');
+ json_path_query 
+-----------------
+ 5
+(1 row)
+
+select json_path_query('{"a": [2, 3, 4]}', 'lax -$.a');
+ json_path_query 
+-----------------
+ -2
+ -3
+ -4
+(3 rows)
+
+-- should fail
+select json_path_query('{"a": [1, 2]}', 'lax $.a * 3');
+ERROR:  singleton SQL/JSON item required
+DETAIL:  left operand of binary jsonpath operator * is not a singleton numeric value
+-- extension: boolean expressions
+select json_path_query('2', '$ > 1');
+ json_path_query 
+-----------------
+ true
+(1 row)
+
+select json_path_query('2', '$ <= 1');
+ json_path_query 
+-----------------
+ false
+(1 row)
+
+select json_path_query('2', '$ == "2"');
+ json_path_query 
+-----------------
+ null
+(1 row)
+
+select json '2' @? '$ == "2"';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '2' @@ '$ > 1';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '2' @@ '$ <= 1';
+ ?column? 
+----------
+ f
+(1 row)
+
+select json '2' @@ '$ == "2"';
+ ?column? 
+----------
+ 
+(1 row)
+
+select json '2' @@ '1';
+ ?column? 
+----------
+ 
+(1 row)
+
+select json '{}' @@ '$';
+ ?column? 
+----------
+ 
+(1 row)
+
+select json '[]' @@ '$';
+ ?column? 
+----------
+ 
+(1 row)
+
+select json '[1,2,3]' @@ '$[*]';
+ ?column? 
+----------
+ 
+(1 row)
+
+select json '[]' @@ '$[*]';
+ ?column? 
+----------
+ 
+(1 row)
+
+select json_path_match('[[1, true], [2, false]]', 'strict $[*] ? (@[0] > $x) [1]', '{"x": 1}');
+ json_path_match 
+-----------------
+ f
+(1 row)
+
+select json_path_match('[[1, true], [2, false]]', 'strict $[*] ? (@[0] < $x) [1]', '{"x": 2}');
+ json_path_match 
+-----------------
+ t
+(1 row)
+
+select json_path_query('[null,1,true,"a",[],{}]', '$.type()');
+ json_path_query 
+-----------------
+ "array"
+(1 row)
+
+select json_path_query('[null,1,true,"a",[],{}]', 'lax $.type()');
+ json_path_query 
+-----------------
+ "array"
+(1 row)
+
+select json_path_query('[null,1,true,"a",[],{}]', '$[*].type()');
+ json_path_query 
+-----------------
+ "null"
+ "number"
+ "boolean"
+ "string"
+ "array"
+ "object"
+(6 rows)
+
+select json_path_query('null', 'null.type()');
+ json_path_query 
+-----------------
+ "null"
+(1 row)
+
+select json_path_query('null', 'true.type()');
+ json_path_query 
+-----------------
+ "boolean"
+(1 row)
+
+select json_path_query('null', '123.type()');
+ json_path_query 
+-----------------
+ "number"
+(1 row)
+
+select json_path_query('null', '"123".type()');
+ json_path_query 
+-----------------
+ "string"
+(1 row)
+
+select json_path_query('{"a": 2}', '($.a - 5).abs() + 10');
+ json_path_query 
+-----------------
+ 13
+(1 row)
+
+select json_path_query('{"a": 2.5}', '-($.a * $.a).floor() % 4.3');
+ json_path_query 
+-----------------
+ -1.7
+(1 row)
+
+select json_path_query('[1, 2, 3]', '($[*] > 2) ? (@ == true)');
+ json_path_query 
+-----------------
+ true
+(1 row)
+
+select json_path_query('[1, 2, 3]', '($[*] > 3).type()');
+ json_path_query 
+-----------------
+ "boolean"
+(1 row)
+
+select json_path_query('[1, 2, 3]', '($[*].a > 3).type()');
+ json_path_query 
+-----------------
+ "boolean"
+(1 row)
+
+select json_path_query('[1, 2, 3]', 'strict ($[*].a > 3).type()');
+ json_path_query 
+-----------------
+ "null"
+(1 row)
+
+select json_path_query('[1,null,true,"11",[],[1],[1,2,3],{},{"a":1,"b":2}]', 'strict $[*].size()');
+ERROR:  SQL/JSON array not found
+DETAIL:  jsonpath item method .size() is applied to not an array
+select json_path_query('[1,null,true,"11",[],[1],[1,2,3],{},{"a":1,"b":2}]', 'lax $[*].size()');
+ json_path_query 
+-----------------
+ 1
+ 1
+ 1
+ 1
+ 0
+ 1
+ 3
+ 1
+ 1
+(9 rows)
+
+select json_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].abs()');
+ json_path_query 
+-----------------
+ 0
+ 1
+ 2
+ 3.4
+ 5.6
+(5 rows)
+
+select json_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].floor()');
+ json_path_query 
+-----------------
+ 0
+ 1
+ -2
+ -4
+ 5
+(5 rows)
+
+select json_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].ceiling()');
+ json_path_query 
+-----------------
+ 0
+ 1
+ -2
+ -3
+ 6
+(5 rows)
+
+select json_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].ceiling().abs()');
+ json_path_query 
+-----------------
+ 0
+ 1
+ 2
+ 3
+ 6
+(5 rows)
+
+select json_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].ceiling().abs().type()');
+ json_path_query 
+-----------------
+ "number"
+ "number"
+ "number"
+ "number"
+ "number"
+(5 rows)
+
+select json_path_query('[{},1]', '$[*].keyvalue()');
+ERROR:  SQL/JSON object not found
+DETAIL:  jsonpath item method .keyvalue() is applied to not an object
+select json_path_query('{}', '$.keyvalue()');
+ json_path_query 
+-----------------
+(0 rows)
+
+select json_path_query('{"a": 1, "b": [1, 2], "c": {"a": "bbb"}}', '$.keyvalue()');
+               json_path_query                
+----------------------------------------------
+ {"key": "a", "value": 1, "id": 0}
+ {"key": "b", "value": [1, 2], "id": 0}
+ {"key": "c", "value": {"a": "bbb"}, "id": 0}
+(3 rows)
+
+select json_path_query('[{"a": 1, "b": [1, 2]}, {"c": {"a": "bbb"}}]', '$[*].keyvalue()');
+                json_path_query                
+-----------------------------------------------
+ {"key": "a", "value": 1, "id": 1}
+ {"key": "b", "value": [1, 2], "id": 1}
+ {"key": "c", "value": {"a": "bbb"}, "id": 24}
+(3 rows)
+
+select json_path_query('[{"a": 1, "b": [1, 2]}, {"c": {"a": "bbb"}}]', 'strict $.keyvalue()');
+ERROR:  SQL/JSON object not found
+DETAIL:  jsonpath item method .keyvalue() is applied to not an object
+select json_path_query('[{"a": 1, "b": [1, 2]}, {"c": {"a": "bbb"}}]', 'lax $.keyvalue()');
+                json_path_query                
+-----------------------------------------------
+ {"key": "a", "value": 1, "id": 1}
+ {"key": "b", "value": [1, 2], "id": 1}
+ {"key": "c", "value": {"a": "bbb"}, "id": 24}
+(3 rows)
+
+select json_path_query('[{"a": 1, "b": [1, 2]}, {"c": {"a": "bbb"}}]', 'strict $.keyvalue().a');
+ERROR:  SQL/JSON object not found
+DETAIL:  jsonpath item method .keyvalue() is applied to not an object
+select json '{"a": 1, "b": [1, 2]}' @? 'lax $.keyvalue()';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json '{"a": 1, "b": [1, 2]}' @? 'lax $.keyvalue().key';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json_path_query('null', '$.double()');
+ERROR:  non-numeric SQL/JSON item
+DETAIL:  jsonpath item method .double() is applied to neither a string nor numeric value
+select json_path_query('true', '$.double()');
+ERROR:  non-numeric SQL/JSON item
+DETAIL:  jsonpath item method .double() is applied to neither a string nor numeric value
+select json_path_query('[]', '$.double()');
+ json_path_query 
+-----------------
+(0 rows)
+
+select json_path_query('[]', 'strict $.double()');
+ERROR:  non-numeric SQL/JSON item
+DETAIL:  jsonpath item method .double() is applied to neither a string nor numeric value
+select json_path_query('{}', '$.double()');
+ERROR:  non-numeric SQL/JSON item
+DETAIL:  jsonpath item method .double() is applied to neither a string nor numeric value
+select json_path_query('1.23', '$.double()');
+ json_path_query 
+-----------------
+ 1.23
+(1 row)
+
+select json_path_query('"1.23"', '$.double()');
+ json_path_query 
+-----------------
+ 1.23
+(1 row)
+
+select json_path_query('"1.23aaa"', '$.double()');
+ERROR:  non-numeric SQL/JSON item
+DETAIL:  jsonpath item method .double() is applied to not a numeric value
+select json_path_query('"nan"', '$.double()');
+ json_path_query 
+-----------------
+ "NaN"
+(1 row)
+
+select json_path_query('"NaN"', '$.double()');
+ json_path_query 
+-----------------
+ "NaN"
+(1 row)
+
+select json_path_query('"inf"', '$.double()');
+ERROR:  non-numeric SQL/JSON item
+DETAIL:  jsonpath item method .double() is applied to not a numeric value
+select json_path_query('"-inf"', '$.double()');
+ERROR:  non-numeric SQL/JSON item
+DETAIL:  jsonpath item method .double() is applied to not a numeric value
+select json_path_query('{}', '$.abs()');
+ERROR:  non-numeric SQL/JSON item
+DETAIL:  jsonpath item method .abs() is applied to not a numeric value
+select json_path_query('true', '$.floor()');
+ERROR:  non-numeric SQL/JSON item
+DETAIL:  jsonpath item method .floor() is applied to not a numeric value
+select json_path_query('"1.2"', '$.ceiling()');
+ERROR:  non-numeric SQL/JSON item
+DETAIL:  jsonpath item method .ceiling() is applied to not a numeric value
+select json_path_query('["", "a", "abc", "abcabc"]', '$[*] ? (@ starts with "abc")');
+ json_path_query 
+-----------------
+ "abc"
+ "abcabc"
+(2 rows)
+
+select json_path_query('["", "a", "abc", "abcabc"]', 'strict $ ? (@[*] starts with "abc")');
+      json_path_query       
+----------------------------
+ ["", "a", "abc", "abcabc"]
+(1 row)
+
+select json_path_query('["", "a", "abd", "abdabc"]', 'strict $ ? (@[*] starts with "abc")');
+ json_path_query 
+-----------------
+(0 rows)
+
+select json_path_query('["abc", "abcabc", null, 1]', 'strict $ ? (@[*] starts with "abc")');
+ json_path_query 
+-----------------
+(0 rows)
+
+select json_path_query('["abc", "abcabc", null, 1]', 'strict $ ? ((@[*] starts with "abc") is unknown)');
+      json_path_query       
+----------------------------
+ ["abc", "abcabc", null, 1]
+(1 row)
+
+select json_path_query('[[null, 1, "abc", "abcabc"]]', 'lax $ ? (@[*] starts with "abc")');
+      json_path_query       
+----------------------------
+ [null, 1, "abc", "abcabc"]
+(1 row)
+
+select json_path_query('[[null, 1, "abd", "abdabc"]]', 'lax $ ? ((@[*] starts with "abc") is unknown)');
+      json_path_query       
+----------------------------
+ [null, 1, "abd", "abdabc"]
+(1 row)
+
+select json_path_query('[null, 1, "abd", "abdabc"]', 'lax $[*] ? ((@ starts with "abc") is unknown)');
+ json_path_query 
+-----------------
+ null
+ 1
+(2 rows)
+
+select json_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "adc\nabc", "babc"]', 'lax $[*] ? (@ like_regex "^ab.*c")');
+ json_path_query 
+-----------------
+ "abc"
+ "abdacb"
+(2 rows)
+
+select json_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "adc\nabc", "babc"]', 'lax $[*] ? (@ like_regex "^a  b.*  c " flag "ix")');
+ json_path_query 
+-----------------
+ "abc"
+ "aBdC"
+ "abdacb"
+(3 rows)
+
+select json_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "adc\nabc", "babc"]', 'lax $[*] ? (@ like_regex "^ab.*c" flag "m")');
+ json_path_query 
+-----------------
+ "abc"
+ "abdacb"
+ "adc\nabc"
+(3 rows)
+
+select json_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "adc\nabc", "babc"]', 'lax $[*] ? (@ like_regex "^ab.*c" flag "s")');
+ json_path_query 
+-----------------
+ "abc"
+ "abdacb"
+(2 rows)
+
+select json_path_query('null', '$.datetime()');
+ERROR:  invalid argument for SQL/JSON datetime function
+DETAIL:  jsonpath item method .datetime() is applied to not a string
+select json_path_query('true', '$.datetime()');
+ERROR:  invalid argument for SQL/JSON datetime function
+DETAIL:  jsonpath item method .datetime() is applied to not a string
+select json_path_query('1', '$.datetime()');
+ERROR:  invalid argument for SQL/JSON datetime function
+DETAIL:  jsonpath item method .datetime() is applied to not a string
+select json_path_query('[]', '$.datetime()');
+ json_path_query 
+-----------------
+(0 rows)
+
+select json_path_query('[]', 'strict $.datetime()');
+ERROR:  invalid argument for SQL/JSON datetime function
+DETAIL:  jsonpath item method .datetime() is applied to not a string
+select json_path_query('{}', '$.datetime()');
+ERROR:  invalid argument for SQL/JSON datetime function
+DETAIL:  jsonpath item method .datetime() is applied to not a string
+select json_path_query('""', '$.datetime()');
+ERROR:  invalid argument for SQL/JSON datetime function
+DETAIL:  unrecognized datetime format
+HINT:  use datetime template argument for explicit format specification
+select json_path_query('"12:34"', '$.datetime("aaa")');
+ERROR:  datetime format is not dated and not timed
+select json_path_query('"12:34"', '$.datetime("aaa", 1)');
+ERROR:  datetime format is not dated and not timed
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH", 1)');
+   json_path_query   
+---------------------
+ "12:34:00+00:00:01"
+(1 row)
+
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH", 10000000000000)');
+ERROR:  invalid argument for SQL/JSON datetime function
+DETAIL:  timezone argument of jsonpath item method .datetime() is out of integer range
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH", 10000000000000)');
+ERROR:  invalid argument for SQL/JSON datetime function
+DETAIL:  timezone argument of jsonpath item method .datetime() is out of integer range
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH", 2147483647)');
+     json_path_query     
+-------------------------
+ "12:34:00+596523:14:07"
+(1 row)
+
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH", 2147483648)');
+ERROR:  invalid argument for SQL/JSON datetime function
+DETAIL:  timezone argument of jsonpath item method .datetime() is out of integer range
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH", -2147483647)');
+     json_path_query     
+-------------------------
+ "12:34:00-596523:14:07"
+(1 row)
+
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH", -2147483648)');
+ERROR:  invalid argument for SQL/JSON datetime function
+DETAIL:  timezone argument of jsonpath item method .datetime() is out of integer range
+select json_path_query('"aaaa"', '$.datetime("HH24")');
+ERROR:  invalid value "aa" for "HH24"
+DETAIL:  Value must be an integer.
+select json '"10-03-2017"' @? '$.datetime("dd-mm-yyyy")';
+ ?column? 
+----------
+ t
+(1 row)
+
+select json_path_query('"10-03-2017"', '$.datetime("dd-mm-yyyy")');
+ json_path_query 
+-----------------
+ "2017-03-10"
+(1 row)
+
+select json_path_query('"10-03-2017"', '$.datetime("dd-mm-yyyy").type()');
+ json_path_query 
+-----------------
+ "date"
+(1 row)
+
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy")');
+ json_path_query 
+-----------------
+ "2017-03-10"
+(1 row)
+
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy").type()');
+ json_path_query 
+-----------------
+ "date"
+(1 row)
+
+select json_path_query('"10-03-2017 12:34"', '       $.datetime("dd-mm-yyyy HH24:MI").type()');
+        json_path_query        
+-------------------------------
+ "timestamp without time zone"
+(1 row)
+
+select json_path_query('"10-03-2017 12:34 +05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM").type()');
+      json_path_query       
+----------------------------
+ "timestamp with time zone"
+(1 row)
+
+select json_path_query('"12:34:56"', '$.datetime("HH24:MI:SS").type()');
+     json_path_query      
+--------------------------
+ "time without time zone"
+(1 row)
+
+select json_path_query('"12:34:56 +05:20"', '$.datetime("HH24:MI:SS TZH:TZM").type()');
+    json_path_query    
+-----------------------
+ "time with time zone"
+(1 row)
+
+set time zone '+00';
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI")');
+    json_path_query    
+-----------------------
+ "2017-03-10T12:34:00"
+(1 row)
+
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+ERROR:  missing time-zone in input string for type timestamptz
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", "+00")');
+       json_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+00:00"
+(1 row)
+
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", "+00:12")');
+       json_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+00:12"
+(1 row)
+
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", "-00:12:34")');
+        json_path_query         
+--------------------------------
+ "2017-03-10T12:34:00-00:12:34"
+(1 row)
+
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", "UTC")');
+ERROR:  invalid input syntax for type timestamptz: "UTC"
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", 12 * 60)');
+       json_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+00:12"
+(1 row)
+
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", -(5 * 3600 + 12 * 60 + 34))');
+        json_path_query         
+--------------------------------
+ "2017-03-10T12:34:00-05:12:34"
+(1 row)
+
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", $tz)',
+                        json_build_object('tz', extract(timezone from now())));
+       json_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+00:00"
+(1 row)
+
+select json_path_query('"10-03-2017 12:34 +05"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+       json_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+05:00"
+(1 row)
+
+select json_path_query('"10-03-2017 12:34 -05"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+       json_path_query       
+-----------------------------
+ "2017-03-10T12:34:00-05:00"
+(1 row)
+
+select json_path_query('"10-03-2017 12:34 +05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")');
+       json_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+05:20"
+(1 row)
+
+select json_path_query('"10-03-2017 12:34 -05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")');
+       json_path_query       
+-----------------------------
+ "2017-03-10T12:34:00-05:20"
+(1 row)
+
+select json_path_query('"12:34"', '$.datetime("HH24:MI")');
+ json_path_query 
+-----------------
+ "12:34:00"
+(1 row)
+
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH")');
+ERROR:  missing time-zone in input string for type timetz
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH", "+00")');
+ json_path_query  
+------------------
+ "12:34:00+00:00"
+(1 row)
+
+select json_path_query('"12:34 +05"', '$.datetime("HH24:MI TZH")');
+ json_path_query  
+------------------
+ "12:34:00+05:00"
+(1 row)
+
+select json_path_query('"12:34 -05"', '$.datetime("HH24:MI TZH")');
+ json_path_query  
+------------------
+ "12:34:00-05:00"
+(1 row)
+
+select json_path_query('"12:34 +05:20"', '$.datetime("HH24:MI TZH:TZM")');
+ json_path_query  
+------------------
+ "12:34:00+05:20"
+(1 row)
+
+select json_path_query('"12:34 -05:20"', '$.datetime("HH24:MI TZH:TZM")');
+ json_path_query  
+------------------
+ "12:34:00-05:20"
+(1 row)
+
+set time zone '+10';
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI")');
+    json_path_query    
+-----------------------
+ "2017-03-10T12:34:00"
+(1 row)
+
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+ERROR:  missing time-zone in input string for type timestamptz
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", "+10")');
+       json_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+10:00"
+(1 row)
+
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", $tz)',
+                        json_build_object('tz', extract(timezone from now())));
+       json_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+10:00"
+(1 row)
+
+select json_path_query('"10-03-2017 12:34 +05"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+       json_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+05:00"
+(1 row)
+
+select json_path_query('"10-03-2017 12:34 -05"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+       json_path_query       
+-----------------------------
+ "2017-03-10T12:34:00-05:00"
+(1 row)
+
+select json_path_query('"10-03-2017 12:34 +05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")');
+       json_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+05:20"
+(1 row)
+
+select json_path_query('"10-03-2017 12:34 -05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")');
+       json_path_query       
+-----------------------------
+ "2017-03-10T12:34:00-05:20"
+(1 row)
+
+select json_path_query('"12:34"', '$.datetime("HH24:MI")');
+ json_path_query 
+-----------------
+ "12:34:00"
+(1 row)
+
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH")');
+ERROR:  missing time-zone in input string for type timetz
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH", "+10")');
+ json_path_query  
+------------------
+ "12:34:00+10:00"
+(1 row)
+
+select json_path_query('"12:34 +05"', '$.datetime("HH24:MI TZH")');
+ json_path_query  
+------------------
+ "12:34:00+05:00"
+(1 row)
+
+select json_path_query('"12:34 -05"', '$.datetime("HH24:MI TZH")');
+ json_path_query  
+------------------
+ "12:34:00-05:00"
+(1 row)
+
+select json_path_query('"12:34 +05:20"', '$.datetime("HH24:MI TZH:TZM")');
+ json_path_query  
+------------------
+ "12:34:00+05:20"
+(1 row)
+
+select json_path_query('"12:34 -05:20"', '$.datetime("HH24:MI TZH:TZM")');
+ json_path_query  
+------------------
+ "12:34:00-05:20"
+(1 row)
+
+set time zone default;
+select json_path_query('"2017-03-10"', '$.datetime().type()');
+ json_path_query 
+-----------------
+ "date"
+(1 row)
+
+select json_path_query('"2017-03-10"', '$.datetime()');
+ json_path_query 
+-----------------
+ "2017-03-10"
+(1 row)
+
+select json_path_query('"2017-03-10 12:34:56"', '$.datetime().type()');
+        json_path_query        
+-------------------------------
+ "timestamp without time zone"
+(1 row)
+
+select json_path_query('"2017-03-10 12:34:56"', '$.datetime()');
+    json_path_query    
+-----------------------
+ "2017-03-10T12:34:56"
+(1 row)
+
+select json_path_query('"2017-03-10 12:34:56 +3"', '$.datetime().type()');
+      json_path_query       
+----------------------------
+ "timestamp with time zone"
+(1 row)
+
+select json_path_query('"2017-03-10 12:34:56 +3"', '$.datetime()');
+       json_path_query       
+-----------------------------
+ "2017-03-10T12:34:56+03:00"
+(1 row)
+
+select json_path_query('"2017-03-10 12:34:56 +3:10"', '$.datetime().type()');
+      json_path_query       
+----------------------------
+ "timestamp with time zone"
+(1 row)
+
+select json_path_query('"2017-03-10 12:34:56 +3:10"', '$.datetime()');
+       json_path_query       
+-----------------------------
+ "2017-03-10T12:34:56+03:10"
+(1 row)
+
+select json_path_query('"12:34:56"', '$.datetime().type()');
+     json_path_query      
+--------------------------
+ "time without time zone"
+(1 row)
+
+select json_path_query('"12:34:56"', '$.datetime()');
+ json_path_query 
+-----------------
+ "12:34:56"
+(1 row)
+
+select json_path_query('"12:34:56 +3"', '$.datetime().type()');
+    json_path_query    
+-----------------------
+ "time with time zone"
+(1 row)
+
+select json_path_query('"12:34:56 +3"', '$.datetime()');
+ json_path_query  
+------------------
+ "12:34:56+03:00"
+(1 row)
+
+select json_path_query('"12:34:56 +3:10"', '$.datetime().type()');
+    json_path_query    
+-----------------------
+ "time with time zone"
+(1 row)
+
+select json_path_query('"12:34:56 +3:10"', '$.datetime()');
+ json_path_query  
+------------------
+ "12:34:56+03:10"
+(1 row)
+
+set time zone '+00';
+-- date comparison
+select json_path_query(
+	'["2017-03-10", "2017-03-11", "2017-03-09", "12:34:56", "01:02:03 +04", "2017-03-10 00:00:00", "2017-03-10 12:34:56", "2017-03-10 01:02:03 +04", "2017-03-10 03:00:00 +03"]',
+	'$[*].datetime() ? (@ == "10.03.2017".datetime("dd.mm.yyyy"))');
+    json_path_query    
+-----------------------
+ "2017-03-10"
+ "2017-03-10T00:00:00"
+(2 rows)
+
+select json_path_query(
+	'["2017-03-10", "2017-03-11", "2017-03-09", "12:34:56", "01:02:03 +04", "2017-03-10 00:00:00", "2017-03-10 12:34:56", "2017-03-10 01:02:03 +04", "2017-03-10 03:00:00 +03"]',
+	'$[*].datetime() ? (@ >= "10.03.2017".datetime("dd.mm.yyyy"))');
+    json_path_query    
+-----------------------
+ "2017-03-10"
+ "2017-03-11"
+ "2017-03-10T00:00:00"
+ "2017-03-10T12:34:56"
+(4 rows)
+
+select json_path_query(
+	'["2017-03-10", "2017-03-11", "2017-03-09", "12:34:56", "01:02:03 +04", "2017-03-10 00:00:00", "2017-03-10 12:34:56", "2017-03-10 01:02:03 +04", "2017-03-10 03:00:00 +03"]',
+	'$[*].datetime() ? (@ <  "10.03.2017".datetime("dd.mm.yyyy"))');
+ json_path_query 
+-----------------
+ "2017-03-09"
+(1 row)
+
+-- time comparison
+select json_path_query(
+	'["12:34:00", "12:35:00", "12:36:00", "12:35:00 +00", "12:35:00 +01", "13:35:00 +01", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +01"]',
+	'$[*].datetime() ? (@ == "12:35".datetime("HH24:MI"))');
+ json_path_query 
+-----------------
+ "12:35:00"
+(1 row)
+
+select json_path_query(
+	'["12:34:00", "12:35:00", "12:36:00", "12:35:00 +00", "12:35:00 +01", "13:35:00 +01", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +01"]',
+	'$[*].datetime() ? (@ >= "12:35".datetime("HH24:MI"))');
+ json_path_query 
+-----------------
+ "12:35:00"
+ "12:36:00"
+(2 rows)
+
+select json_path_query(
+	'["12:34:00", "12:35:00", "12:36:00", "12:35:00 +00", "12:35:00 +01", "13:35:00 +01", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +01"]',
+	'$[*].datetime() ? (@ <  "12:35".datetime("HH24:MI"))');
+ json_path_query 
+-----------------
+ "12:34:00"
+(1 row)
+
+-- timetz comparison
+select json_path_query(
+	'["12:34:00 +01", "12:35:00 +01", "12:36:00 +01", "12:35:00 +02", "12:35:00 -02", "10:35:00", "11:35:00", "12:35:00", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +1"]',
+	'$[*].datetime() ? (@ == "12:35 +1".datetime("HH24:MI TZH"))');
+ json_path_query  
+------------------
+ "12:35:00+01:00"
+(1 row)
+
+select json_path_query(
+	'["12:34:00 +01", "12:35:00 +01", "12:36:00 +01", "12:35:00 +02", "12:35:00 -02", "10:35:00", "11:35:00", "12:35:00", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +1"]',
+	'$[*].datetime() ? (@ >= "12:35 +1".datetime("HH24:MI TZH"))');
+ json_path_query  
+------------------
+ "12:35:00+01:00"
+ "12:36:00+01:00"
+ "12:35:00-02:00"
+(3 rows)
+
+select json_path_query(
+	'["12:34:00 +01", "12:35:00 +01", "12:36:00 +01", "12:35:00 +02", "12:35:00 -02", "10:35:00", "11:35:00", "12:35:00", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +1"]',
+	'$[*].datetime() ? (@ <  "12:35 +1".datetime("HH24:MI TZH"))');
+ json_path_query  
+------------------
+ "12:34:00+01:00"
+ "12:35:00+02:00"
+(2 rows)
+
+-- timestamp comparison
+select json_path_query(
+	'["2017-03-10 12:34:00", "2017-03-10 12:35:00", "2017-03-10 12:36:00", "2017-03-10 12:35:00 +01", "2017-03-10 13:35:00 +01", "2017-03-10 12:35:00 -01", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ == "10.03.2017 12:35".datetime("dd.mm.yyyy HH24:MI"))');
+    json_path_query    
+-----------------------
+ "2017-03-10T12:35:00"
+(1 row)
+
+select json_path_query(
+	'["2017-03-10 12:34:00", "2017-03-10 12:35:00", "2017-03-10 12:36:00", "2017-03-10 12:35:00 +01", "2017-03-10 13:35:00 +01", "2017-03-10 12:35:00 -01", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ >= "10.03.2017 12:35".datetime("dd.mm.yyyy HH24:MI"))');
+    json_path_query    
+-----------------------
+ "2017-03-10T12:35:00"
+ "2017-03-10T12:36:00"
+ "2017-03-11"
+(3 rows)
+
+select json_path_query(
+	'["2017-03-10 12:34:00", "2017-03-10 12:35:00", "2017-03-10 12:36:00", "2017-03-10 12:35:00 +01", "2017-03-10 13:35:00 +01", "2017-03-10 12:35:00 -01", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ < "10.03.2017 12:35".datetime("dd.mm.yyyy HH24:MI"))');
+    json_path_query    
+-----------------------
+ "2017-03-10T12:34:00"
+ "2017-03-10"
+(2 rows)
+
+-- timestamptz comparison
+select json_path_query(
+	'["2017-03-10 12:34:00 +01", "2017-03-10 12:35:00 +01", "2017-03-10 12:36:00 +01", "2017-03-10 12:35:00 +02", "2017-03-10 12:35:00 -02", "2017-03-10 10:35:00", "2017-03-10 11:35:00", "2017-03-10 12:35:00", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ == "10.03.2017 12:35 +1".datetime("dd.mm.yyyy HH24:MI TZH"))');
+       json_path_query       
+-----------------------------
+ "2017-03-10T12:35:00+01:00"
+(1 row)
+
+select json_path_query(
+	'["2017-03-10 12:34:00 +01", "2017-03-10 12:35:00 +01", "2017-03-10 12:36:00 +01", "2017-03-10 12:35:00 +02", "2017-03-10 12:35:00 -02", "2017-03-10 10:35:00", "2017-03-10 11:35:00", "2017-03-10 12:35:00", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ >= "10.03.2017 12:35 +1".datetime("dd.mm.yyyy HH24:MI TZH"))');
+       json_path_query       
+-----------------------------
+ "2017-03-10T12:35:00+01:00"
+ "2017-03-10T12:36:00+01:00"
+ "2017-03-10T12:35:00-02:00"
+(3 rows)
+
+select json_path_query(
+	'["2017-03-10 12:34:00 +01", "2017-03-10 12:35:00 +01", "2017-03-10 12:36:00 +01", "2017-03-10 12:35:00 +02", "2017-03-10 12:35:00 -02", "2017-03-10 10:35:00", "2017-03-10 11:35:00", "2017-03-10 12:35:00", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ < "10.03.2017 12:35 +1".datetime("dd.mm.yyyy HH24:MI TZH"))');
+       json_path_query       
+-----------------------------
+ "2017-03-10T12:34:00+01:00"
+ "2017-03-10T12:35:00+02:00"
+(2 rows)
+
+set time zone default;
+-- jsonpath operators
+SELECT json_path_query('[{"a": 1}, {"a": 2}]', '$[*]');
+ json_path_query 
+-----------------
+ {"a": 1}
+ {"a": 2}
+(2 rows)
+
+SELECT json_path_query('[{"a": 1}, {"a": 2}]', '$[*] ? (@.a > 10)');
+ json_path_query 
+-----------------
+(0 rows)
+
+SELECT json_path_query_array('[{"a": 1}, {"a": 2}, {}]', 'strict $[*].a');
+ERROR:  SQL/JSON member not found
+DETAIL:  JSON object does not contain key "a"
+SELECT json_path_query_array('[{"a": 1}, {"a": 2}]', '$[*].a');
+ json_path_query_array 
+-----------------------
+ [1, 2]
+(1 row)
+
+SELECT json_path_query_array('[{"a": 1}, {"a": 2}]', '$[*].a ? (@ == 1)');
+ json_path_query_array 
+-----------------------
+ [1]
+(1 row)
+
+SELECT json_path_query_array('[{"a": 1}, {"a": 2}]', '$[*].a ? (@ > 10)');
+ json_path_query_array 
+-----------------------
+ []
+(1 row)
+
+SELECT json_path_query_array('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*].a ? (@ > $min && @ < $max)', '{"min": 1, "max": 4}');
+ json_path_query_array 
+-----------------------
+ [2, 3]
+(1 row)
+
+SELECT json_path_query_array('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*].a ? (@ > $min && @ < $max)', '{"min": 3, "max": 4}');
+ json_path_query_array 
+-----------------------
+ []
+(1 row)
+
+SELECT json_path_query_first('[{"a": 1}, {"a": 2}, {}]', 'strict $[*].a');
+ERROR:  SQL/JSON member not found
+DETAIL:  JSON object does not contain key "a"
+SELECT json_path_query_first('[{"a": 1}, {"a": 2}]', '$[*].a');
+ json_path_query_first 
+-----------------------
+ 1
+(1 row)
+
+SELECT json_path_query_first('[{"a": 1}, {"a": 2}]', '$[*].a ? (@ == 1)');
+ json_path_query_first 
+-----------------------
+ 1
+(1 row)
+
+SELECT json_path_query_first('[{"a": 1}, {"a": 2}]', '$[*].a ? (@ > 10)');
+ json_path_query_first 
+-----------------------
+ 
+(1 row)
+
+SELECT json_path_query_first('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*].a ? (@ > $min && @ < $max)', '{"min": 1, "max": 4}');
+ json_path_query_first 
+-----------------------
+ 2
+(1 row)
+
+SELECT json_path_query_first('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*].a ? (@ > $min && @ < $max)', '{"min": 3, "max": 4}');
+ json_path_query_first 
+-----------------------
+ 
+(1 row)
+
+SELECT json '[{"a": 1}, {"a": 2}]' @? '$[*].a ? (@ > 1)';
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT json '[{"a": 1}, {"a": 2}]' @? '$[*] ? (@.a > 2)';
+ ?column? 
+----------
+ f
+(1 row)
+
+SELECT json_path_exists('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*] ? (@.a > $min && @.a < $max)', '{"min": 1, "max": 4}');
+ json_path_exists 
+------------------
+ t
+(1 row)
+
+SELECT json_path_exists('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*] ? (@.a > $min && @.a < $max)', '{"min": 3, "max": 4}');
+ json_path_exists 
+------------------
+ f
+(1 row)
+
+SELECT json '[{"a": 1}, {"a": 2}]' @@ '$[*].a > 1';
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT json '[{"a": 1}, {"a": 2}]' @@ '$[*].a > 2';
+ ?column? 
+----------
+ f
+(1 row)
+
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index c10d909..2f1dd8d 100644
--- a/src/test/regress/parallel_schedule
+++ b/src/test/regress/parallel_schedule
@@ -115,7 +115,7 @@ test: select_views portals_p2 foreign_key cluster dependency guc bitmapops combo
 # ----------
 # Another group of parallel tests (JSON related)
 # ----------
-test: json jsonb json_encoding jsonpath jsonb_jsonpath
+test: json jsonb json_encoding jsonpath json_jsonpath jsonb_jsonpath
 
 # ----------
 # Another group of parallel tests
diff --git a/src/test/regress/serial_schedule b/src/test/regress/serial_schedule
index d2bf88b..f1fb336 100644
--- a/src/test/regress/serial_schedule
+++ b/src/test/regress/serial_schedule
@@ -158,6 +158,7 @@ test: json
 test: jsonb
 test: json_encoding
 test: jsonpath
+test: json_jsonpath
 test: jsonb_jsonpath
 test: indirect_toast
 test: equivclass
diff --git a/src/test/regress/sql/json_jsonpath.sql b/src/test/regress/sql/json_jsonpath.sql
new file mode 100644
index 0000000..73781b0
--- /dev/null
+++ b/src/test/regress/sql/json_jsonpath.sql
@@ -0,0 +1,477 @@
+select json '{"a": 12}' @? '$';
+select json '{"a": 12}' @? '1';
+select json '{"a": 12}' @? '$.a.b';
+select json '{"a": 12}' @? '$.b';
+select json '{"a": 12}' @? '$.a + 2';
+select json '{"a": 12}' @? '$.b + 2';
+select json '{"a": {"a": 12}}' @? '$.a.a';
+select json '{"a": {"a": 12}}' @? '$.*.a';
+select json '{"b": {"a": 12}}' @? '$.*.a';
+select json '{"b": {"a": 12}}' @? '$.*.b';
+select json '{"b": {"a": 12}}' @? 'strict $.*.b';
+select json '{}' @? '$.*';
+select json '{"a": 1}' @? '$.*';
+select json '{"a": {"b": 1}}' @? 'lax $.**{1}';
+select json '{"a": {"b": 1}}' @? 'lax $.**{2}';
+select json '{"a": {"b": 1}}' @? 'lax $.**{3}';
+select json '[]' @? '$[*]';
+select json '[1]' @? '$[*]';
+select json '[1]' @? '$[1]';
+select json '[1]' @? 'strict $[1]';
+select json_path_query('[1]', 'strict $[1]');
+select json '[1]' @? 'lax $[10000000000000000]';
+select json '[1]' @? 'strict $[10000000000000000]';
+select json_path_query('[1]', 'lax $[10000000000000000]');
+select json_path_query('[1]', 'strict $[10000000000000000]');
+select json '[1]' @? '$[0]';
+select json '[1]' @? '$[0.3]';
+select json '[1]' @? '$[0.5]';
+select json '[1]' @? '$[0.9]';
+select json '[1]' @? '$[1.2]';
+select json '[1]' @? 'strict $[1.2]';
+select json '{"a": [1,2,3], "b": [3,4,5]}' @? '$ ? (@.a[*] >  @.b[*])';
+select json '{"a": [1,2,3], "b": [3,4,5]}' @? '$ ? (@.a[*] >= @.b[*])';
+select json '{"a": [1,2,3], "b": [3,4,"5"]}' @? '$ ? (@.a[*] >= @.b[*])';
+select json '{"a": [1,2,3], "b": [3,4,"5"]}' @? 'strict $ ? (@.a[*] >= @.b[*])';
+select json '{"a": [1,2,3], "b": [3,4,null]}' @? '$ ? (@.a[*] >= @.b[*])';
+select json '1' @? '$ ? ((@ == "1") is unknown)';
+select json '1' @? '$ ? ((@ == 1) is unknown)';
+select json '[{"a": 1}, {"a": 2}]' @? '$[0 to 1] ? (@.a > 1)';
+
+select json_path_query('1', 'lax $.a');
+select json_path_query('1', 'strict $.a');
+select json_path_query('1', 'strict $.*');
+select json_path_query('[]', 'lax $.a');
+select json_path_query('[]', 'strict $.a');
+select json_path_query('{}', 'lax $.a');
+select json_path_query('{}', 'strict $.a');
+
+select json_path_query('1', 'strict $[1]');
+select json_path_query('1', 'strict $[*]');
+select json_path_query('[]', 'strict $[1]');
+select json_path_query('[]', 'strict $["a"]');
+
+select json_path_query('{"a": 12, "b": {"a": 13}}', '$.a');
+select json_path_query('{"a": 12, "b": {"a": 13}}', '$.b');
+select json_path_query('{"a": 12, "b": {"a": 13}}', '$.*');
+select json_path_query('{"a": 12, "b": {"a": 13}}', 'lax $.*.a');
+select json_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[*].a');
+select json_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[*].*');
+select json_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[0].a');
+select json_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[1].a');
+select json_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[2].a');
+select json_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[0,1].a');
+select json_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[0 to 10].a');
+select json_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[0 to 10 / 0].a');
+select json_path_query('[12, {"a": 13}, {"b": 14}, "ccc", true]', '$[2.5 - 1 to $.size() - 2]');
+select json_path_query('1', 'lax $[0]');
+select json_path_query('1', 'lax $[*]');
+select json_path_query('[1]', 'lax $[0]');
+select json_path_query('[1]', 'lax $[*]');
+select json_path_query('[1,2,3]', 'lax $[*]');
+select json_path_query('[1,2,3]', 'strict $[*].a');
+select json_path_query('[]', '$[last]');
+select json_path_query('[]', '$[last ? (exists(last))]');
+select json_path_query('[]', 'strict $[last]');
+select json_path_query('[1]', '$[last]');
+select json_path_query('[1,2,3]', '$[last]');
+select json_path_query('[1,2,3]', '$[last - 1]');
+select json_path_query('[1,2,3]', '$[last ? (@.type() == "number")]');
+select json_path_query('[1,2,3]', '$[last ? (@.type() == "string")]');
+
+select * from json_path_query('{"a": 10}', '$');
+select * from json_path_query('{"a": 10}', '$ ? (@.a < $value)');
+select * from json_path_query('{"a": 10}', '$ ? (@.a < $value)', '1');
+select * from json_path_query('{"a": 10}', '$ ? (@.a < $value)', '[{"value" : 13}]');
+select * from json_path_query('{"a": 10}', '$ ? (@.a < $value)', '{"value" : 13}');
+select * from json_path_query('{"a": 10}', '$ ? (@.a < $value)', '{"value" : 8}');
+select * from json_path_query('{"a": 10}', '$.a ? (@ < $value)', '{"value" : 13}');
+select * from json_path_query('[10,11,12,13,14,15]', '$[*] ? (@ < $value)', '{"value" : 13}');
+select * from json_path_query('[10,11,12,13,14,15]', '$[0,1] ? (@ < $x.value)', '{"x": {"value" : 13}}');
+select * from json_path_query('[10,11,12,13,14,15]', '$[0 to 2] ? (@ < $value)', '{"value" : 15}');
+select * from json_path_query('[1,"1",2,"2",null]', '$[*] ? (@ == "1")');
+select * from json_path_query('[1,"1",2,"2",null]', '$[*] ? (@ == $value)', '{"value" : "1"}');
+select * from json_path_query('[1,"1",2,"2",null]', '$[*] ? (@ == $value)', '{"value" : null}');
+select * from json_path_query('[1, "2", null]', '$[*] ? (@ != null)');
+select * from json_path_query('[1, "2", null]', '$[*] ? (@ == null)');
+select * from json_path_query('{}', '$ ? (@ == @)');
+select * from json_path_query('[]', 'strict $ ? (@ == @)');
+
+select json_path_query('{"a": {"b": 1}}', 'lax $.**');
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{0}');
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{0 to last}');
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{1}');
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{1 to last}');
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{2}');
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{2 to last}');
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{3 to last}');
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{last}');
+select json_path_query('{"a": {"b": 1}}', 'lax $.**.b ? (@ > 0)');
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{0}.b ? (@ > 0)');
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{1}.b ? (@ > 0)');
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{0 to last}.b ? (@ > 0)');
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{1 to last}.b ? (@ > 0)');
+select json_path_query('{"a": {"b": 1}}', 'lax $.**{1 to 2}.b ? (@ > 0)');
+select json_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**.b ? (@ > 0)');
+select json_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{0}.b ? (@ > 0)');
+select json_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{1}.b ? (@ > 0)');
+select json_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{0 to last}.b ? (@ > 0)');
+select json_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{1 to last}.b ? (@ > 0)');
+select json_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{1 to 2}.b ? (@ > 0)');
+select json_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{2 to 3}.b ? (@ > 0)');
+
+select json '{"a": {"b": 1}}' @? '$.**.b ? ( @ > 0)';
+select json '{"a": {"b": 1}}' @? '$.**{0}.b ? ( @ > 0)';
+select json '{"a": {"b": 1}}' @? '$.**{1}.b ? ( @ > 0)';
+select json '{"a": {"b": 1}}' @? '$.**{0 to last}.b ? ( @ > 0)';
+select json '{"a": {"b": 1}}' @? '$.**{1 to last}.b ? ( @ > 0)';
+select json '{"a": {"b": 1}}' @? '$.**{1 to 2}.b ? ( @ > 0)';
+select json '{"a": {"c": {"b": 1}}}' @? '$.**.b ? ( @ > 0)';
+select json '{"a": {"c": {"b": 1}}}' @? '$.**{0}.b ? ( @ > 0)';
+select json '{"a": {"c": {"b": 1}}}' @? '$.**{1}.b ? ( @ > 0)';
+select json '{"a": {"c": {"b": 1}}}' @? '$.**{0 to last}.b ? ( @ > 0)';
+select json '{"a": {"c": {"b": 1}}}' @? '$.**{1 to last}.b ? ( @ > 0)';
+select json '{"a": {"c": {"b": 1}}}' @? '$.**{1 to 2}.b ? ( @ > 0)';
+select json '{"a": {"c": {"b": 1}}}' @? '$.**{2 to 3}.b ? ( @ > 0)';
+
+select json_path_query('{"g": {"x": 2}}', '$.g ? (exists (@.x))');
+select json_path_query('{"g": {"x": 2}}', '$.g ? (exists (@.y))');
+select json_path_query('{"g": {"x": 2}}', '$.g ? (exists (@.x ? (@ >= 2) ))');
+select json_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'lax $.g ? (exists (@.x))');
+select json_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'lax $.g ? (exists (@.x + "3"))');
+select json_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'lax $.g ? ((exists (@.x + "3")) is unknown)');
+select json_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'strict $.g[*] ? (exists (@.x))');
+select json_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'strict $.g[*] ? ((exists (@.x)) is unknown)');
+select json_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'strict $.g ? (exists (@[*].x))');
+select json_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'strict $.g ? ((exists (@[*].x)) is unknown)');
+
+--test ternary logic
+select
+	x, y,
+	json_path_query(
+		'[true, false, null]',
+		'$[*] ? (@ == true  &&  ($x == true && $y == true) ||
+				 @ == false && !($x == true && $y == true) ||
+				 @ == null  &&  ($x == true && $y == true) is unknown)',
+		json_build_object('x', x, 'y', y)
+	) as "x && y"
+from
+	(values (json 'true'), ('false'), ('"null"')) x(x),
+	(values (json 'true'), ('false'), ('"null"')) y(y);
+
+select
+	x, y,
+	json_path_query(
+		'[true, false, null]',
+		'$[*] ? (@ == true  &&  ($x == true || $y == true) ||
+				 @ == false && !($x == true || $y == true) ||
+				 @ == null  &&  ($x == true || $y == true) is unknown)',
+		json_build_object('x', x, 'y', y)
+	) as "x || y"
+from
+	(values (json 'true'), ('false'), ('"null"')) x(x),
+	(values (json 'true'), ('false'), ('"null"')) y(y);
+
+select json '{"a": 1, "b":1}' @? '$ ? (@.a == @.b)';
+select json '{"c": {"a": 1, "b":1}}' @? '$ ? (@.a == @.b)';
+select json '{"c": {"a": 1, "b":1}}' @? '$.c ? (@.a == @.b)';
+select json '{"c": {"a": 1, "b":1}}' @? '$.c ? ($.c.a == @.b)';
+select json '{"c": {"a": 1, "b":1}}' @? '$.* ? (@.a == @.b)';
+select json '{"a": 1, "b":1}' @? '$.** ? (@.a == @.b)';
+select json '{"c": {"a": 1, "b":1}}' @? '$.** ? (@.a == @.b)';
+
+select json_path_query('{"c": {"a": 2, "b":1}}', '$.** ? (@.a == 1 + 1)');
+select json_path_query('{"c": {"a": 2, "b":1}}', '$.** ? (@.a == (1 + 1))');
+select json_path_query('{"c": {"a": 2, "b":1}}', '$.** ? (@.a == @.b + 1)');
+select json_path_query('{"c": {"a": 2, "b":1}}', '$.** ? (@.a == (@.b + 1))');
+select json '{"c": {"a": -1, "b":1}}' @? '$.** ? (@.a == - 1)';
+select json '{"c": {"a": -1, "b":1}}' @? '$.** ? (@.a == -1)';
+select json '{"c": {"a": -1, "b":1}}' @? '$.** ? (@.a == -@.b)';
+select json '{"c": {"a": -1, "b":1}}' @? '$.** ? (@.a == - @.b)';
+select json '{"c": {"a": 0, "b":1}}' @? '$.** ? (@.a == 1 - @.b)';
+select json '{"c": {"a": 2, "b":1}}' @? '$.** ? (@.a == 1 - - @.b)';
+select json '{"c": {"a": 0, "b":1}}' @? '$.** ? (@.a == 1 - +@.b)';
+select json '[1,2,3]' @? '$ ? (+@[*] > +2)';
+select json '[1,2,3]' @? '$ ? (+@[*] > +3)';
+select json '[1,2,3]' @? '$ ? (-@[*] < -2)';
+select json '[1,2,3]' @? '$ ? (-@[*] < -3)';
+select json '1' @? '$ ? ($ > 0)';
+
+-- arithmetic errors
+select json_path_query('[1,2,0,3]', '$[*] ? (2 / @ > 0)');
+select json_path_query('[1,2,0,3]', '$[*] ? ((2 / @ > 0) is unknown)');
+select json_path_query('0', '1 / $');
+select json_path_query('0', '1 / $ + 2');
+select json_path_query('0', '-(3 + 1 % $)');
+select json_path_query('1', '$ + "2"');
+select json_path_query('[1, 2]', '3 * $');
+select json_path_query('"a"', '-$');
+select json_path_query('[1,"2",3]', '+$');
+select json '["1",2,0,3]' @? '-$[*]';
+select json '[1,"2",0,3]' @? '-$[*]';
+select json '["1",2,0,3]' @? 'strict -$[*]';
+select json '[1,"2",0,3]' @? 'strict -$[*]';
+
+-- unwrapping of operator arguments in lax mode
+select json_path_query('{"a": [2]}', 'lax $.a * 3');
+select json_path_query('{"a": [2]}', 'lax $.a + 3');
+select json_path_query('{"a": [2, 3, 4]}', 'lax -$.a');
+-- should fail
+select json_path_query('{"a": [1, 2]}', 'lax $.a * 3');
+
+-- extension: boolean expressions
+select json_path_query('2', '$ > 1');
+select json_path_query('2', '$ <= 1');
+select json_path_query('2', '$ == "2"');
+select json '2' @? '$ == "2"';
+
+select json '2' @@ '$ > 1';
+select json '2' @@ '$ <= 1';
+select json '2' @@ '$ == "2"';
+select json '2' @@ '1';
+select json '{}' @@ '$';
+select json '[]' @@ '$';
+select json '[1,2,3]' @@ '$[*]';
+select json '[]' @@ '$[*]';
+select json_path_match('[[1, true], [2, false]]', 'strict $[*] ? (@[0] > $x) [1]', '{"x": 1}');
+select json_path_match('[[1, true], [2, false]]', 'strict $[*] ? (@[0] < $x) [1]', '{"x": 2}');
+
+select json_path_query('[null,1,true,"a",[],{}]', '$.type()');
+select json_path_query('[null,1,true,"a",[],{}]', 'lax $.type()');
+select json_path_query('[null,1,true,"a",[],{}]', '$[*].type()');
+select json_path_query('null', 'null.type()');
+select json_path_query('null', 'true.type()');
+select json_path_query('null', '123.type()');
+select json_path_query('null', '"123".type()');
+
+select json_path_query('{"a": 2}', '($.a - 5).abs() + 10');
+select json_path_query('{"a": 2.5}', '-($.a * $.a).floor() % 4.3');
+select json_path_query('[1, 2, 3]', '($[*] > 2) ? (@ == true)');
+select json_path_query('[1, 2, 3]', '($[*] > 3).type()');
+select json_path_query('[1, 2, 3]', '($[*].a > 3).type()');
+select json_path_query('[1, 2, 3]', 'strict ($[*].a > 3).type()');
+
+select json_path_query('[1,null,true,"11",[],[1],[1,2,3],{},{"a":1,"b":2}]', 'strict $[*].size()');
+select json_path_query('[1,null,true,"11",[],[1],[1,2,3],{},{"a":1,"b":2}]', 'lax $[*].size()');
+
+select json_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].abs()');
+select json_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].floor()');
+select json_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].ceiling()');
+select json_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].ceiling().abs()');
+select json_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].ceiling().abs().type()');
+
+select json_path_query('[{},1]', '$[*].keyvalue()');
+select json_path_query('{}', '$.keyvalue()');
+select json_path_query('{"a": 1, "b": [1, 2], "c": {"a": "bbb"}}', '$.keyvalue()');
+select json_path_query('[{"a": 1, "b": [1, 2]}, {"c": {"a": "bbb"}}]', '$[*].keyvalue()');
+select json_path_query('[{"a": 1, "b": [1, 2]}, {"c": {"a": "bbb"}}]', 'strict $.keyvalue()');
+select json_path_query('[{"a": 1, "b": [1, 2]}, {"c": {"a": "bbb"}}]', 'lax $.keyvalue()');
+select json_path_query('[{"a": 1, "b": [1, 2]}, {"c": {"a": "bbb"}}]', 'strict $.keyvalue().a');
+select json '{"a": 1, "b": [1, 2]}' @? 'lax $.keyvalue()';
+select json '{"a": 1, "b": [1, 2]}' @? 'lax $.keyvalue().key';
+
+select json_path_query('null', '$.double()');
+select json_path_query('true', '$.double()');
+select json_path_query('[]', '$.double()');
+select json_path_query('[]', 'strict $.double()');
+select json_path_query('{}', '$.double()');
+select json_path_query('1.23', '$.double()');
+select json_path_query('"1.23"', '$.double()');
+select json_path_query('"1.23aaa"', '$.double()');
+select json_path_query('"nan"', '$.double()');
+select json_path_query('"NaN"', '$.double()');
+select json_path_query('"inf"', '$.double()');
+select json_path_query('"-inf"', '$.double()');
+
+select json_path_query('{}', '$.abs()');
+select json_path_query('true', '$.floor()');
+select json_path_query('"1.2"', '$.ceiling()');
+
+select json_path_query('["", "a", "abc", "abcabc"]', '$[*] ? (@ starts with "abc")');
+select json_path_query('["", "a", "abc", "abcabc"]', 'strict $ ? (@[*] starts with "abc")');
+select json_path_query('["", "a", "abd", "abdabc"]', 'strict $ ? (@[*] starts with "abc")');
+select json_path_query('["abc", "abcabc", null, 1]', 'strict $ ? (@[*] starts with "abc")');
+select json_path_query('["abc", "abcabc", null, 1]', 'strict $ ? ((@[*] starts with "abc") is unknown)');
+select json_path_query('[[null, 1, "abc", "abcabc"]]', 'lax $ ? (@[*] starts with "abc")');
+select json_path_query('[[null, 1, "abd", "abdabc"]]', 'lax $ ? ((@[*] starts with "abc") is unknown)');
+select json_path_query('[null, 1, "abd", "abdabc"]', 'lax $[*] ? ((@ starts with "abc") is unknown)');
+
+select json_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "adc\nabc", "babc"]', 'lax $[*] ? (@ like_regex "^ab.*c")');
+select json_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "adc\nabc", "babc"]', 'lax $[*] ? (@ like_regex "^a  b.*  c " flag "ix")');
+select json_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "adc\nabc", "babc"]', 'lax $[*] ? (@ like_regex "^ab.*c" flag "m")');
+select json_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "adc\nabc", "babc"]', 'lax $[*] ? (@ like_regex "^ab.*c" flag "s")');
+
+select json_path_query('null', '$.datetime()');
+select json_path_query('true', '$.datetime()');
+select json_path_query('1', '$.datetime()');
+select json_path_query('[]', '$.datetime()');
+select json_path_query('[]', 'strict $.datetime()');
+select json_path_query('{}', '$.datetime()');
+select json_path_query('""', '$.datetime()');
+select json_path_query('"12:34"', '$.datetime("aaa")');
+select json_path_query('"12:34"', '$.datetime("aaa", 1)');
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH", 1)');
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH", 10000000000000)');
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH", 10000000000000)');
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH", 2147483647)');
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH", 2147483648)');
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH", -2147483647)');
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH", -2147483648)');
+select json_path_query('"aaaa"', '$.datetime("HH24")');
+
+select json '"10-03-2017"' @? '$.datetime("dd-mm-yyyy")';
+select json_path_query('"10-03-2017"', '$.datetime("dd-mm-yyyy")');
+select json_path_query('"10-03-2017"', '$.datetime("dd-mm-yyyy").type()');
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy")');
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy").type()');
+
+select json_path_query('"10-03-2017 12:34"', '       $.datetime("dd-mm-yyyy HH24:MI").type()');
+select json_path_query('"10-03-2017 12:34 +05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM").type()');
+select json_path_query('"12:34:56"', '$.datetime("HH24:MI:SS").type()');
+select json_path_query('"12:34:56 +05:20"', '$.datetime("HH24:MI:SS TZH:TZM").type()');
+
+set time zone '+00';
+
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI")');
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", "+00")');
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", "+00:12")');
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", "-00:12:34")');
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", "UTC")');
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", 12 * 60)');
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", -(5 * 3600 + 12 * 60 + 34))');
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", $tz)',
+                        json_build_object('tz', extract(timezone from now())));
+select json_path_query('"10-03-2017 12:34 +05"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+select json_path_query('"10-03-2017 12:34 -05"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+select json_path_query('"10-03-2017 12:34 +05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")');
+select json_path_query('"10-03-2017 12:34 -05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")');
+select json_path_query('"12:34"', '$.datetime("HH24:MI")');
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH")');
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH", "+00")');
+select json_path_query('"12:34 +05"', '$.datetime("HH24:MI TZH")');
+select json_path_query('"12:34 -05"', '$.datetime("HH24:MI TZH")');
+select json_path_query('"12:34 +05:20"', '$.datetime("HH24:MI TZH:TZM")');
+select json_path_query('"12:34 -05:20"', '$.datetime("HH24:MI TZH:TZM")');
+
+set time zone '+10';
+
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI")');
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", "+10")');
+select json_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH", $tz)',
+                        json_build_object('tz', extract(timezone from now())));
+select json_path_query('"10-03-2017 12:34 +05"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+select json_path_query('"10-03-2017 12:34 -05"', '$.datetime("dd-mm-yyyy HH24:MI TZH")');
+select json_path_query('"10-03-2017 12:34 +05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")');
+select json_path_query('"10-03-2017 12:34 -05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")');
+select json_path_query('"12:34"', '$.datetime("HH24:MI")');
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH")');
+select json_path_query('"12:34"', '$.datetime("HH24:MI TZH", "+10")');
+select json_path_query('"12:34 +05"', '$.datetime("HH24:MI TZH")');
+select json_path_query('"12:34 -05"', '$.datetime("HH24:MI TZH")');
+select json_path_query('"12:34 +05:20"', '$.datetime("HH24:MI TZH:TZM")');
+select json_path_query('"12:34 -05:20"', '$.datetime("HH24:MI TZH:TZM")');
+
+set time zone default;
+
+select json_path_query('"2017-03-10"', '$.datetime().type()');
+select json_path_query('"2017-03-10"', '$.datetime()');
+select json_path_query('"2017-03-10 12:34:56"', '$.datetime().type()');
+select json_path_query('"2017-03-10 12:34:56"', '$.datetime()');
+select json_path_query('"2017-03-10 12:34:56 +3"', '$.datetime().type()');
+select json_path_query('"2017-03-10 12:34:56 +3"', '$.datetime()');
+select json_path_query('"2017-03-10 12:34:56 +3:10"', '$.datetime().type()');
+select json_path_query('"2017-03-10 12:34:56 +3:10"', '$.datetime()');
+select json_path_query('"12:34:56"', '$.datetime().type()');
+select json_path_query('"12:34:56"', '$.datetime()');
+select json_path_query('"12:34:56 +3"', '$.datetime().type()');
+select json_path_query('"12:34:56 +3"', '$.datetime()');
+select json_path_query('"12:34:56 +3:10"', '$.datetime().type()');
+select json_path_query('"12:34:56 +3:10"', '$.datetime()');
+
+set time zone '+00';
+
+-- date comparison
+select json_path_query(
+	'["2017-03-10", "2017-03-11", "2017-03-09", "12:34:56", "01:02:03 +04", "2017-03-10 00:00:00", "2017-03-10 12:34:56", "2017-03-10 01:02:03 +04", "2017-03-10 03:00:00 +03"]',
+	'$[*].datetime() ? (@ == "10.03.2017".datetime("dd.mm.yyyy"))');
+select json_path_query(
+	'["2017-03-10", "2017-03-11", "2017-03-09", "12:34:56", "01:02:03 +04", "2017-03-10 00:00:00", "2017-03-10 12:34:56", "2017-03-10 01:02:03 +04", "2017-03-10 03:00:00 +03"]',
+	'$[*].datetime() ? (@ >= "10.03.2017".datetime("dd.mm.yyyy"))');
+select json_path_query(
+	'["2017-03-10", "2017-03-11", "2017-03-09", "12:34:56", "01:02:03 +04", "2017-03-10 00:00:00", "2017-03-10 12:34:56", "2017-03-10 01:02:03 +04", "2017-03-10 03:00:00 +03"]',
+	'$[*].datetime() ? (@ <  "10.03.2017".datetime("dd.mm.yyyy"))');
+
+-- time comparison
+select json_path_query(
+	'["12:34:00", "12:35:00", "12:36:00", "12:35:00 +00", "12:35:00 +01", "13:35:00 +01", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +01"]',
+	'$[*].datetime() ? (@ == "12:35".datetime("HH24:MI"))');
+select json_path_query(
+	'["12:34:00", "12:35:00", "12:36:00", "12:35:00 +00", "12:35:00 +01", "13:35:00 +01", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +01"]',
+	'$[*].datetime() ? (@ >= "12:35".datetime("HH24:MI"))');
+select json_path_query(
+	'["12:34:00", "12:35:00", "12:36:00", "12:35:00 +00", "12:35:00 +01", "13:35:00 +01", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +01"]',
+	'$[*].datetime() ? (@ <  "12:35".datetime("HH24:MI"))');
+
+-- timetz comparison
+select json_path_query(
+	'["12:34:00 +01", "12:35:00 +01", "12:36:00 +01", "12:35:00 +02", "12:35:00 -02", "10:35:00", "11:35:00", "12:35:00", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +1"]',
+	'$[*].datetime() ? (@ == "12:35 +1".datetime("HH24:MI TZH"))');
+select json_path_query(
+	'["12:34:00 +01", "12:35:00 +01", "12:36:00 +01", "12:35:00 +02", "12:35:00 -02", "10:35:00", "11:35:00", "12:35:00", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +1"]',
+	'$[*].datetime() ? (@ >= "12:35 +1".datetime("HH24:MI TZH"))');
+select json_path_query(
+	'["12:34:00 +01", "12:35:00 +01", "12:36:00 +01", "12:35:00 +02", "12:35:00 -02", "10:35:00", "11:35:00", "12:35:00", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +1"]',
+	'$[*].datetime() ? (@ <  "12:35 +1".datetime("HH24:MI TZH"))');
+
+-- timestamp comparison
+select json_path_query(
+	'["2017-03-10 12:34:00", "2017-03-10 12:35:00", "2017-03-10 12:36:00", "2017-03-10 12:35:00 +01", "2017-03-10 13:35:00 +01", "2017-03-10 12:35:00 -01", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ == "10.03.2017 12:35".datetime("dd.mm.yyyy HH24:MI"))');
+select json_path_query(
+	'["2017-03-10 12:34:00", "2017-03-10 12:35:00", "2017-03-10 12:36:00", "2017-03-10 12:35:00 +01", "2017-03-10 13:35:00 +01", "2017-03-10 12:35:00 -01", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ >= "10.03.2017 12:35".datetime("dd.mm.yyyy HH24:MI"))');
+select json_path_query(
+	'["2017-03-10 12:34:00", "2017-03-10 12:35:00", "2017-03-10 12:36:00", "2017-03-10 12:35:00 +01", "2017-03-10 13:35:00 +01", "2017-03-10 12:35:00 -01", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ < "10.03.2017 12:35".datetime("dd.mm.yyyy HH24:MI"))');
+
+-- timestamptz comparison
+select json_path_query(
+	'["2017-03-10 12:34:00 +01", "2017-03-10 12:35:00 +01", "2017-03-10 12:36:00 +01", "2017-03-10 12:35:00 +02", "2017-03-10 12:35:00 -02", "2017-03-10 10:35:00", "2017-03-10 11:35:00", "2017-03-10 12:35:00", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ == "10.03.2017 12:35 +1".datetime("dd.mm.yyyy HH24:MI TZH"))');
+select json_path_query(
+	'["2017-03-10 12:34:00 +01", "2017-03-10 12:35:00 +01", "2017-03-10 12:36:00 +01", "2017-03-10 12:35:00 +02", "2017-03-10 12:35:00 -02", "2017-03-10 10:35:00", "2017-03-10 11:35:00", "2017-03-10 12:35:00", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ >= "10.03.2017 12:35 +1".datetime("dd.mm.yyyy HH24:MI TZH"))');
+select json_path_query(
+	'["2017-03-10 12:34:00 +01", "2017-03-10 12:35:00 +01", "2017-03-10 12:36:00 +01", "2017-03-10 12:35:00 +02", "2017-03-10 12:35:00 -02", "2017-03-10 10:35:00", "2017-03-10 11:35:00", "2017-03-10 12:35:00", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56 +01"]',
+	'$[*].datetime() ? (@ < "10.03.2017 12:35 +1".datetime("dd.mm.yyyy HH24:MI TZH"))');
+
+set time zone default;
+
+-- jsonpath operators
+
+SELECT json_path_query('[{"a": 1}, {"a": 2}]', '$[*]');
+SELECT json_path_query('[{"a": 1}, {"a": 2}]', '$[*] ? (@.a > 10)');
+
+SELECT json_path_query_array('[{"a": 1}, {"a": 2}, {}]', 'strict $[*].a');
+SELECT json_path_query_array('[{"a": 1}, {"a": 2}]', '$[*].a');
+SELECT json_path_query_array('[{"a": 1}, {"a": 2}]', '$[*].a ? (@ == 1)');
+SELECT json_path_query_array('[{"a": 1}, {"a": 2}]', '$[*].a ? (@ > 10)');
+SELECT json_path_query_array('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*].a ? (@ > $min && @ < $max)', '{"min": 1, "max": 4}');
+SELECT json_path_query_array('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*].a ? (@ > $min && @ < $max)', '{"min": 3, "max": 4}');
+
+SELECT json_path_query_first('[{"a": 1}, {"a": 2}, {}]', 'strict $[*].a');
+SELECT json_path_query_first('[{"a": 1}, {"a": 2}]', '$[*].a');
+SELECT json_path_query_first('[{"a": 1}, {"a": 2}]', '$[*].a ? (@ == 1)');
+SELECT json_path_query_first('[{"a": 1}, {"a": 2}]', '$[*].a ? (@ > 10)');
+SELECT json_path_query_first('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*].a ? (@ > $min && @ < $max)', '{"min": 1, "max": 4}');
+SELECT json_path_query_first('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*].a ? (@ > $min && @ < $max)', '{"min": 3, "max": 4}');
+
+SELECT json '[{"a": 1}, {"a": 2}]' @? '$[*].a ? (@ > 1)';
+SELECT json '[{"a": 1}, {"a": 2}]' @? '$[*] ? (@.a > 2)';
+SELECT json_path_exists('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*] ? (@.a > $min && @.a < $max)', '{"min": 1, "max": 4}');
+SELECT json_path_exists('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*] ? (@.a > $min && @.a < $max)', '{"min": 3, "max": 4}');
+
+SELECT json '[{"a": 1}, {"a": 2}]' @@ '$[*].a > 1';
+SELECT json '[{"a": 1}, {"a": 2}]' @@ '$[*].a > 2';
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index daaafa3..5a1518e 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -1097,6 +1097,7 @@ JsValue
 JsonAggState
 JsonBaseObjectInfo
 JsonHashEntry
+JsonItem
 JsonItemStack
 JsonItemStackEntry
 JsonIterateStringValuesAction
@@ -1112,6 +1113,7 @@ JsonPathItemType
 JsonPathParseItem
 JsonPathParseResult
 JsonPathPredicateCallback
+JsonPathUserFuncContext
 JsonPathVariable
 JsonPathVariable_cb
 JsonSemAction
-- 
2.7.4

  [text/x-patch] 0005-Jsonpath-GIN-support-v34.patch (47.0K, ../a3be6a7a-77d3-0e88-4f9d-4f725d11d7cd@postgrespro.ru/7-0005-Jsonpath-GIN-support-v34.patch)
  download | inline diff:
From 203e42eb03b2eabf604aeae6aa782a9d3a295e9a Mon Sep 17 00:00:00 2001
From: Nikita Glukhov <n.gluhov@postgrespro.ru>
Date: Fri, 1 Mar 2019 03:15:18 +0300
Subject: [PATCH 05/13] Jsonpath GIN support

---
 doc/src/sgml/gin.sgml                    |   4 +
 src/backend/utils/adt/jsonb_gin.c        | 903 ++++++++++++++++++++++++++++---
 src/include/catalog/pg_amop.dat          |  12 +
 src/include/utils/jsonb.h                |   3 +
 src/include/utils/jsonpath.h             |   2 +
 src/test/regress/expected/jsonb.out      | 453 ++++++++++++++++
 src/test/regress/expected/opr_sanity.out |   4 +-
 src/test/regress/sql/jsonb.sql           |  79 +++
 8 files changed, 1384 insertions(+), 76 deletions(-)

diff --git a/doc/src/sgml/gin.sgml b/doc/src/sgml/gin.sgml
index cc7cd1e..ccab220 100644
--- a/doc/src/sgml/gin.sgml
+++ b/doc/src/sgml/gin.sgml
@@ -102,6 +102,8 @@
        <literal>?&amp;</literal>
        <literal>?|</literal>
        <literal>@&gt;</literal>
+       <literal>@?</literal>
+       <literal>@@</literal>
       </entry>
      </row>
      <row>
@@ -109,6 +111,8 @@
       <entry><type>jsonb</type></entry>
       <entry>
        <literal>@&gt;</literal>
+       <literal>@?</literal>
+       <literal>@@</literal>
       </entry>
      </row>
      <row>
diff --git a/src/backend/utils/adt/jsonb_gin.c b/src/backend/utils/adt/jsonb_gin.c
index a7f73b6..c3231f5 100644
--- a/src/backend/utils/adt/jsonb_gin.c
+++ b/src/backend/utils/adt/jsonb_gin.c
@@ -13,6 +13,7 @@
  */
 #include "postgres.h"
 
+#include "miscadmin.h"
 #include "access/gin.h"
 #include "access/hash.h"
 #include "access/stratnum.h"
@@ -20,6 +21,7 @@
 #include "catalog/pg_type.h"
 #include "utils/builtins.h"
 #include "utils/jsonb.h"
+#include "utils/jsonpath.h"
 #include "utils/varlena.h"
 
 typedef struct PathHashStack
@@ -28,9 +30,120 @@ typedef struct PathHashStack
 	struct PathHashStack *parent;
 } PathHashStack;
 
+/* Buffer for GIN entries */
+typedef struct GinEntries
+{
+	Datum	   *buf;
+	int			count;
+	int			allocated;
+} GinEntries;
+
+typedef enum GinJsonPathNodeType
+{
+	GIN_JSP_OR,
+	GIN_JSP_AND,
+	GIN_JSP_ENTRY
+} GinJsonPathNodeType;
+
+typedef struct GinJsonPathNode GinJsonPathNode;
+
+/* Node in jsonpath expression tree */
+struct GinJsonPathNode
+{
+	GinJsonPathNodeType type;
+	union
+	{
+		int			nargs;			/* valid for OR and AND nodes */
+		int			entryIndex;		/* index in GinEntries array, valid for
+									 * ENTRY nodes after entries output */
+		Datum		entryDatum;		/* path hash or key name/scalar, valid
+									 * for ENTRY nodes before entries output */
+	} val;
+	GinJsonPathNode *args[FLEXIBLE_ARRAY_MEMBER]; /* valid for OR and AND nodes */
+};
+
+/*
+ * Single entry in the extracted json path (used for jsonb_ops only).
+ * Path entry can be one of:
+ *   .key        (key name is stored in 'entry' field)
+ *   .*
+ *   .**
+ *   [index]
+ *   [*]
+ * Entry type is stored in 'type' field.
+ */
+typedef struct GinJsonPathEntry
+{
+	struct GinJsonPathEntry *parent;
+	Datum		entry;				/* key name or NULL */
+	JsonPathItemType type;
+} GinJsonPathEntry;
+
+/* GIN representation of the extracted json path */
+typedef union GinJsonPath
+{
+	GinJsonPathEntry *entries;		/* list of path entries (jsonb_ops) */
+	uint32		hash;				/* hash of the path (jsonb_path_ops) */
+} GinJsonPath;
+
+typedef struct GinJsonPathContext GinJsonPathContext;
+
+/* Add entry to the extracted json path */
+typedef bool (*GinAddPathEntryFunc)(GinJsonPath *path, JsonPathItem *jsp);
+typedef List *(*GinExtractPathNodesFunc)(GinJsonPathContext *cxt,
+										 GinJsonPath path, JsonbValue *scalar,
+										 List *nodes);
+
+/* Context for jsonpath entries extraction */
+struct GinJsonPathContext
+{
+	GinAddPathEntryFunc add_path_entry;
+	GinExtractPathNodesFunc extract_path_nodes;
+	bool		lax;
+};
+
 static Datum make_text_key(char flag, const char *str, int len);
 static Datum make_scalar_key(const JsonbValue *scalarVal, bool is_key);
 
+static GinJsonPathNode *extract_jsp_bool_expr(GinJsonPathContext *cxt,
+					  GinJsonPath path, JsonPathItem *jsp, bool not);
+
+
+/* Init GIN entry buffer. */
+static void
+init_entries(GinEntries *entries, int preallocated)
+{
+	entries->allocated = preallocated;
+	entries->buf = preallocated ? palloc(sizeof(Datum) * preallocated) : NULL;
+	entries->count = 0;
+}
+
+/* Add GIN entry to the buffer. */
+static int
+add_entry(GinEntries *entries, Datum entry)
+{
+	int			id = entries->count;
+
+	if (entries->count >= entries->allocated)
+	{
+		if (entries->allocated)
+		{
+			entries->allocated *= 2;
+			entries->buf = repalloc(entries->buf,
+									sizeof(Datum) * entries->allocated);
+		}
+		else
+		{
+			entries->allocated = 8;
+			entries->buf = palloc(sizeof(Datum) * entries->allocated);
+		}
+	}
+
+	entries->buf[entries->count++] = entry;
+
+	return id;
+}
+
 /*
  *
  * jsonb_ops GIN opclass support functions
@@ -68,12 +181,11 @@ gin_extract_jsonb(PG_FUNCTION_ARGS)
 {
 	Jsonb	   *jb = (Jsonb *) PG_GETARG_JSONB_P(0);
 	int32	   *nentries = (int32 *) PG_GETARG_POINTER(1);
-	int			total = 2 * JB_ROOT_COUNT(jb);
+	int			total = JB_ROOT_COUNT(jb);
 	JsonbIterator *it;
 	JsonbValue	v;
 	JsonbIteratorToken r;
-	int			i = 0;
-	Datum	   *entries;
+	GinEntries	entries;
 
 	/* If the root level is empty, we certainly have no keys */
 	if (total == 0)
@@ -83,30 +195,23 @@ gin_extract_jsonb(PG_FUNCTION_ARGS)
 	}
 
 	/* Otherwise, use 2 * root count as initial estimate of result size */
-	entries = (Datum *) palloc(sizeof(Datum) * total);
+	init_entries(&entries, 2 * total);
 
 	it = JsonbIteratorInit(&jb->root);
 
 	while ((r = JsonbIteratorNext(&it, &v, false)) != WJB_DONE)
 	{
-		/* Since we recurse into the object, we might need more space */
-		if (i >= total)
-		{
-			total *= 2;
-			entries = (Datum *) repalloc(entries, sizeof(Datum) * total);
-		}
-
 		switch (r)
 		{
 			case WJB_KEY:
-				entries[i++] = make_scalar_key(&v, true);
+				add_entry(&entries, make_scalar_key(&v, true));
 				break;
 			case WJB_ELEM:
 				/* Pretend string array elements are keys, see jsonb.h */
-				entries[i++] = make_scalar_key(&v, (v.type == jbvString));
+				add_entry(&entries, make_scalar_key(&v, v.type == jbvString));
 				break;
 			case WJB_VALUE:
-				entries[i++] = make_scalar_key(&v, false);
+				add_entry(&entries, make_scalar_key(&v, false));
 				break;
 			default:
 				/* we can ignore structural items */
@@ -114,9 +219,575 @@ gin_extract_jsonb(PG_FUNCTION_ARGS)
 		}
 	}
 
-	*nentries = i;
+	*nentries = entries.count;
 
-	PG_RETURN_POINTER(entries);
+	PG_RETURN_POINTER(entries.buf);
+}
+
+/* Append key name to the path (jsonb_ops). */
+static bool
+jsonb_ops__add_path_entry(GinJsonPath *path, JsonPathItem *jsp)
+{
+	GinJsonPathEntry *pentry;
+	Datum		entry;
+
+	switch (jsp->type)
+	{
+		case jpiRoot:
+			path->entries = NULL;	/* reset path */
+			return true;
+
+		case jpiKey:
+			{
+				int			len;
+				char	   *key = jspGetString(jsp, &len);
+
+				entry = make_text_key(JGINFLAG_KEY, key, len);
+				break;
+			}
+
+		case jpiAny:
+		case jpiAnyKey:
+		case jpiAnyArray:
+		case jpiIndexArray:
+			entry = PointerGetDatum(NULL);
+			break;
+
+		default:
+			/* other path items like item methods are not supported */
+			return false;
+	}
+
+	pentry = palloc(sizeof(*pentry));
+
+	pentry->type = jsp->type;
+	pentry->entry = entry;
+	pentry->parent = path->entries;
+
+	path->entries = pentry;
+
+	return true;
+}
+
+/* Combine existing path hash with next key hash (jsonb_path_ops). */
+static bool
+jsonb_path_ops__add_path_entry(GinJsonPath *path, JsonPathItem *jsp)
+{
+	switch (jsp->type)
+	{
+		case jpiRoot:
+			path->hash = 0;	/* reset path hash */
+			return true;
+
+		case jpiKey:
+			{
+				JsonbValue 	jbv;
+
+				jbv.type = jbvString;
+				jbv.val.string.val = jspGetString(jsp, &jbv.val.string.len);
+
+				JsonbHashScalarValue(&jbv, &path->hash);
+				return true;
+			}
+
+		case jpiIndexArray:
+		case jpiAnyArray:
+			return true;	/* path hash is unchanged */
+
+		default:
+			/* other items (wildcard paths, item methods) are not supported */
+			return false;
+	}
+}
+
+static inline GinJsonPathNode *
+make_jsp_entry_node(Datum entry)
+{
+	GinJsonPathNode *node = palloc(offsetof(GinJsonPathNode, args));
+
+	node->type = GIN_JSP_ENTRY;
+	node->val.entryDatum = entry;
+
+	return node;
+}
+
+static inline GinJsonPathNode *
+make_jsp_entry_node_scalar(JsonbValue *scalar, bool iskey)
+{
+	return make_jsp_entry_node(make_scalar_key(scalar, iskey));
+}
+
+static inline GinJsonPathNode *
+make_jsp_expr_node(GinJsonPathNodeType type, int nargs)
+{
+	GinJsonPathNode *node = palloc(offsetof(GinJsonPathNode, args) +
+								   sizeof(node->args[0]) * nargs);
+
+	node->type = type;
+	node->val.nargs = nargs;
+
+	return node;
+}
+
+static inline GinJsonPathNode *
+make_jsp_expr_node_args(GinJsonPathNodeType type, List *args)
+{
+	GinJsonPathNode *node = make_jsp_expr_node(type, list_length(args));
+	ListCell   *lc;
+	int			i = 0;
+
+	foreach(lc, args)
+		node->args[i++] = lfirst(lc);
+
+	return node;
+}
+
+static inline GinJsonPathNode *
+make_jsp_expr_node_binary(GinJsonPathNodeType type,
+						  GinJsonPathNode *arg1, GinJsonPathNode *arg2)
+{
+	GinJsonPathNode *node = make_jsp_expr_node(type, 2);
+
+	node->args[0] = arg1;
+	node->args[1] = arg2;
+
+	return node;
+}
+
+/* Append a list of nodes from the jsonpath (jsonb_ops). */
+static List *
+jsonb_ops__extract_path_nodes(GinJsonPathContext *cxt, GinJsonPath path,
+							  JsonbValue *scalar, List *nodes)
+{
+	GinJsonPathEntry *pentry;
+
+	/* append path entry nodes */
+	for (pentry = path.entries; pentry; pentry = pentry->parent)
+	{
+		if (pentry->type == jpiKey)		/* only keys are indexed */
+			nodes = lappend(nodes, make_jsp_entry_node(pentry->entry));
+	}
+
+	if (scalar)
+	{
+		/* Append scalar node for equality queries. */
+		GinJsonPathNode *node;
+
+		if (scalar->type == jbvString)
+		{
+			GinJsonPathEntry *last = path.entries;
+			GinTernaryValue array_access;
+
+			/*
+			 * Create OR-node when the string scalar can be matched as a key
+			 * and a non-key. It is possible in lax mode where arrays are
+			 * automatically unwrapped, or in strict mode for jpiAny items.
+			 */
+
+			if (cxt->lax)
+				array_access = GIN_MAYBE;
+			else if (!last)	/* root ($) */
+				array_access = GIN_FALSE;
+			else if (last->type == jpiAnyArray || last->type == jpiIndexArray)
+				array_access = GIN_TRUE;
+			else if (last->type == jpiAny)
+				array_access = GIN_MAYBE;
+			else
+				array_access = GIN_FALSE;
+
+			if (array_access == GIN_MAYBE)
+			{
+				GinJsonPathNode *n1 = make_jsp_entry_node_scalar(scalar, true);
+				GinJsonPathNode *n2 = make_jsp_entry_node_scalar(scalar, false);
+
+				node = make_jsp_expr_node_binary(GIN_JSP_OR, n1, n2);
+			}
+			else
+			{
+				node = make_jsp_entry_node_scalar(scalar,
+												  array_access == GIN_TRUE);
+			}
+		}
+		else
+		{
+			node = make_jsp_entry_node_scalar(scalar, false);
+		}
+
+		nodes = lappend(nodes, node);
+	}
+
+	return nodes;
+}
+
+/* Append a list of nodes from the jsonpath (jsonb_path_ops). */
+static List *
+jsonb_path_ops__extract_path_nodes(GinJsonPathContext *cxt, GinJsonPath path,
+								   JsonbValue *scalar, List *nodes)
+{
+	if (scalar)
+	{
+		/* append path hash node for equality queries */
+		uint32		hash = path.hash;
+
+		JsonbHashScalarValue(scalar, &hash);
+
+		return lappend(nodes,
+					   make_jsp_entry_node(UInt32GetDatum(hash)));
+	}
+	else
+	{
+		/* jsonb_path_ops doesn't support EXISTS queries => nothing to append */
+		return nodes;
+	}
+}
+
+/*
+ * Extract a list of expression nodes that need to be AND-ed by the caller.
+ * Extracted expression is 'path == scalar' if 'scalar' is non-NULL, and
+ * 'EXISTS(path)' otherwise.
+ */
+static List *
+extract_jsp_path_expr_nodes(GinJsonPathContext *cxt, GinJsonPath path,
+							JsonPathItem *jsp, JsonbValue *scalar)
+{
+	JsonPathItem next;
+	List	   *nodes = NIL;
+
+	for (;;)
+	{
+		switch (jsp->type)
+		{
+			case jpiCurrent:
+				break;
+
+			case jpiFilter:
+				{
+					JsonPathItem arg;
+					GinJsonPathNode *filter;
+
+					jspGetArg(jsp, &arg);
+
+					filter = extract_jsp_bool_expr(cxt, path, &arg, false);
+
+					if (filter)
+						nodes = lappend(nodes, filter);
+
+					break;
+				}
+
+			default:
+				if (!cxt->add_path_entry(&path, jsp))
+					/*
+					 * Path is not supported by the index opclass, return only
+					 * the extracted filter nodes.
+					 */
+					return nodes;
+				break;
+		}
+
+		if (!jspGetNext(jsp, &next))
+			break;
+
+		jsp = &next;
+	}
+
+	/*
+	 * Append nodes from the path expression itself to the already extracted
+	 * list of filter nodes.
+	 */
+	return cxt->extract_path_nodes(cxt, path, scalar, nodes);
+}
+
+/*
+ * Extract an expression node from one of following jsonpath path expressions:
+ *   EXISTS(jsp)    (when 'scalar' is NULL)
+ *   jsp == scalar  (when 'scalar' is not NULL).
+ *
+ * The current path (@) is passed in 'path'.
+ */
+static GinJsonPathNode *
+extract_jsp_path_expr(GinJsonPathContext *cxt, GinJsonPath path,
+					  JsonPathItem *jsp, JsonbValue *scalar)
+{
+	/* extract a list of nodes to be AND-ed */
+	List	   *nodes = extract_jsp_path_expr_nodes(cxt, path, jsp, scalar);
+
+	if (list_length(nodes) <= 0)
+		/* no nodes were extracted => full scan is needed for this path */
+		return NULL;
+
+	if (list_length(nodes) == 1)
+		return linitial(nodes);		/* avoid extra AND-node */
+
+	/* construct AND-node for path with filters */
+	return make_jsp_expr_node_args(GIN_JSP_AND, nodes);
+}
+
+/* Recursively extract nodes from the boolean jsonpath expression. */
+static GinJsonPathNode *
+extract_jsp_bool_expr(GinJsonPathContext *cxt, GinJsonPath path,
+					  JsonPathItem *jsp, bool not)
+{
+	check_stack_depth();
+
+	switch (jsp->type)
+	{
+		case jpiAnd:		/* expr && expr */
+		case jpiOr:			/* expr || expr */
+			{
+				JsonPathItem arg;
+				GinJsonPathNode *larg;
+				GinJsonPathNode *rarg;
+				GinJsonPathNodeType type;
+
+				jspGetLeftArg(jsp, &arg);
+				larg = extract_jsp_bool_expr(cxt, path, &arg, not);
+
+				jspGetRightArg(jsp, &arg);
+				rarg = extract_jsp_bool_expr(cxt, path, &arg, not);
+
+				if (!larg || !rarg)
+				{
+					if (jsp->type == jpiOr)
+						return NULL;
+
+					return larg ? larg : rarg;
+				}
+
+				type = not ^ (jsp->type == jpiAnd) ? GIN_JSP_AND : GIN_JSP_OR;
+
+				return make_jsp_expr_node_binary(type, larg, rarg);
+			}
+
+		case jpiNot:		/* !expr  */
+			{
+				JsonPathItem arg;
+
+				jspGetArg(jsp, &arg);
+
+				/* extract child expression inverting 'not' flag */
+				return extract_jsp_bool_expr(cxt, path, &arg, !not);
+			}
+
+		case jpiExists:		/* EXISTS(path) */
+			{
+				JsonPathItem arg;
+
+				if (not)
+					return NULL;	/* NOT EXISTS is not supported */
+
+				jspGetArg(jsp, &arg);
+
+				return extract_jsp_path_expr(cxt, path, &arg, NULL);
+			}
+
+		case jpiNotEqual:
+			/*
+			 * 'not' == true case is not supported here because
+			 * '!(path != scalar)' is not equivalent to 'path == scalar' in the
+			 * general case because of sequence comparison semantics:
+			 *   'path == scalar'  === 'EXISTS (path, @ == scalar)',
+			 * '!(path != scalar)' === 'FOR_ALL(path, @ == scalar)'.
+			 * So, we should translate '!(path != scalar)' into GIN query
+			 * 'path == scalar || EMPTY(path)', but 'EMPTY(path)' queries
+			 * are not supported by the both jsonb opclasses.  However in strict
+			 * mode we could omit 'EMPTY(path)' part if the path can return
+			 * exactly one item (it does not contain wildcard accessors or
+			 * item methods like .keyvalue() etc.).
+			 */
+			return NULL;
+
+		case jpiEqual:		/* path == scalar */
+			{
+				JsonPathItem left_item;
+				JsonPathItem right_item;
+				JsonPathItem *path_item;
+				JsonPathItem *scalar_item;
+				JsonbValue	scalar;
+
+
+
+				if (not)
+					return NULL;
+
+				jspGetLeftArg(jsp, &left_item);
+				jspGetRightArg(jsp, &right_item);
+
+				if (jspIsScalar(left_item.type))
+				{
+					scalar_item = &left_item;
+					path_item = &right_item;
+				}
+				else if (jspIsScalar(right_item.type))
+				{
+					scalar_item = &right_item;
+					path_item = &left_item;
+				}
+				else
+					return NULL; /* at least one operand should be a scalar */
+
+				switch (scalar_item->type)
+				{
+					case jpiNull:
+						scalar.type = jbvNull;
+						break;
+					case jpiBool:
+						scalar.type = jbvBool;
+						scalar.val.boolean = !!*scalar_item->content.value.data;
+						break;
+					case jpiNumeric:
+						scalar.type = jbvNumeric;
+						scalar.val.numeric =
+							(Numeric) scalar_item->content.value.data;
+						break;
+					case jpiString:
+						scalar.type = jbvString;
+						scalar.val.string.val = scalar_item->content.value.data;
+						scalar.val.string.len =
+							scalar_item->content.value.datalen;
+						break;
+					default:
+						elog(ERROR, "invalid scalar jsonpath item type: %d",
+							 scalar_item->type);
+						return NULL;
+				}
+
+				return extract_jsp_path_expr(cxt, path, path_item, &scalar);
+			}
+
+		default:
+			return NULL;	/* not a boolean expression */
+	}
+}
+
+/* Recursively emit all GIN entries found in the node tree */
+static void
+emit_jsp_entries(GinJsonPathNode *node, GinEntries *entries)
+{
+	check_stack_depth();
+
+	switch (node->type)
+	{
+		case GIN_JSP_ENTRY:
+			/* replace datum with its index in the array */
+			node->val.entryIndex = add_entry(entries, node->val.entryDatum);
+			break;
+
+		case GIN_JSP_OR:
+		case GIN_JSP_AND:
+			{
+				int			i;
+
+				for (i = 0; i < node->val.nargs; i++)
+					emit_jsp_entries(node->args[i], entries);
+
+				break;
+			}
+	}
+}
+
+/*
+ * Recursively extract GIN entries from jsonpath query.
+ * Root expression node is put into (*extra_data)[0].
+ */
+static Datum *
+extract_jsp_query(JsonPath *jp, StrategyNumber strat, bool pathOps,
+				  int32 *nentries, Pointer **extra_data)
+{
+	GinJsonPathContext cxt;
+	JsonPathItem root;
+	GinJsonPathNode *node;
+	GinJsonPath path = { 0 };
+	GinEntries	entries = { 0 };
+
+	cxt.lax = (jp->header & JSONPATH_LAX) != 0;
+
+	if (pathOps)
+	{
+		cxt.add_path_entry = jsonb_path_ops__add_path_entry;
+		cxt.extract_path_nodes = jsonb_path_ops__extract_path_nodes;
+	}
+	else
+	{
+		cxt.add_path_entry = jsonb_ops__add_path_entry;
+		cxt.extract_path_nodes = jsonb_ops__extract_path_nodes;
+	}
+
+	jspInit(&root, jp);
+
+	node = strat == JsonbJsonpathExistsStrategyNumber
+		? extract_jsp_path_expr(&cxt, path, &root, NULL)
+		: extract_jsp_bool_expr(&cxt, path, &root, false);
+
+	if (!node)
+	{
+		*nentries = 0;
+		return NULL;
+	}
+
+	emit_jsp_entries(node, &entries);
+
+	*nentries = entries.count;
+	if (!*nentries)
+		return NULL;
+
+	*extra_data = palloc0(sizeof(**extra_data) * entries.count);
+	**extra_data = (Pointer) node;
+
+	return entries.buf;
+}
+
+/*
+ * Recursively execute jsonpath expression.
+ * 'check' is a bool[] or a GinTernaryValue[] depending on 'ternary' flag.
+ */
+static GinTernaryValue
+execute_jsp_expr(GinJsonPathNode *node, void *check, bool ternary)
+{
+	GinTernaryValue	res;
+	GinTernaryValue	v;
+	int			i;
+
+	switch (node->type)
+	{
+		case GIN_JSP_AND:
+			res = GIN_TRUE;
+			for (i = 0; i < node->val.nargs; i++)
+			{
+				v = execute_jsp_expr(node->args[i], check, ternary);
+				if (v == GIN_FALSE)
+					return GIN_FALSE;
+				else if (v == GIN_MAYBE)
+					res = GIN_MAYBE;
+			}
+			return res;
+
+		case GIN_JSP_OR:
+			res = GIN_FALSE;
+			for (i = 0; i < node->val.nargs; i++)
+			{
+				v = execute_jsp_expr(node->args[i], check, ternary);
+				if (v == GIN_TRUE)
+					return GIN_TRUE;
+				else if (v == GIN_MAYBE)
+					res = GIN_MAYBE;
+			}
+			return res;
+
+		case GIN_JSP_ENTRY:
+			{
+				int			index = node->val.entryIndex;
+				bool		maybe = ternary
+					? ((GinTernaryValue *) check)[index] != GIN_FALSE
+					: ((bool *) check)[index];
+
+				return maybe ? GIN_MAYBE : GIN_FALSE;
+			}
+
+		default:
+			elog(ERROR, "invalid jsonpath gin node type: %d", node->type);
+			return GIN_FALSE;
+	}
 }
 
 Datum
@@ -181,6 +852,18 @@ gin_extract_jsonb_query(PG_FUNCTION_ARGS)
 		if (j == 0 && strategy == JsonbExistsAllStrategyNumber)
 			*searchMode = GIN_SEARCH_MODE_ALL;
 	}
+	else if (strategy == JsonbJsonpathPredicateStrategyNumber ||
+			 strategy == JsonbJsonpathExistsStrategyNumber)
+	{
+		JsonPath   *jp = PG_GETARG_JSONPATH_P(0);
+		Pointer	  **extra_data = (Pointer **) PG_GETARG_POINTER(4);
+
+		entries = extract_jsp_query(jp, strategy, false, nentries,
+											 extra_data);
+
+		if (!entries)
+			*searchMode = GIN_SEARCH_MODE_ALL;
+	}
 	else
 	{
 		elog(ERROR, "unrecognized strategy number: %d", strategy);
@@ -199,7 +882,7 @@ gin_consistent_jsonb(PG_FUNCTION_ARGS)
 	/* Jsonb	   *query = PG_GETARG_JSONB_P(2); */
 	int32		nkeys = PG_GETARG_INT32(3);
 
-	/* Pointer	   *extra_data = (Pointer *) PG_GETARG_POINTER(4); */
+	Pointer	   *extra_data = (Pointer *) PG_GETARG_POINTER(4);
 	bool	   *recheck = (bool *) PG_GETARG_POINTER(5);
 	bool		res = true;
 	int32		i;
@@ -256,6 +939,22 @@ gin_consistent_jsonb(PG_FUNCTION_ARGS)
 			}
 		}
 	}
+	else if (strategy == JsonbJsonpathPredicateStrategyNumber ||
+			 strategy == JsonbJsonpathExistsStrategyNumber)
+	{
+		*recheck = true;
+
+		if (nkeys <= 0)
+		{
+			res = true;
+		}
+		else
+		{
+			Assert(extra_data && extra_data[0]);
+			res = execute_jsp_expr((GinJsonPathNode *) extra_data[0], check,
+								   false) != GIN_FALSE;
+		}
+	}
 	else
 		elog(ERROR, "unrecognized strategy number: %d", strategy);
 
@@ -270,8 +969,7 @@ gin_triconsistent_jsonb(PG_FUNCTION_ARGS)
 
 	/* Jsonb	   *query = PG_GETARG_JSONB_P(2); */
 	int32		nkeys = PG_GETARG_INT32(3);
-
-	/* Pointer	   *extra_data = (Pointer *) PG_GETARG_POINTER(4); */
+	Pointer	   *extra_data = (Pointer *) PG_GETARG_POINTER(4);
 	GinTernaryValue res = GIN_MAYBE;
 	int32		i;
 
@@ -308,6 +1006,20 @@ gin_triconsistent_jsonb(PG_FUNCTION_ARGS)
 			}
 		}
 	}
+	else if (strategy == JsonbJsonpathPredicateStrategyNumber ||
+			 strategy == JsonbJsonpathExistsStrategyNumber)
+	{
+		if (nkeys <= 0)
+		{
+			res = GIN_MAYBE;
+		}
+		else
+		{
+			Assert(extra_data && extra_data[0]);
+			res = execute_jsp_expr((GinJsonPathNode *) extra_data[0], check,
+								   true);
+		}
+	}
 	else
 		elog(ERROR, "unrecognized strategy number: %d", strategy);
 
@@ -331,14 +1043,13 @@ gin_extract_jsonb_path(PG_FUNCTION_ARGS)
 {
 	Jsonb	   *jb = PG_GETARG_JSONB_P(0);
 	int32	   *nentries = (int32 *) PG_GETARG_POINTER(1);
-	int			total = 2 * JB_ROOT_COUNT(jb);
+	int			total = JB_ROOT_COUNT(jb);
 	JsonbIterator *it;
 	JsonbValue	v;
 	JsonbIteratorToken r;
 	PathHashStack tail;
 	PathHashStack *stack;
-	int			i = 0;
-	Datum	   *entries;
+	GinEntries	entries;
 
 	/* If the root level is empty, we certainly have no keys */
 	if (total == 0)
@@ -348,7 +1059,7 @@ gin_extract_jsonb_path(PG_FUNCTION_ARGS)
 	}
 
 	/* Otherwise, use 2 * root count as initial estimate of result size */
-	entries = (Datum *) palloc(sizeof(Datum) * total);
+	init_entries(&entries, 2 * total);
 
 	/* We keep a stack of partial hashes corresponding to parent key levels */
 	tail.parent = NULL;
@@ -361,13 +1072,6 @@ gin_extract_jsonb_path(PG_FUNCTION_ARGS)
 	{
 		PathHashStack *parent;
 
-		/* Since we recurse into the object, we might need more space */
-		if (i >= total)
-		{
-			total *= 2;
-			entries = (Datum *) repalloc(entries, sizeof(Datum) * total);
-		}
-
 		switch (r)
 		{
 			case WJB_BEGIN_ARRAY:
@@ -398,7 +1102,7 @@ gin_extract_jsonb_path(PG_FUNCTION_ARGS)
 				/* mix the element or value's hash into the prepared hash */
 				JsonbHashScalarValue(&v, &stack->hash);
 				/* and emit an index entry */
-				entries[i++] = UInt32GetDatum(stack->hash);
+				add_entry(&entries, UInt32GetDatum(stack->hash));
 				/* reset hash for next key, value, or sub-object */
 				stack->hash = stack->parent->hash;
 				break;
@@ -419,9 +1123,9 @@ gin_extract_jsonb_path(PG_FUNCTION_ARGS)
 		}
 	}
 
-	*nentries = i;
+	*nentries = entries.count;
 
-	PG_RETURN_POINTER(entries);
+	PG_RETURN_POINTER(entries.buf);
 }
 
 Datum
@@ -432,18 +1136,35 @@ gin_extract_jsonb_query_path(PG_FUNCTION_ARGS)
 	int32	   *searchMode = (int32 *) PG_GETARG_POINTER(6);
 	Datum	   *entries;
 
-	if (strategy != JsonbContainsStrategyNumber)
-		elog(ERROR, "unrecognized strategy number: %d", strategy);
+	if (strategy == JsonbContainsStrategyNumber)
+	{
+		/* Query is a jsonb, so just apply gin_extract_jsonb_path ... */
+		entries = (Datum *)
+			DatumGetPointer(DirectFunctionCall2(gin_extract_jsonb_path,
+												PG_GETARG_DATUM(0),
+												PointerGetDatum(nentries)));
+
+		/* ... although "contains {}" requires a full index scan */
+		if (*nentries == 0)
+			*searchMode = GIN_SEARCH_MODE_ALL;
+	}
+	else if (strategy == JsonbJsonpathPredicateStrategyNumber ||
+			 strategy == JsonbJsonpathExistsStrategyNumber)
+	{
+		JsonPath   *jp = PG_GETARG_JSONPATH_P(0);
+		Pointer	  **extra_data = (Pointer **) PG_GETARG_POINTER(4);
 
-	/* Query is a jsonb, so just apply gin_extract_jsonb_path ... */
-	entries = (Datum *)
-		DatumGetPointer(DirectFunctionCall2(gin_extract_jsonb_path,
-											PG_GETARG_DATUM(0),
-											PointerGetDatum(nentries)));
+		entries = extract_jsp_query(jp, strategy, true, nentries,
+										extra_data);
 
-	/* ... although "contains {}" requires a full index scan */
-	if (*nentries == 0)
-		*searchMode = GIN_SEARCH_MODE_ALL;
+		if (!entries)
+			*searchMode = GIN_SEARCH_MODE_ALL;
+	}
+	else
+	{
+		elog(ERROR, "unrecognized strategy number: %d", strategy);
+		entries = NULL;
+	}
 
 	PG_RETURN_POINTER(entries);
 }
@@ -456,32 +1177,49 @@ gin_consistent_jsonb_path(PG_FUNCTION_ARGS)
 
 	/* Jsonb	   *query = PG_GETARG_JSONB_P(2); */
 	int32		nkeys = PG_GETARG_INT32(3);
-
-	/* Pointer	   *extra_data = (Pointer *) PG_GETARG_POINTER(4); */
+	Pointer	   *extra_data = (Pointer *) PG_GETARG_POINTER(4);
 	bool	   *recheck = (bool *) PG_GETARG_POINTER(5);
 	bool		res = true;
 	int32		i;
 
-	if (strategy != JsonbContainsStrategyNumber)
-		elog(ERROR, "unrecognized strategy number: %d", strategy);
-
-	/*
-	 * jsonb_path_ops is necessarily lossy, not only because of hash
-	 * collisions but also because it doesn't preserve complete information
-	 * about the structure of the JSON object.  Besides, there are some
-	 * special rules around the containment of raw scalars in arrays that are
-	 * not handled here.  So we must always recheck a match.  However, if not
-	 * all of the keys are present, the tuple certainly doesn't match.
-	 */
-	*recheck = true;
-	for (i = 0; i < nkeys; i++)
+	if (strategy == JsonbContainsStrategyNumber)
 	{
-		if (!check[i])
+		/*
+		 * jsonb_path_ops is necessarily lossy, not only because of hash
+		 * collisions but also because it doesn't preserve complete information
+		 * about the structure of the JSON object.  Besides, there are some
+		 * special rules around the containment of raw scalars in arrays that are
+		 * not handled here.  So we must always recheck a match.  However, if not
+		 * all of the keys are present, the tuple certainly doesn't match.
+		 */
+		*recheck = true;
+		for (i = 0; i < nkeys; i++)
 		{
-			res = false;
-			break;
+			if (!check[i])
+			{
+				res = false;
+				break;
+			}
+		}
+	}
+	else if (strategy == JsonbJsonpathPredicateStrategyNumber ||
+			 strategy == JsonbJsonpathExistsStrategyNumber)
+	{
+		*recheck = true;
+
+		if (nkeys <= 0)
+		{
+			res = true;
+		}
+		else
+		{
+			Assert(extra_data && extra_data[0]);
+			res = execute_jsp_expr((GinJsonPathNode *) extra_data[0], check,
+								   false) != GIN_FALSE;
 		}
 	}
+	else
+		elog(ERROR, "unrecognized strategy number: %d", strategy);
 
 	PG_RETURN_BOOL(res);
 }
@@ -494,27 +1232,42 @@ gin_triconsistent_jsonb_path(PG_FUNCTION_ARGS)
 
 	/* Jsonb	   *query = PG_GETARG_JSONB_P(2); */
 	int32		nkeys = PG_GETARG_INT32(3);
-
-	/* Pointer	   *extra_data = (Pointer *) PG_GETARG_POINTER(4); */
+	Pointer	   *extra_data = (Pointer *) PG_GETARG_POINTER(4);
 	GinTernaryValue res = GIN_MAYBE;
 	int32		i;
 
-	if (strategy != JsonbContainsStrategyNumber)
-		elog(ERROR, "unrecognized strategy number: %d", strategy);
-
-	/*
-	 * Note that we never return GIN_TRUE, only GIN_MAYBE or GIN_FALSE; this
-	 * corresponds to always forcing recheck in the regular consistent
-	 * function, for the reasons listed there.
-	 */
-	for (i = 0; i < nkeys; i++)
+	if (strategy == JsonbContainsStrategyNumber)
 	{
-		if (check[i] == GIN_FALSE)
+		/*
+		 * Note that we never return GIN_TRUE, only GIN_MAYBE or GIN_FALSE; this
+		 * corresponds to always forcing recheck in the regular consistent
+		 * function, for the reasons listed there.
+		 */
+		for (i = 0; i < nkeys; i++)
 		{
-			res = GIN_FALSE;
-			break;
+			if (check[i] == GIN_FALSE)
+			{
+				res = GIN_FALSE;
+				break;
+			}
+		}
+	}
+	else if (strategy == JsonbJsonpathPredicateStrategyNumber ||
+			 strategy == JsonbJsonpathExistsStrategyNumber)
+	{
+		if (nkeys <= 0)
+		{
+			res = GIN_MAYBE;
+		}
+		else
+		{
+			Assert(extra_data && extra_data[0]);
+			res = execute_jsp_expr((GinJsonPathNode *) extra_data[0], check,
+								   true);
 		}
 	}
+	else
+		elog(ERROR, "unrecognized strategy number: %d", strategy);
 
 	PG_RETURN_GIN_TERNARY_VALUE(res);
 }
diff --git a/src/include/catalog/pg_amop.dat b/src/include/catalog/pg_amop.dat
index 0ab95d8..cf63eb7 100644
--- a/src/include/catalog/pg_amop.dat
+++ b/src/include/catalog/pg_amop.dat
@@ -1468,11 +1468,23 @@
 { amopfamily => 'gin/jsonb_ops', amoplefttype => 'jsonb',
   amoprighttype => '_text', amopstrategy => '11', amopopr => '?&(jsonb,_text)',
   amopmethod => 'gin' },
+{ amopfamily => 'gin/jsonb_ops', amoplefttype => 'jsonb',
+  amoprighttype => 'jsonpath', amopstrategy => '15',
+  amopopr => '@?(jsonb,jsonpath)', amopmethod => 'gin' },
+{ amopfamily => 'gin/jsonb_ops', amoplefttype => 'jsonb',
+  amoprighttype => 'jsonpath', amopstrategy => '16',
+  amopopr => '@@(jsonb,jsonpath)', amopmethod => 'gin' },
 
 # GIN jsonb_path_ops
 { amopfamily => 'gin/jsonb_path_ops', amoplefttype => 'jsonb',
   amoprighttype => 'jsonb', amopstrategy => '7', amopopr => '@>(jsonb,jsonb)',
   amopmethod => 'gin' },
+{ amopfamily => 'gin/jsonb_path_ops', amoplefttype => 'jsonb',
+  amoprighttype => 'jsonpath', amopstrategy => '15',
+  amopopr => '@?(jsonb,jsonpath)', amopmethod => 'gin' },
+{ amopfamily => 'gin/jsonb_path_ops', amoplefttype => 'jsonb',
+  amoprighttype => 'jsonpath', amopstrategy => '16',
+  amopopr => '@@(jsonb,jsonpath)', amopmethod => 'gin' },
 
 # SP-GiST range_ops
 { amopfamily => 'spgist/range_ops', amoplefttype => 'anyrange',
diff --git a/src/include/utils/jsonb.h b/src/include/utils/jsonb.h
index a5d1df4..4dc00f4 100644
--- a/src/include/utils/jsonb.h
+++ b/src/include/utils/jsonb.h
@@ -34,6 +34,9 @@ typedef enum
 #define JsonbExistsStrategyNumber		9
 #define JsonbExistsAnyStrategyNumber	10
 #define JsonbExistsAllStrategyNumber	11
+#define JsonbJsonpathExistsStrategyNumber		15
+#define JsonbJsonpathPredicateStrategyNumber	16
+
 
 /*
  * In the standard jsonb_ops GIN opclass for jsonb, we choose to index both
diff --git a/src/include/utils/jsonpath.h b/src/include/utils/jsonpath.h
index 2170a70..6266f86 100644
--- a/src/include/utils/jsonpath.h
+++ b/src/include/utils/jsonpath.h
@@ -35,6 +35,8 @@ typedef struct
 #define PG_GETARG_JSONPATH_P_COPY(x)	DatumGetJsonPathPCopy(PG_GETARG_DATUM(x))
 #define PG_RETURN_JSONPATH_P(p)			PG_RETURN_POINTER(p)
 
+#define jspIsScalar(type) ((type) >= jpiNull && (type) <= jpiBool)
+
 /*
  * All node's type of jsonpath expression
  */
diff --git a/src/test/regress/expected/jsonb.out b/src/test/regress/expected/jsonb.out
index 8dcdaf5..5438af7 100644
--- a/src/test/regress/expected/jsonb.out
+++ b/src/test/regress/expected/jsonb.out
@@ -2731,6 +2731,114 @@ SELECT count(*) FROM testjsonb WHERE j ?& ARRAY['public','disabled'];
     42
 (1 row)
 
+SELECT count(*) FROM testjsonb WHERE j @@ '$.wait == null';
+ count 
+-------
+     1
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ '"CC" == $.wait';
+ count 
+-------
+    15
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ '$.wait == "CC" && true == $.public';
+ count 
+-------
+     2
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ '$.age == 25';
+ count 
+-------
+     2
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ '$.age == 25.0';
+ count 
+-------
+     2
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($)';
+ count 
+-------
+  1012
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.public)';
+ count 
+-------
+   194
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.bar)';
+ count 
+-------
+     0
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.public) || exists($.disabled)';
+ count 
+-------
+   337
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.public) && exists($.disabled)';
+ count 
+-------
+    42
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? (@ == null)';
+ count 
+-------
+     1
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? ("CC" == @)';
+ count 
+-------
+    15
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.wait == "CC" && true == @.public)';
+ count 
+-------
+     2
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$.age ? (@ == 25)';
+ count 
+-------
+     2
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.age == 25.0)';
+ count 
+-------
+     2
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$';
+ count 
+-------
+  1012
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$.public';
+ count 
+-------
+   194
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$.bar';
+ count 
+-------
+     0
+(1 row)
+
 CREATE INDEX jidx ON testjsonb USING gin (j);
 SET enable_seqscan = off;
 SELECT count(*) FROM testjsonb WHERE j @> '{"wait":null}';
@@ -2806,6 +2914,196 @@ SELECT count(*) FROM testjsonb WHERE j ?& ARRAY['public','disabled'];
     42
 (1 row)
 
+EXPLAIN (COSTS OFF)
+SELECT count(*) FROM testjsonb WHERE j @@ '$.wait == null';
+                           QUERY PLAN                            
+-----------------------------------------------------------------
+ Aggregate
+   ->  Bitmap Heap Scan on testjsonb
+         Recheck Cond: (j @@ '($."wait" == null)'::jsonpath)
+         ->  Bitmap Index Scan on jidx
+               Index Cond: (j @@ '($."wait" == null)'::jsonpath)
+(5 rows)
+
+SELECT count(*) FROM testjsonb WHERE j @@ '$.wait == null';
+ count 
+-------
+     1
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($ ? (@.wait == null))';
+ count 
+-------
+     1
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.wait ? (@ == null))';
+ count 
+-------
+     1
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ '"CC" == $.wait';
+ count 
+-------
+    15
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ '$.wait == "CC" && true == $.public';
+ count 
+-------
+     2
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ '$.age == 25';
+ count 
+-------
+     2
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ '$.age == 25.0';
+ count 
+-------
+     2
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ '$.array[*] == "foo"';
+ count 
+-------
+     3
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ '$.array[*] == "bar"';
+ count 
+-------
+     3
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($ ? (@.array[*] == "bar"))';
+ count 
+-------
+     3
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.array ? (@[*] == "bar"))';
+ count 
+-------
+     3
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.array[*] ? (@ == "bar"))';
+ count 
+-------
+     3
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($)';
+ count 
+-------
+  1012
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.public)';
+ count 
+-------
+   194
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.bar)';
+ count 
+-------
+     0
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.public) || exists($.disabled)';
+ count 
+-------
+   337
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.public) && exists($.disabled)';
+ count 
+-------
+    42
+(1 row)
+
+EXPLAIN (COSTS OFF)
+SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? (@ == null)';
+                            QUERY PLAN                             
+-------------------------------------------------------------------
+ Aggregate
+   ->  Bitmap Heap Scan on testjsonb
+         Recheck Cond: (j @? '$."wait"?(@ == null)'::jsonpath)
+         ->  Bitmap Index Scan on jidx
+               Index Cond: (j @? '$."wait"?(@ == null)'::jsonpath)
+(5 rows)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? (@ == null)';
+ count 
+-------
+     1
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? ("CC" == @)';
+ count 
+-------
+    15
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.wait == "CC" && true == @.public)';
+ count 
+-------
+     2
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$.age ? (@ == 25)';
+ count 
+-------
+     2
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.age == 25.0)';
+ count 
+-------
+     2
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.array[*] == "bar")';
+ count 
+-------
+     3
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$.array ? (@[*] == "bar")';
+ count 
+-------
+     3
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$.array[*] ? (@ == "bar")';
+ count 
+-------
+     3
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$';
+ count 
+-------
+  1012
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$.public';
+ count 
+-------
+   194
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$.bar';
+ count 
+-------
+     0
+(1 row)
+
 -- array exists - array elements should behave as keys (for GIN index scans too)
 CREATE INDEX jidx_array ON testjsonb USING gin((j->'array'));
 SELECT count(*) from testjsonb  WHERE j->'array' ? 'bar';
@@ -2956,6 +3254,161 @@ SELECT count(*) FROM testjsonb WHERE j @> '{}';
   1012
 (1 row)
 
+SELECT count(*) FROM testjsonb WHERE j @@ '$.wait == null';
+ count 
+-------
+     1
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($ ? (@.wait == null))';
+ count 
+-------
+     1
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.wait ? (@ == null))';
+ count 
+-------
+     1
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ '"CC" == $.wait';
+ count 
+-------
+    15
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ '$.wait == "CC" && true == $.public';
+ count 
+-------
+     2
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ '$.age == 25';
+ count 
+-------
+     2
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ '$.age == 25.0';
+ count 
+-------
+     2
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ '$.array[*] == "foo"';
+ count 
+-------
+     3
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ '$.array[*] == "bar"';
+ count 
+-------
+     3
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($ ? (@.array[*] == "bar"))';
+ count 
+-------
+     3
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.array ? (@[*] == "bar"))';
+ count 
+-------
+     3
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.array[*] ? (@ == "bar"))';
+ count 
+-------
+     3
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($)';
+ count 
+-------
+  1012
+(1 row)
+
+EXPLAIN (COSTS OFF)
+SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? (@ == null)';
+                            QUERY PLAN                             
+-------------------------------------------------------------------
+ Aggregate
+   ->  Bitmap Heap Scan on testjsonb
+         Recheck Cond: (j @? '$."wait"?(@ == null)'::jsonpath)
+         ->  Bitmap Index Scan on jidx
+               Index Cond: (j @? '$."wait"?(@ == null)'::jsonpath)
+(5 rows)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? (@ == null)';
+ count 
+-------
+     1
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? ("CC" == @)';
+ count 
+-------
+    15
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.wait == "CC" && true == @.public)';
+ count 
+-------
+     2
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$.age ? (@ == 25)';
+ count 
+-------
+     2
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.age == 25.0)';
+ count 
+-------
+     2
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.array[*] == "bar")';
+ count 
+-------
+     3
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$.array ? (@[*] == "bar")';
+ count 
+-------
+     3
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$.array[*] ? (@ == "bar")';
+ count 
+-------
+     3
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$';
+ count 
+-------
+  1012
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$.public';
+ count 
+-------
+   194
+(1 row)
+
+SELECT count(*) FROM testjsonb WHERE j @? '$.bar';
+ count 
+-------
+     0
+(1 row)
+
 RESET enable_seqscan;
 DROP INDEX jidx;
 -- nested tests
diff --git a/src/test/regress/expected/opr_sanity.out b/src/test/regress/expected/opr_sanity.out
index ce25ee0..f6f450e 100644
--- a/src/test/regress/expected/opr_sanity.out
+++ b/src/test/regress/expected/opr_sanity.out
@@ -1906,6 +1906,8 @@ ORDER BY 1, 2, 3;
        2742 |            9 | ?
        2742 |           10 | ?|
        2742 |           11 | ?&
+       2742 |           15 | @?
+       2742 |           16 | @@
        3580 |            1 | <
        3580 |            1 | <<
        3580 |            2 | &<
@@ -1971,7 +1973,7 @@ ORDER BY 1, 2, 3;
        4000 |           26 | >>
        4000 |           27 | >>=
        4000 |           28 | ^@
-(123 rows)
+(125 rows)
 
 -- Check that all opclass search operators have selectivity estimators.
 -- This is not absolutely required, but it seems a reasonable thing
diff --git a/src/test/regress/sql/jsonb.sql b/src/test/regress/sql/jsonb.sql
index 6cbdfe4..ed273dc 100644
--- a/src/test/regress/sql/jsonb.sql
+++ b/src/test/regress/sql/jsonb.sql
@@ -740,6 +740,24 @@ SELECT count(*) FROM testjsonb WHERE j ? 'public';
 SELECT count(*) FROM testjsonb WHERE j ? 'bar';
 SELECT count(*) FROM testjsonb WHERE j ?| ARRAY['public','disabled'];
 SELECT count(*) FROM testjsonb WHERE j ?& ARRAY['public','disabled'];
+SELECT count(*) FROM testjsonb WHERE j @@ '$.wait == null';
+SELECT count(*) FROM testjsonb WHERE j @@ '"CC" == $.wait';
+SELECT count(*) FROM testjsonb WHERE j @@ '$.wait == "CC" && true == $.public';
+SELECT count(*) FROM testjsonb WHERE j @@ '$.age == 25';
+SELECT count(*) FROM testjsonb WHERE j @@ '$.age == 25.0';
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($)';
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.public)';
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.bar)';
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.public) || exists($.disabled)';
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.public) && exists($.disabled)';
+SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? (@ == null)';
+SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? ("CC" == @)';
+SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.wait == "CC" && true == @.public)';
+SELECT count(*) FROM testjsonb WHERE j @? '$.age ? (@ == 25)';
+SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.age == 25.0)';
+SELECT count(*) FROM testjsonb WHERE j @? '$';
+SELECT count(*) FROM testjsonb WHERE j @? '$.public';
+SELECT count(*) FROM testjsonb WHERE j @? '$.bar';
 
 CREATE INDEX jidx ON testjsonb USING gin (j);
 SET enable_seqscan = off;
@@ -758,6 +776,39 @@ SELECT count(*) FROM testjsonb WHERE j ? 'bar';
 SELECT count(*) FROM testjsonb WHERE j ?| ARRAY['public','disabled'];
 SELECT count(*) FROM testjsonb WHERE j ?& ARRAY['public','disabled'];
 
+EXPLAIN (COSTS OFF)
+SELECT count(*) FROM testjsonb WHERE j @@ '$.wait == null';
+SELECT count(*) FROM testjsonb WHERE j @@ '$.wait == null';
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($ ? (@.wait == null))';
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.wait ? (@ == null))';
+SELECT count(*) FROM testjsonb WHERE j @@ '"CC" == $.wait';
+SELECT count(*) FROM testjsonb WHERE j @@ '$.wait == "CC" && true == $.public';
+SELECT count(*) FROM testjsonb WHERE j @@ '$.age == 25';
+SELECT count(*) FROM testjsonb WHERE j @@ '$.age == 25.0';
+SELECT count(*) FROM testjsonb WHERE j @@ '$.array[*] == "foo"';
+SELECT count(*) FROM testjsonb WHERE j @@ '$.array[*] == "bar"';
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($ ? (@.array[*] == "bar"))';
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.array ? (@[*] == "bar"))';
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.array[*] ? (@ == "bar"))';
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($)';
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.public)';
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.bar)';
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.public) || exists($.disabled)';
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.public) && exists($.disabled)';
+EXPLAIN (COSTS OFF)
+SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? (@ == null)';
+SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? (@ == null)';
+SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? ("CC" == @)';
+SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.wait == "CC" && true == @.public)';
+SELECT count(*) FROM testjsonb WHERE j @? '$.age ? (@ == 25)';
+SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.age == 25.0)';
+SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.array[*] == "bar")';
+SELECT count(*) FROM testjsonb WHERE j @? '$.array ? (@[*] == "bar")';
+SELECT count(*) FROM testjsonb WHERE j @? '$.array[*] ? (@ == "bar")';
+SELECT count(*) FROM testjsonb WHERE j @? '$';
+SELECT count(*) FROM testjsonb WHERE j @? '$.public';
+SELECT count(*) FROM testjsonb WHERE j @? '$.bar';
+
 -- array exists - array elements should behave as keys (for GIN index scans too)
 CREATE INDEX jidx_array ON testjsonb USING gin((j->'array'));
 SELECT count(*) from testjsonb  WHERE j->'array' ? 'bar';
@@ -807,6 +858,34 @@ SELECT count(*) FROM testjsonb WHERE j @> '{"age":25.0}';
 -- exercise GIN_SEARCH_MODE_ALL
 SELECT count(*) FROM testjsonb WHERE j @> '{}';
 
+SELECT count(*) FROM testjsonb WHERE j @@ '$.wait == null';
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($ ? (@.wait == null))';
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.wait ? (@ == null))';
+SELECT count(*) FROM testjsonb WHERE j @@ '"CC" == $.wait';
+SELECT count(*) FROM testjsonb WHERE j @@ '$.wait == "CC" && true == $.public';
+SELECT count(*) FROM testjsonb WHERE j @@ '$.age == 25';
+SELECT count(*) FROM testjsonb WHERE j @@ '$.age == 25.0';
+SELECT count(*) FROM testjsonb WHERE j @@ '$.array[*] == "foo"';
+SELECT count(*) FROM testjsonb WHERE j @@ '$.array[*] == "bar"';
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($ ? (@.array[*] == "bar"))';
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.array ? (@[*] == "bar"))';
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.array[*] ? (@ == "bar"))';
+SELECT count(*) FROM testjsonb WHERE j @@ 'exists($)';
+
+EXPLAIN (COSTS OFF)
+SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? (@ == null)';
+SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? (@ == null)';
+SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? ("CC" == @)';
+SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.wait == "CC" && true == @.public)';
+SELECT count(*) FROM testjsonb WHERE j @? '$.age ? (@ == 25)';
+SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.age == 25.0)';
+SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.array[*] == "bar")';
+SELECT count(*) FROM testjsonb WHERE j @? '$.array ? (@[*] == "bar")';
+SELECT count(*) FROM testjsonb WHERE j @? '$.array[*] ? (@ == "bar")';
+SELECT count(*) FROM testjsonb WHERE j @? '$';
+SELECT count(*) FROM testjsonb WHERE j @? '$.public';
+SELECT count(*) FROM testjsonb WHERE j @? '$.bar';
+
 RESET enable_seqscan;
 DROP INDEX jidx;
 
-- 
2.7.4

view thread (198+ messages)  latest in thread

Message-ID: <a3be6a7a-77d3-0e88-4f9d-4f725d11d7cd@postgrespro.ru>
Permalink:  ../a3be6a7a-77d3-0e88-4f9d-4f725d11d7cd@postgrespro.ru/
Also on:    postgresql.org/message-id/a3be6a7a-77d3-0e88-4f9d-4f725d11d7cd@postgrespro.ru

 ·  · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-hackers@postgresql.org
  Cc: n.gluhov@postgrespro.ru, a.korotkov@postgrespro.ru, tomas.vondra@2ndquadrant.com, andres@anarazel.de, obartunov@postgrespro.ru, michael@paquier.xyz, s.kelvich@postgrespro.ru, thomas.munro@enterprisedb.com, david@pgmasters.net, tgl@sss.pgh.pa.us, andrew.dunstan@2ndquadrant.com, robertmhaas@gmail.com, pavel.stehule@gmail.com
  Subject: Re: jsonpath
  In-Reply-To: <a3be6a7a-77d3-0e88-4f9d-4f725d11d7cd@postgrespro.ru>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox