You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@age.apache.org by jg...@apache.org on 2022/12/13 18:17:44 UTC

[age] 01/01: Add the ability to pass parameters to the cypher function

This is an automated email from the ASF dual-hosted git repository.

jgemignani pushed a commit to branch PG12
in repository https://gitbox.apache.org/repos/asf/age.git

commit b9b8b5add0c0b0db3eda6487d093a1e0e0f3b291
Author: John Gemignani <jr...@gmail.com>
AuthorDate: Tue Dec 13 10:16:17 2022 -0800

    Add the ability to pass parameters to the cypher function
    
    Added the ability to pass parameters to the cypher() function via
    a function called age_prepare_cypher().
    
    This extra function is necessary because the cypher() function itself
    isn't actually executed - it is instead transformed and replaced. This
    means that it needs to have its input parameters resolved prior to
    that transform. However, parameters aren't resolved until the
    execution phase. So, another command to resolve them needs to run
    prior to the cypher() function call.
    
    This mainly impacts the drivers, which will need to be updated.
    
    Additionally, modified the golang driver as an example of this new
    usage.
    
    Added regression tests.
---
 Makefile                                 |   2 +
 age--1.1.0.sql                           |  12 ++-
 drivers/golang/age/age.go                |  52 +++------
 drivers/golang/go.mod                    |   2 +-
 drivers/golang/go.sum                    |  14 +++
 drivers/golang/parser/Age.g4             |   3 +-
 regress/expected/analyze.out             | 135 ++++++++++++++++++++++++
 regress/sql/analyze.sql                  |  60 +++++++++++
 src/backend/parser/cypher_analyze.c      | 176 +++++++++++++++++++++++--------
 src/backend/utils/adt/age_session_info.c | 170 +++++++++++++++++++++++++++++
 src/include/utils/age_session_info.h     |  29 +++++
 11 files changed, 570 insertions(+), 85 deletions(-)

diff --git a/Makefile b/Makefile
index f8b1369..926c877 100644
--- a/Makefile
+++ b/Makefile
@@ -57,6 +57,7 @@ OBJS = src/backend/age.o \
        src/backend/utils/adt/agtype_parser.o \
        src/backend/utils/adt/agtype_util.o \
        src/backend/utils/adt/age_global_graph.o \
+       src/backend/utils/adt/age_session_info.o \
        src/backend/utils/adt/age_vle.o \
        src/backend/utils/adt/cypher_funcs.o \
        src/backend/utils/adt/ag_float8_supp.o \
@@ -91,6 +92,7 @@ REGRESS = scan \
           cypher_merge \
           age_load \
           index \
+          analyze \
           drop
 
 srcdir=`pwd`
diff --git a/age--1.1.0.sql b/age--1.1.0.sql
index f6b555b..367f5d9 100644
--- a/age--1.1.0.sql
+++ b/age--1.1.0.sql
@@ -3389,8 +3389,9 @@ AS 'MODULE_PATHNAME';
 --
 -- query functions
 --
-CREATE FUNCTION ag_catalog.cypher(graph_name name, query_string cstring,
-                       params agtype = NULL)
+CREATE FUNCTION ag_catalog.cypher(graph_name name = NULL,
+                                  query_string cstring = NULL,
+                                  params agtype = NULL)
 RETURNS SETOF record
 LANGUAGE c
 AS 'MODULE_PATHNAME';
@@ -4160,6 +4161,13 @@ STABLE
 PARALLEL SAFE
 AS 'MODULE_PATHNAME';
 
+CREATE FUNCTION ag_catalog.age_prepare_cypher(cstring, cstring)
+RETURNS boolean
+LANGUAGE c
+STABLE
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
 --
 -- End
 --
diff --git a/drivers/golang/age/age.go b/drivers/golang/age/age.go
index 38a629f..3f83920 100644
--- a/drivers/golang/age/age.go
+++ b/drivers/golang/age/age.go
@@ -76,29 +76,34 @@ func execCypher(cursorProvider CursorProvider, tx *sql.Tx, graphName string, col
 
 	cypherStmt := fmt.Sprintf(cypher, args...)
 
-	buf.WriteString("SELECT * from cypher('")
-	buf.WriteString(graphName)
-	buf.WriteString("', $$ ")
-	buf.WriteString(cypherStmt)
-	buf.WriteString(" $$)")
-	buf.WriteString(" as (")
-	buf.WriteString("v0 agtype")
+        buf.WriteString("SELECT * from cypher(NULL,NULL) as (v0 agtype")
+
 	for i := 1; i < columnCount; i++ {
 		buf.WriteString(fmt.Sprintf(", v%d agtype", i))
 	}
-	buf.WriteString(")")
+	buf.WriteString(");")
 
 	stmt := buf.String()
 
+        // Pass in the graph name and cypher statement via parameters to prepare
+        // the cypher function call for session info.
+
+        prepare_stmt := "SELECT * FROM age_prepare_cypher($1, $2);"
+        _, perr := tx.Exec(prepare_stmt, graphName, cypherStmt)
+        if perr != nil {
+                        fmt.Println(prepare_stmt + " " + graphName + " " + cypher)
+                        return nil, perr
+        }
+
 	if columnCount == 0 {
-		_, err := tx.Exec(stmt)
+                _, err := tx.Exec(stmt)
 		if err != nil {
 			fmt.Println(stmt)
 			return nil, err
 		}
 		return nil, nil
 	} else {
-		rows, err := tx.Query(stmt)
+                rows, err := tx.Query(stmt)
 		if err != nil {
 			fmt.Println(stmt)
 			return nil, err
@@ -133,33 +138,6 @@ func ExecCypherMap(tx *sql.Tx, graphName string, columnCount int, cypher string,
 	return cypherMapCursor, err
 }
 
-// // ExecCypher execute without return
-// // CREATE , DROP .... */
-// func ExecCypher2(tx *sql.Tx, graphName string, cypher string, args ...interface{}) error {
-// 	cypherStmt := fmt.Sprintf(cypher, args...)
-// 	stmt := fmt.Sprintf("SELECT * from cypher('%s', $$ %s $$) as (v agtype);",
-// 		graphName, cypherStmt)
-
-// 	_, err := tx.Exec(stmt)
-// 	return err
-// }
-
-// // QueryCypher execute with return
-// // MATCH .... RETURN ....
-// // CREATE , DROP .... RETURN ...
-// func QueryCypher(tx *sql.Tx, graphName string, cypher string, args ...interface{}) (*CypherCursor, error) {
-// 	cypherStmt := fmt.Sprintf(cypher, args...)
-// 	stmt := fmt.Sprintf("SELECT * from cypher('%s', $$ %s $$) as (v agtype);",
-// 		graphName, cypherStmt)
-
-// 	rows, err := tx.Query(stmt)
-// 	if err != nil {
-// 		return nil, err
-// 	} else {
-// 		return NewCypherCursor(1, rows), nil
-// 	}
-// }
-
 type Age struct {
 	db        *sql.DB
 	graphName string
diff --git a/drivers/golang/go.mod b/drivers/golang/go.mod
index bd27c5c..81525d6 100644
--- a/drivers/golang/go.mod
+++ b/drivers/golang/go.mod
@@ -22,7 +22,7 @@ module github.com/apache/age/drivers/golang
 go 1.16
 
 require (
-	github.com/antlr/antlr4/runtime/Go/antlr v0.0.0-20221020221120-327014a2b522
+	github.com/antlr/antlr4/runtime/Go/antlr v0.0.0-20210521184019-c5ad59b459ec
 	github.com/lib/pq v1.10.2
 	github.com/stretchr/testify v1.7.0
 )
diff --git a/drivers/golang/go.sum b/drivers/golang/go.sum
new file mode 100644
index 0000000..13a472e
--- /dev/null
+++ b/drivers/golang/go.sum
@@ -0,0 +1,14 @@
+github.com/antlr/antlr4/runtime/Go/antlr v0.0.0-20210521184019-c5ad59b459ec h1:EEyRvzmpEUZ+I8WmD5cw/vY8EqhambkOqy5iFr0908A=
+github.com/antlr/antlr4/runtime/Go/antlr v0.0.0-20210521184019-c5ad59b459ec/go.mod h1:F7bn7fEU90QkQ3tnmaTx3LTKLEDqnwWODIYppRQ5hnY=
+github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/lib/pq v1.10.2 h1:AqzbZs4ZoCBp+GtejcpCpcxM3zlSMx29dXbUSeVtJb8=
+github.com/lib/pq v1.10.2/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/drivers/golang/parser/Age.g4 b/drivers/golang/parser/Age.g4
index 5ba157a..c5516a9 100644
--- a/drivers/golang/parser/Age.g4
+++ b/drivers/golang/parser/Age.g4
@@ -79,7 +79,7 @@ BOOL
    ;
 
 NULL
-   : 'null' 
+   : 'null'
    ;
 
 
@@ -125,4 +125,3 @@ fragment EXP
 WS
    : [ \t\n\r] + -> skip
    ;
-   
\ No newline at end of file
diff --git a/regress/expected/analyze.out b/regress/expected/analyze.out
new file mode 100644
index 0000000..5b24838
--- /dev/null
+++ b/regress/expected/analyze.out
@@ -0,0 +1,135 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+LOAD 'age';
+SET search_path TO ag_catalog;
+--
+-- Start of tests
+--
+SELECT * FROM create_graph('analyze');
+NOTICE:  graph "analyze" has been created
+ create_graph 
+--------------
+ 
+(1 row)
+
+SELECT * FROM cypher('analyze', $$ CREATE (u) RETURN u $$) AS (result agtype);
+                             result                             
+----------------------------------------------------------------
+ {"id": 281474976710657, "label": "", "properties": {}}::vertex
+(1 row)
+
+-- should error due to invalid input to cypher function
+SELECT * FROM cypher(NULL, NULL) AS (result agtype);
+ERROR:  a name constant is expected
+LINE 1: SELECT * FROM cypher(NULL, NULL) AS (result agtype);
+                             ^
+SELECT * FROM cypher('analyze', NULL) AS (result agtype);
+ERROR:  a dollar-quoted string constant is expected
+LINE 1: SELECT * FROM cypher('analyze', NULL) AS (result agtype);
+                                        ^
+SELECT * FROM cypher(NULL, '') AS (result agtype);
+ERROR:  a name constant is expected
+LINE 1: SELECT * FROM cypher(NULL, '') AS (result agtype);
+                             ^
+SELECT * FROM cypher('', '') AS (result agtype);
+ERROR:  a dollar-quoted string constant is expected
+LINE 1: SELECT * FROM cypher('', '') AS (result agtype);
+                                 ^
+SELECT * FROM cypher('analyze', '') AS (result agtype);
+ERROR:  a dollar-quoted string constant is expected
+LINE 1: SELECT * FROM cypher('analyze', '') AS (result agtype);
+                                        ^
+-- should error due to bad cypher statement
+SELECT * FROM cypher('analyze', $$ $$) AS (result agtype);
+ERROR:  syntax error at end of input
+LINE 1: SELECT * FROM cypher('analyze', $$ $$) AS (result agtype);
+                                           ^
+-- should return false due to invalid input to age_prepare_function
+SELECT * FROM age_prepare_cypher(NULL, NULL);
+ age_prepare_cypher 
+--------------------
+ f
+(1 row)
+
+SELECT * FROM age_prepare_cypher('analyze', NULL);
+ age_prepare_cypher 
+--------------------
+ f
+(1 row)
+
+SELECT * FROM age_prepare_cypher(NULL, '');
+ age_prepare_cypher 
+--------------------
+ f
+(1 row)
+
+-- should return true but cypher should fail
+SELECT * FROM age_prepare_cypher('analyze', '');
+ age_prepare_cypher 
+--------------------
+ t
+(1 row)
+
+SELECT * FROM cypher(NULL, NULL) AS (result agtype);
+ERROR:  syntax error at end of input
+LINE 1: SELECT * FROM cypher(NULL, NULL) AS (result agtype);
+        ^
+-- should return true and execute cypher command
+SELECT * FROM age_prepare_cypher('analyze', 'MATCH (u) RETURN (u)');
+ age_prepare_cypher 
+--------------------
+ t
+(1 row)
+
+SELECT * FROM cypher(NULL, NULL) AS (result agtype);
+                             result                             
+----------------------------------------------------------------
+ {"id": 281474976710657, "label": "", "properties": {}}::vertex
+(1 row)
+
+-- should error due to invalid input to cypher function
+SELECT * FROM cypher(NULL, NULL) AS (result agtype);
+ERROR:  a name constant is expected
+LINE 1: SELECT * FROM cypher(NULL, NULL) AS (result agtype);
+                             ^
+-- should return true but cypher should fail
+SELECT * FROM age_prepare_cypher('analyze', '$$ $$');
+ age_prepare_cypher 
+--------------------
+ t
+(1 row)
+
+SELECT * FROM cypher(NULL, NULL) AS (result agtype);
+ERROR:  unexpected character at or near "$"
+LINE 1: SELECT * FROM cypher(NULL, NULL) AS (result agtype);
+        ^
+-- drop graphs
+SELECT * FROM drop_graph('analyze', true);
+NOTICE:  drop cascades to 2 other objects
+DETAIL:  drop cascades to table "analyze"._ag_label_vertex
+drop cascades to table "analyze"._ag_label_edge
+NOTICE:  graph "analyze" has been dropped
+ drop_graph 
+------------
+ 
+(1 row)
+
+--
+-- End of tests
+--
diff --git a/regress/sql/analyze.sql b/regress/sql/analyze.sql
new file mode 100644
index 0000000..881ef3f
--- /dev/null
+++ b/regress/sql/analyze.sql
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+LOAD 'age';
+SET search_path TO ag_catalog;
+
+--
+-- Start of tests
+--
+
+SELECT * FROM create_graph('analyze');
+SELECT * FROM cypher('analyze', $$ CREATE (u) RETURN u $$) AS (result agtype);
+
+-- should error due to invalid input to cypher function
+SELECT * FROM cypher(NULL, NULL) AS (result agtype);
+SELECT * FROM cypher('analyze', NULL) AS (result agtype);
+SELECT * FROM cypher(NULL, '') AS (result agtype);
+SELECT * FROM cypher('', '') AS (result agtype);
+SELECT * FROM cypher('analyze', '') AS (result agtype);
+-- should error due to bad cypher statement
+SELECT * FROM cypher('analyze', $$ $$) AS (result agtype);
+
+-- should return false due to invalid input to age_prepare_function
+SELECT * FROM age_prepare_cypher(NULL, NULL);
+SELECT * FROM age_prepare_cypher('analyze', NULL);
+SELECT * FROM age_prepare_cypher(NULL, '');
+-- should return true but cypher should fail
+SELECT * FROM age_prepare_cypher('analyze', '');
+SELECT * FROM cypher(NULL, NULL) AS (result agtype);
+-- should return true and execute cypher command
+SELECT * FROM age_prepare_cypher('analyze', 'MATCH (u) RETURN (u)');
+SELECT * FROM cypher(NULL, NULL) AS (result agtype);
+-- should error due to invalid input to cypher function
+SELECT * FROM cypher(NULL, NULL) AS (result agtype);
+-- should return true but cypher should fail
+SELECT * FROM age_prepare_cypher('analyze', '$$ $$');
+SELECT * FROM cypher(NULL, NULL) AS (result agtype);
+
+-- drop graphs
+SELECT * FROM drop_graph('analyze', true);
+
+--
+-- End of tests
+--
diff --git a/src/backend/parser/cypher_analyze.c b/src/backend/parser/cypher_analyze.c
index 9ffb863..ba65420 100644
--- a/src/backend/parser/cypher_analyze.c
+++ b/src/backend/parser/cypher_analyze.c
@@ -41,6 +41,7 @@
 #include "parser/cypher_parse_node.h"
 #include "parser/cypher_parser.h"
 #include "utils/ag_func.h"
+#include "utils/age_session_info.h"
 #include "utils/agtype.h"
 
 static Node *extra_node = NULL;
@@ -268,15 +269,18 @@ static void convert_cypher_to_subquery(RangeTblEntry *rte, ParseState *pstate)
 {
     RangeTblFunction *rtfunc = linitial(rte->functions);
     FuncExpr *funcexpr = (FuncExpr *)rtfunc->funcexpr;
-    Node *arg;
-    Name graph_name;
+    Node *arg1 = NULL;
+    Node *arg2 = NULL;
+    Node *arg3 = NULL;
+    Name graph_name = NULL;
+    char *graph_name_str = NULL;
     uint32 graph_oid;
-    const char *query_str;
-    int query_loc;
-    Param *params;
-    errpos_ecb_state ecb_state;
-    List *stmt;
-    Query *query;
+    const char *query_str = NULL;
+    int query_loc = -1;
+    Param *params = NULL;
+    errpos_ecb_state ecb_state = {{0}};
+    List *stmt = NULL;
+    Query *query = NULL;
 
     /*
      * We cannot apply this feature directly to SELECT subquery because the
@@ -292,28 +296,14 @@ static void convert_cypher_to_subquery(RangeTblEntry *rte, ParseState *pstate)
                  parser_errposition(pstate, exprLocation((Node *)funcexpr))));
     }
 
-    arg = linitial(funcexpr->args);
-    Assert(exprType(arg) == NAMEOID);
+    /* get our first 2 arguments */
+    arg1 = linitial(funcexpr->args);
+    arg2 = lsecond(funcexpr->args);
 
-    graph_name = expr_get_const_name(arg);
-    if (!graph_name)
-    {
-        ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR),
-                        errmsg("a name constant is expected"),
-                        parser_errposition(pstate, exprLocation(arg))));
-    }
+    Assert(exprType(arg1) == NAMEOID);
+    Assert(exprType(arg2) == CSTRINGOID);
 
-    graph_oid = get_graph_oid(NameStr(*graph_name));
-    if (!OidIsValid(graph_oid))
-    {
-        ereport(ERROR,
-                (errcode(ERRCODE_UNDEFINED_SCHEMA),
-                 errmsg("graph \"%s\" does not exist", NameStr(*graph_name)),
-                 parser_errposition(pstate, exprLocation(arg))));
-    }
-
-    arg = lsecond(funcexpr->args);
-    Assert(exprType(arg) == CSTRINGOID);
+    graph_name = expr_get_const_name(arg1);
 
     /*
      * Since cypher() function is nothing but an interface to get a Cypher
@@ -327,32 +317,132 @@ static void convert_cypher_to_subquery(RangeTblEntry *rte, ParseState *pstate)
      *   may differ from what they are shown. This will confuse users.
      * * In the case above, the error position may not be accurate.
      */
-    query_str = expr_get_const_cstring(arg, pstate->p_sourcetext);
-    if (!query_str)
+
+    query_str = expr_get_const_cstring(arg2, pstate->p_sourcetext);
+
+    /*
+     * Validate appropriate cypher function usage -
+     *
+     * Session info OVERRIDES ANY INPUT PASSED and if any is passed, it will
+     * cause the cypher function to error out.
+     *
+     * If this is using session info, both of the first 2 input parameters need
+     * to be NULL, in addition to the session info being set up. Furthermore,
+     * the input parameters passed in by session info need to both be non-NULL.
+     *
+     * If this is not using session info, both input parameters need to be
+     * non-NULL.
+     *
+     */
+    if (is_session_info_prepared())
     {
-        ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR),
-                        errmsg("a dollar-quoted string constant is expected"),
-                        parser_errposition(pstate, exprLocation(arg))));
+        /* check to see if either input parameter is non-NULL*/
+        if (graph_name != NULL || query_str != NULL)
+        {
+            Node *arg = (graph_name == NULL) ? arg1 : arg2;
+
+            /*
+             * Make sure to clean up session info because the ereport will
+             * cause the function to exit.
+             */
+            reset_session_info();
+
+            ereport(ERROR,
+                    (errcode(ERRCODE_SYNTAX_ERROR),
+                     errmsg("session info requires cypher(NULL, NULL) to be passed"),
+                     parser_errposition(pstate, exprLocation(arg))));
+        }
+        /* get our input parameters from session info */
+        else
+        {
+            graph_name_str = get_session_info_graph_name();
+            query_str = get_session_info_cypher_statement();
+
+            /* check to see if either are NULL */
+            if (graph_name_str == NULL || query_str == NULL)
+            {
+                /*
+                 * Make sure to clean up session info because the ereport will
+                 * cause the function to exit.
+                 */
+                reset_session_info();
+
+                ereport(ERROR,
+                    (errcode(ERRCODE_SYNTAX_ERROR),
+                     errmsg("both session info parameters need to be non-NULL"),
+                     parser_errposition(pstate, -1)));
+            }
+        }
+    }
+    /* otherwise, we get the parameters from the passed function input */
+    else
+    {
+        /* get the graph name string from the passed parameters */
+        if (!graph_name)
+        {
+            ereport(ERROR,
+                    (errcode(ERRCODE_SYNTAX_ERROR),
+                     errmsg("a name constant is expected"),
+                     parser_errposition(pstate, exprLocation(arg1))));
+        }
+        else
+        {
+            graph_name_str = NameStr(*graph_name);
+        }
+        /* get the query string from the passed parameters */
+        if (!query_str)
+        {
+            ereport(ERROR,
+                    (errcode(ERRCODE_SYNTAX_ERROR),
+                     errmsg("a dollar-quoted string constant is expected"),
+                     parser_errposition(pstate, exprLocation(arg2))));
+        }
     }
-    query_loc = get_query_location(((Const *)arg)->location,
-                                   pstate->p_sourcetext);
 
     /*
-     * Check to see if the cypher function had any parameters passed to it,
+     * The session info is only valid for one cypher call. Now that we are done
+     * with it, if it was used, we need to reset it to free the memory used.
+     * Additionally, the query location is dependent on how we got the query
+     * string, so set the location accordingly.
+     */
+    if (is_session_info_prepared())
+    {
+        reset_session_info();
+        query_loc = 0;
+    }
+    else
+    {
+        /* this call will crash if we use session info */
+        query_loc = get_query_location(((Const *)arg2)->location,
+                                       pstate->p_sourcetext);
+    }
+
+    /* validate the graph exists */
+    graph_oid = get_graph_oid(graph_name_str);
+    if (!OidIsValid(graph_oid))
+    {
+        ereport(ERROR,
+                (errcode(ERRCODE_UNDEFINED_SCHEMA),
+                 errmsg("graph \"%s\" does not exist", graph_name_str),
+                 parser_errposition(pstate, exprLocation(arg1))));
+    }
+
+    /*
+     * Check to see if the cypher function had a third parameters passed to it,
      * if so make sure Postgres parsed the second argument to a Param node.
      */
     if (list_length(funcexpr->args) == 3)
     {
-        arg = lthird(funcexpr->args);
-        if (!IsA(arg, Param))
+        arg3 = lthird(funcexpr->args);
+        if (!IsA(arg3, Param))
         {
             ereport(ERROR,
                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                      errmsg("third argument of cypher function must be a parameter"),
-                     parser_errposition(pstate, exprLocation(arg))));
+                     parser_errposition(pstate, exprLocation(arg3))));
         }
 
-        params = (Param *)arg;
+        params = (Param *)arg3;
     }
     else
     {
@@ -416,13 +506,13 @@ static void convert_cypher_to_subquery(RangeTblEntry *rte, ParseState *pstate)
         }
 
         query = analyze_cypher(stmt, pstate, query_str, query_loc,
-                               NameStr(*graph_name), graph_oid, params);
+                               graph_name_str, graph_oid, params);
     }
     else
     {
         query = analyze_cypher_and_coerce(stmt, rtfunc, pstate, query_str,
-                                          query_loc, NameStr(*graph_name),
-                                          graph_oid, params);
+                                          query_loc, graph_name_str, graph_oid,
+                                          params);
     }
 
     pstate->p_lateral_active = false;
diff --git a/src/backend/utils/adt/age_session_info.c b/src/backend/utils/adt/age_session_info.c
new file mode 100644
index 0000000..193aaa1
--- /dev/null
+++ b/src/backend/utils/adt/age_session_info.c
@@ -0,0 +1,170 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "postgres.h"
+
+#include "funcapi.h"
+
+#include <unistd.h>
+#include "utils/age_session_info.h"
+
+/*
+ * static/global session info variables for use with the driver interface.
+ */
+static int session_info_pid = -1;
+static char *session_info_graph_name = NULL;
+static char *session_info_cypher_statement = NULL;
+static bool session_info_prepared = false;
+
+static void set_session_info(char *graph_name, char *cypher_statement);
+
+/* function to set the session info. it will clean it, if necessary. */
+static void set_session_info(char *graph_name, char *cypher_statement)
+{
+    MemoryContext oldctx = NULL;
+
+    if (is_session_info_prepared())
+    {
+        reset_session_info();
+    }
+
+    /* we need to use a higher memory context for the data pointed to. */
+    oldctx = MemoryContextSwitchTo(TopMemoryContext);
+
+    if (graph_name != NULL)
+    {
+        session_info_graph_name = pstrdup(graph_name);
+    }
+    else
+    {
+        session_info_graph_name = NULL;
+    }
+
+    if (cypher_statement != NULL)
+    {
+        session_info_cypher_statement = pstrdup(cypher_statement);
+    }
+    else
+    {
+        session_info_cypher_statement = NULL;
+    }
+
+    /* switch back to the original context */
+    MemoryContextSwitchTo(oldctx);
+
+    session_info_pid = getpid();
+    session_info_prepared = true;
+}
+
+/*
+ * Helper function to return the value of session_info_cypher_statement or NULL
+ * if the value isn't set. The value returned is a copy, so please free it when
+ * done.
+ */
+char *get_session_info_graph_name(void)
+{
+    if (is_session_info_prepared() &&
+        session_info_graph_name != NULL)
+    {
+        return pstrdup(session_info_graph_name);
+    }
+
+    return NULL;
+}
+
+/*
+ * Helper function to return the value of session_info_cypher_statement or NULL
+ * if the value isn't set. The value returned is a copy, so please free it when
+ * done.
+ */
+char *get_session_info_cypher_statement(void)
+{
+    if (is_session_info_prepared() &&
+        session_info_cypher_statement != NULL)
+    {
+        return pstrdup(session_info_cypher_statement);
+    }
+
+    return NULL;
+}
+
+/* function to return the state of the session info data */
+bool is_session_info_prepared(void)
+{
+    /* is the session infor prepared AND is the pid the same pid */
+    if (session_info_prepared == true &&
+        session_info_pid == getpid())
+    {
+        return true;
+    }
+
+    return false;
+}
+
+/* function to clean and reset the session info back to default values */
+void reset_session_info(void)
+{
+    /* if the session info is prepared, free the strings */
+    if (session_info_prepared == true)
+    {
+        if (session_info_graph_name != NULL)
+        {
+            pfree(session_info_graph_name);
+        }
+
+        if (session_info_cypher_statement != NULL)
+        {
+            pfree(session_info_cypher_statement);
+        }
+    }
+
+    /* reset the session info back to default unused values */
+    session_info_graph_name = NULL;
+    session_info_cypher_statement = NULL;
+    session_info_prepared = false;
+    session_info_pid = -1;
+}
+
+/* AGE SQL function to prepare session info */
+PG_FUNCTION_INFO_V1(age_prepare_cypher);
+
+Datum age_prepare_cypher(PG_FUNCTION_ARGS)
+{
+    char *graph_name_str = NULL;
+    char *cypher_statement_str = NULL;
+
+    /* both arguments must be non-NULL */
+    if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
+    {
+        PG_RETURN_BOOL(false);
+    }
+
+    graph_name_str = PG_GETARG_CSTRING(0);
+    cypher_statement_str = PG_GETARG_CSTRING(1);
+
+    /* both strings must be non-NULL */
+    if (graph_name_str == NULL || cypher_statement_str == NULL)
+    {
+        PG_RETURN_BOOL(false);
+    }
+
+    set_session_info(graph_name_str, cypher_statement_str);
+
+    PG_RETURN_BOOL(true);
+}
diff --git a/src/include/utils/age_session_info.h b/src/include/utils/age_session_info.h
new file mode 100644
index 0000000..ebf0035
--- /dev/null
+++ b/src/include/utils/age_session_info.h
@@ -0,0 +1,29 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#ifndef AGE_SESSION_INFO_H
+#define AGE_SESSION_INFO_H
+
+bool is_session_info_prepared(void);
+char *get_session_info_graph_name(void);
+char *get_session_info_cypher_statement(void);
+void reset_session_info(void);
+
+#endif
+