You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@age.apache.org by "MuhammadTahaNaveed (via GitHub)" <gi...@apache.org> on 2026/01/10 15:06:12 UTC
[PR] Add vertex and edge composite types with direct field access optimization [age]
MuhammadTahaNaveed opened a new pull request, #2303:
URL: https://github.com/apache/age/pull/2303
- Introduce vertex and edge as pg composite types
vertex: (id, label, properties)
edge: (id, label, start_id, end_id, properties)
- Property access (a.name) now directly uses a.properties for agtype_access_operator instead of rebuilding via _agtype_build_vertex/edge
- Optimize accessor functions (id, properties, label, type, start_id, end_id) to use direct FieldSelect on composite types instead of agtype functions
- Add casts: vertex/edge to agtype, vertex/edge to json
- Fix label_name specific routine to use cache instead of ag_label scan
- Write/update clauses have executors strictly tied to agtype, due to which the variables after any write/update clause are carried forward as agtype.
- Allows users to completely skip agtype build functions and return vertex/edge for pure read queries.
- Change _label_name to return agtype since record comparisons are not allowed with cstring. Consequently, _agtype_build_vertex/edge now accept agtype as label.
- Fix MERGE clause type mismatch when accessing properties from previous MATCH clauses by wrapping columns with agtype_volatile_wrapper before namespace lookup.
- Update expression index in pgvector.sql, since now it uses raw properties column instead of _agtype_build_vertex/edge.
- Add regression tests
Assisted-by AI
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@age.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add vertex and edge composite types with direct field access optimization [age]
Posted by "MuhammadTahaNaveed (via GitHub)" <gi...@apache.org>.
MuhammadTahaNaveed commented on PR #2303:
URL: https://github.com/apache/age/pull/2303#issuecomment-3744266669
@jrgemignani
> 1. There aren't any additions to the `age--1.6.0--y.y.y.sql` file which is needed for upgrading. I won't be able to test actual performance without this file.
Updated `age--1.6.0--y.y.y.sql`
> 2. These changes to the types will generally make it difficult to upgrade.
The changed functions (_label_name, _agtype_build_vertex, _agtype_build_edge) are intended for internal use only. They are invoked by the parser/executor and are not meant to be called directly by users.
The upgrade script in age--1.6.0--y.y.y.sql manages the transition by dropping the old function signatures and creating the new ones. No data migration is required, as the underlying table structure remains unchanged.
From a user perspective, existing queries that return agtype continue to work without any changes. The composite types are introduced to improve internal query transformation and serve as an additional output option, rather than a breaking change.
> 3. The composite vertex and edge types are an interesting touch, but, it doesn't appear that you removed how the vertices and edges are represented in agtype. If this is intended, won't this increase the space taken by these objects?
The composite types don’t increase storage, as they are only a query-time representation. The underlying tables continue to store the same data as before.
The agtype representation is still required for paths (which are agtype arrays of vertices/edges), for storing entities in agtype containers, and for compatibility with existing agtype operators. When agtype is needed, the implicit casts(backed by functions vertex_to_agtype and edge_to_agtype) handle the conversion.
> Ambiguous operator added
Good catch. Fixed it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@age.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add vertex and edge composite types with direct field access optimization [age]
Posted by "jrgemignani (via GitHub)" <gi...@apache.org>.
jrgemignani commented on PR #2303:
URL: https://github.com/apache/age/pull/2303#issuecomment-4594700453
@MuhammadTahaNaveed One last Copilot review for sanity. Unless it has anything worth fixing, I will merge it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@age.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add vertex and edge composite types with direct field access optimization [age]
Posted by "MuhammadTahaNaveed (via GitHub)" <gi...@apache.org>.
MuhammadTahaNaveed commented on PR #2303:
URL: https://github.com/apache/age/pull/2303#issuecomment-4594559382
@jrgemignani
> 1. **`_get_vertex_by_graphid` has no `REVOKE … FROM PUBLIC`.** Largely mitigated because the underlying `get_vertex` performs `pg_class_aclcheck(… ACL_SELECT)`, so a caller lacking SELECT on the label table errors out. It still bypasses RLS row policies, though AGE label tables don't use RLS. Adding the REVOKE would be defense-in-depth.
> 2. **OID-dependent error text**: `reverse() unsupported argument type 16843` embeds the dynamic `VERTEXOID`. Deterministic in a fresh regress DB, but brittle if catalog OIDs shift.
Addressed both.
> The one structurally risky element — the edge composite field order (id, label, end_id, start_id, properties), with end_id before start_id
`end_id` precedes `start_id` intentionally, it matches the agtype edge's canonical key order (keys sorted by length, `end_id=6 < start_id=8`), keeping the composite positionally consistent with the agtype representation.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@age.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add vertex and edge composite types with direct field access optimization [age]
Posted by "jrgemignani (via GitHub)" <gi...@apache.org>.
jrgemignani merged PR #2303:
URL: https://github.com/apache/age/pull/2303
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@age.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add vertex and edge composite types with direct field access optimization [age]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #2303:
URL: https://github.com/apache/age/pull/2303#discussion_r2678745809
##########
regress/sql/expr.sql:
##########
@@ -3712,9 +3712,360 @@ $$) AS (out agtype);
SELECT * FROM create_graph('issue_2289');
SELECT * FROM cypher('issue_2289', $$ RETURN (1 IN []) AS v $$) AS (v agtype);
+--
+-- Accessor functions and properties extraction
+-- without _agtype_build.. functions
+--
+SELECT * FROM create_graph('accessor_opt');
+
+SELECT * FROM cypher('accessor_opt', $$
+ CREATE (a:Person {name: 'Alice', age: 30})-[r:KNOWS {since: 2020}]->(b:Person {name: 'Bob', age: 25})
+$$) AS (a agtype);
+
+--
+-- Vertex accessor tests
+--
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH (n:Person)
+ RETURN id(n)
+$$) AS (plan agtype);
+
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH (n:Person)
+ RETURN properties(n)
+$$) AS (plan agtype);
+
+SELECT * FROM cypher('accessor_opt', $$
+ MATCH (n:Person)
+ RETURN label(n)
+$$) AS (plan agtype);
+
+-- should use n.properties in _agtype_access_operator
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH (n:Person)
+ RETURN n.name, n.age
+$$) AS (a agtype, b agtype);
+
+--
+-- Edge accessor tests
+--
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH ()-[r:KNOWS]->()
+ RETURN id(r)
+$$) AS (plan agtype);
+
+SELECT * FROM cypher('accessor_opt', $$
+ MATCH ()-[r:KNOWS]->()
+ RETURN type(r)
+$$) AS (plan agtype);
+
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH ()-[r:KNOWS]->()
+ RETURN start_id(r)
+$$) AS (plan agtype);
+
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH ()-[r:KNOWS]->()
+ RETURN end_id(r)
+$$) AS (plan agtype);
+
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH ()-[r:KNOWS]->()
+ RETURN properties(r)
+$$) AS (plan agtype);
+
+-- should use r.properties in _agtype_access_operator
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH ()-[r:KNOWS]->()
+ RETURN r.since
+$$) AS (plan agtype);
+
+--
+-- Multiple accessors in same query
+--
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH (n:Person)
+ RETURN id(n) properties(n), n.name
+$$) AS (a agtype, c agtype, d agtype);
+
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH ()-[r:KNOWS]->()
+ RETURN id(r), start_id(r), end_id(r), properties(r)
+$$) AS (a agtype, c agtype, d agtype, e agtype);
+
+--
+-- Accessors in WHERE clause
+--
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH (n:Person)
+ WHERE id(n) > 0
+ RETURN n.name
+$$) AS (plan agtype);
+
+-- Compare two node ids
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH (a:Person)-[r:KNOWS]->(b:Person)
+ WHERE id(a) < id(b)
+ RETURN a.name, b.name
+$$) AS (aname agtype, bname agtype);
+
+-- Compare edge start_id and end_id
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH ()-[r:KNOWS]->()
+ WHERE start_id(r) <> end_id(r)
+ RETURN id(r)
+$$) AS (rid agtype);
+
+-- Property comparison
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH (n:Person)
+ WHERE n.age >= 25
+ RETURN n.name
+$$) AS (name agtype);
+
+-- Multiple property comparisons
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH (n:Person)
+ WHERE n.age > 20 AND n.name <> 'Unknown'
+ RETURN n.name
+$$) AS (name agtype);
+
+-- Compare properties of two nodes
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH (a:Person)-[r:KNOWS]->(b:Person)
+ WHERE a.age > b.age
+ RETURN a.name, b.name
+$$) AS (aname agtype, bname agtype);
+
+-- Compare id with property
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH (n:Person)
+ WHERE id(n) > n.age
+ RETURN n.name
+$$) AS (name agtype);
+
+-- Edge property comparison
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH ()-[r:KNOWS]->()
+ WHERE r.since > 2015
+ RETURN r.since
+$$) AS (since agtype);
+
+-- IS NOT NULL on accessor
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH (n:Person)
+ WHERE properties(n) IS NOT NULL
+ RETURN n.name
+$$) AS (name agtype);
+
+-- label() comparison
+SELECT * FROM cypher('accessor_opt', $$
+ MATCH (n)
+ WHERE label(n) = 'Person'
+ RETURN n.name
+$$) AS (name agtype);
+
+-- type() comparison on edge
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH ()-[r]->()
+ WHERE type(r) = 'KNOWS'
+ RETURN id(r)
+$$) AS (rid agtype);
+
+--
+-- Accessors in ORDER BY
+--
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH (n:Person)
+ RETURN n.name
+ ORDER BY n.name
+$$) AS (plan agtype);
+
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH (n:Person)
+ RETURN n.name
+ ORDER BY id(n)
+$$) AS (plan agtype);
+
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH (n:Person)
+ RETURN n.name, n.age
+ ORDER BY n.age, n.name
+$$) AS (name agtype, age agtype);
+
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH ()-[r:KNOWS]->()
+ RETURN r.since
Review Comment:
The ORDER BY clause specifies start_id(r) but only one column is returned (r.since), yet the AS clause expects two columns (typ agtype, since agtype). This mismatch will cause a runtime error.
```suggestion
RETURN type(r), r.since
```
##########
regress/sql/expr.sql:
##########
@@ -3712,9 +3712,360 @@ $$) AS (out agtype);
SELECT * FROM create_graph('issue_2289');
SELECT * FROM cypher('issue_2289', $$ RETURN (1 IN []) AS v $$) AS (v agtype);
+--
+-- Accessor functions and properties extraction
+-- without _agtype_build.. functions
+--
+SELECT * FROM create_graph('accessor_opt');
+
+SELECT * FROM cypher('accessor_opt', $$
+ CREATE (a:Person {name: 'Alice', age: 30})-[r:KNOWS {since: 2020}]->(b:Person {name: 'Bob', age: 25})
+$$) AS (a agtype);
+
+--
+-- Vertex accessor tests
+--
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH (n:Person)
+ RETURN id(n)
+$$) AS (plan agtype);
+
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH (n:Person)
+ RETURN properties(n)
+$$) AS (plan agtype);
+
+SELECT * FROM cypher('accessor_opt', $$
+ MATCH (n:Person)
+ RETURN label(n)
+$$) AS (plan agtype);
+
+-- should use n.properties in _agtype_access_operator
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH (n:Person)
+ RETURN n.name, n.age
+$$) AS (a agtype, b agtype);
+
+--
+-- Edge accessor tests
+--
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH ()-[r:KNOWS]->()
+ RETURN id(r)
+$$) AS (plan agtype);
+
+SELECT * FROM cypher('accessor_opt', $$
+ MATCH ()-[r:KNOWS]->()
+ RETURN type(r)
+$$) AS (plan agtype);
+
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH ()-[r:KNOWS]->()
+ RETURN start_id(r)
+$$) AS (plan agtype);
+
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH ()-[r:KNOWS]->()
+ RETURN end_id(r)
+$$) AS (plan agtype);
+
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH ()-[r:KNOWS]->()
+ RETURN properties(r)
+$$) AS (plan agtype);
+
+-- should use r.properties in _agtype_access_operator
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH ()-[r:KNOWS]->()
+ RETURN r.since
+$$) AS (plan agtype);
+
+--
+-- Multiple accessors in same query
+--
+SELECT * FROM cypher('accessor_opt', $$
+ EXPLAIN (VERBOSE, COSTS OFF)
+ MATCH (n:Person)
+ RETURN id(n) properties(n), n.name
Review Comment:
Missing comma between the two return values in the AS clause. The test expects three columns (a, c, d) but the RETURN clause appears to have "id(n) properties(n)" which is missing a comma between them. This is likely a typo in the test query itself.
```suggestion
RETURN id(n), properties(n), n.name
```
##########
src/backend/parser/cypher_expr.c:
##########
@@ -2001,6 +2068,145 @@ static bool function_exists(char *funcname, char *extension)
return found;
}
+/*
+ * Check if function name is an accessor function that can be optimized
+ */
+static bool is_accessor_function(const char *func_name)
+{
+ return (strcasecmp("id", func_name) == 0 ||
+ strcasecmp("properties", func_name) == 0 ||
+ strcasecmp("type", func_name) == 0 ||
+ strcasecmp("label", func_name) == 0 ||
+ strcasecmp("start_id", func_name) == 0 ||
+ strcasecmp("end_id", func_name) == 0 ||
+ strcasecmp("startnode", func_name) == 0 ||
+ strcasecmp("endnode", func_name) == 0);
+}
+
+static Oid get_entity_record_type(Node *node)
+{
+ Oid typeid = InvalidOid;
+
+ if (IsA(node, RowExpr))
+ {
+ typeid = ((RowExpr *)node)->row_typeid;
+ }
+ else if (IsA(node, Var))
+ {
+ typeid = ((Var *)node)->vartype;
+ }
+ else
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("argument must be a vertex or edge record")));
+ }
+
+ if (typeid != VERTEXOID && typeid != EDGEOID)
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("argument must be a vertex or edge record")));
+ }
+
+ return typeid;
+}
+
+/*
+ * Optimize accessor functions when called on RECORD entities
+ * Extracts fields directly using FieldSelect instead of building and parsing agtype
+ */
+static Node *optimize_accessor_function(cypher_parsestate *cpstate,
+ const char *func_name,
+ FuncCall *fn,
+ List *targs)
+{
+ ParseState *pstate = &cpstate->pstate;
+ Node *arg;
+ AttrNumber fieldnum;
+ Oid fieldtype;
+ Node *result;
+ Oid entity_type;
+ bool is_node_func = (strcasecmp(func_name, "startNode") == 0 ||
+ strcasecmp(func_name, "endNode") == 0);
+
+ if (is_node_func)
+ {
+ if (list_length(targs) < 2)
+ return NULL;
+ arg = (Node *)lsecond(targs);
+ }
+ else
+ {
+ if (list_length(targs) < 1)
+ return NULL;
+ arg = (Node *)linitial(targs);
+ }
+
+ if (!is_vertex_or_edge(arg))
+ {
+ return NULL;
+ }
+
+ entity_type = get_entity_record_type(arg);
+ get_record_field_info((char *)func_name, entity_type, &fieldnum, &fieldtype);
+
+ if (fieldnum != InvalidAttrNumber && fieldtype != InvalidOid)
+ {
+ Node *field = NULL;
+
+ /* Validate RowExpr has enough fields */
+ if (IsA(arg, RowExpr))
+ {
+ RowExpr *re = (RowExpr *)arg;
+ if (list_length(re->args) < fieldnum)
+ {
+ return NULL;
+ }
+
+ /* RowExpr args are 0-indexed, but fieldnum is 1-indexed */
+ field = (Node *)list_nth(re->args, fieldnum - 1);
+ }
+ else if (IsA(arg, Var))
+ {
+ field = (Node *)make_field_select((Var *)arg, fieldnum, fieldtype);
+ }
+
+ /* For startNode/endNode functions on edges, look up the vertex */
+ if (is_node_func && entity_type == EDGEOID)
+ {
+ Oid func_oid;
+ Node *graph_name;
+
+ graph_name = (Node *) makeConst(TEXTOID, -1, InvalidOid, -1,
+ CStringGetTextDatum(cpstate->graph_name),
+ false, false);
+
+ /* Call _get_vertex_by_graphid(graph_name, vertex_id) */
+ func_oid = get_ag_func_oid("_get_vertex_by_graphid", 2, TEXTOID, GRAPHIDOID);
+ result = (Node *)makeFuncExpr(func_oid, AGTYPEOID,
+ list_make2(graph_name, field),
+ InvalidOid, InvalidOid,
+ COERCE_EXPLICIT_CALL);
+ }
+ else
+ {
+ result = field;
+ }
+ }
+ else
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("%s() argument must be an %s or null",
+ func_name,
+ (entity_type == VERTEXOID) ? "edge" : "vertex"),
Review Comment:
The error message incorrectly states that the argument must be an "edge" when it should be a "vertex". The logic is inverted: when entity_type == VERTEXOID, the error says "must be an edge", but accessor functions like start_id() and end_id() should only work on edges, not vertices.
```suggestion
(entity_type == VERTEXOID) ? "vertex" : "edge"),
```
##########
src/backend/utils/adt/agtype.c:
##########
@@ -2308,7 +2356,25 @@ Datum _agtype_build_vertex(PG_FUNCTION_ARGS)
}
id = AG_GETARG_GRAPHID(0);
- label = PG_GETARG_CSTRING(1);
+ label_agtype = AG_GET_ARG_AGTYPE_P(1);
+
+ /* Extract the string from the agtype label */
+ if (!AGT_ROOT_IS_SCALAR(label_agtype))
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("_agtype_build_vertex() label must be a scalar string")));
+ }
+
+ label_value = get_ith_agtype_value_from_container(&label_agtype->root, 0);
+ if (label_value->type != AGTV_STRING)
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("_agtype_build_vertex() label must be a string")));
+ }
+
+ label = pnstrdup(label_value->val.string.val, label_value->val.string.len);
Review Comment:
The pnstrdup allocates memory for the label string, but there's no corresponding pfree to release this memory. While the label is used briefly in this function, it should be freed before returning to avoid a memory leak.
```suggestion
label = pnstrdup(label_value->val.string.val, label_value->val.string.len);
pfree(label);
```
##########
src/backend/parser/cypher_expr.c:
##########
@@ -1161,6 +1162,67 @@ static Node *transform_cypher_map(cypher_parsestate *cpstate, cypher_map *cm)
return (Node *)fexpr;
}
+/*
+ * Check if a node is a vertex or edge composite type.
+ */
+bool is_vertex_or_edge(Node *node)
+{
+ Oid typeid;
+
+ if (node == NULL)
+ return false;
+
+ if (IsA(node, RowExpr))
+ typeid = ((RowExpr *)node)->row_typeid;
+ else if (IsA(node, Var))
+ typeid = ((Var *)node)->vartype;
+ else
+ return false;
+
+ return (typeid == VERTEXOID || typeid == EDGEOID);
+}
+
+/*
+ * Extract a field from a vertex/edge Var or RowExpr.
+ */
+Node *extract_field_from_record(Node *node, char *field_name)
+{
+ AttrNumber fieldnum;
+ Oid fieldtype;
+ Oid type_id = get_entity_record_type(node);
+
+ get_record_field_info(field_name, type_id,
+ &fieldnum, &fieldtype);
+
+ if (fieldnum == InvalidAttrNumber || fieldtype == InvalidOid)
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_COLUMN),
+ errmsg("fieldname '%s' does not exist for the entity", field_name)));
+ }
+
+ if (IsA(node, Var))
+ {
+ return (Node *)make_field_select((Var *)node, fieldnum, fieldtype);
+ }
+ else if (IsA(node, RowExpr))
+ {
+ RowExpr *re = (RowExpr *)node;
+
+ if (list_length(re->args) < fieldnum)
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_UNDEFINED_COLUMN),
+ errmsg("field '%s' does not exist in RowExpr", field_name)));
+ }
+
Review Comment:
Trailing whitespace at the end of line 1218 should be removed to maintain consistent code formatting.
```suggestion
```
##########
src/backend/utils/adt/agtype.c:
##########
@@ -2381,10 +2450,28 @@ Datum _agtype_build_edge(PG_FUNCTION_ARGS)
if (fcinfo->args[3].isnull)
{
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
- errmsg("_agtype_build_vertex() label cannot be NULL")));
+ errmsg("_agtype_build_edge() label cannot be NULL")));
}
- label = PG_GETARG_CSTRING(3);
+ label_agtype = AG_GET_ARG_AGTYPE_P(3);
+
+ /* Extract the string from the agtype label */
+ if (!AGT_ROOT_IS_SCALAR(label_agtype))
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("_agtype_build_edge() label must be a scalar string")));
+ }
+
+ label_value = get_ith_agtype_value_from_container(&label_agtype->root, 0);
+ if (label_value->type != AGTV_STRING)
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("_agtype_build_edge() label must be a string")));
+ }
+
+ label = pnstrdup(label_value->val.string.val, label_value->val.string.len);
Review Comment:
Same memory leak issue as in _agtype_build_vertex: pnstrdup allocates memory for label but it's never freed before returning.
##########
src/backend/utils/adt/agtype.c:
##########
@@ -12138,11 +12342,12 @@ Datum agtype_volatile_wrapper(PG_FUNCTION_ARGS)
agtv_result.type = AGTV_BOOL;
agtv_result.val.boolean = DatumGetBool(arg);
}
- else if (type == INT2OID || type == INT4OID || type == INT8OID)
+ else if (type == INT2OID || type == INT4OID ||
+ type == INT8OID || type == GRAPHIDOID)
{
agtv_result.type = AGTV_INTEGER;
- if (type == INT8OID)
+ if (type == INT8OID || type == GRAPHIDOID)
{
agtv_result.val.int_value = DatumGetInt64(arg);
}
Review Comment:
The function agtype_volatile_wrapper now handles GRAPHIDOID by treating it the same as INT8OID (converting to AGTV_INTEGER). However, GRAPHIDOID should potentially be handled differently to preserve its semantic meaning as a graph identifier rather than just an integer. Consider whether graphid values should be wrapped in a specific agtype structure to distinguish them from regular integers.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@age.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add vertex and edge composite types with direct field access optimization [age]
Posted by "jrgemignani (via GitHub)" <gi...@apache.org>.
jrgemignani commented on PR #2303:
URL: https://github.com/apache/age/pull/2303#issuecomment-3741274729
@MuhammadTahaNaveed Cursory thoughts so far -
1. There aren't any additions to the `age--1.6.0--y.y.y.sql` file which is needed for upgrading.
2. These changes to the types will generally make it difficult to upgrade.
3. The composite vertex and edge types are an interesting touch, but, it doesn't appear that you removed how the vertices and edges are represented in agtype. If this is intended, won't this increase the space taken by these objects?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@age.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add vertex and edge composite types with direct field access optimization [age]
Posted by "MuhammadTahaNaveed (via GitHub)" <gi...@apache.org>.
MuhammadTahaNaveed commented on code in PR #2303:
URL: https://github.com/apache/age/pull/2303#discussion_r3336087736
##########
sql/agtype_graphid.sql:
##########
@@ -69,14 +96,163 @@ AS 'MODULE_PATHNAME';
-- agtype - edge
--
CREATE FUNCTION ag_catalog._agtype_build_edge(graphid, graphid, graphid,
- cstring, agtype)
+ agtype, agtype)
RETURNS agtype
LANGUAGE c
IMMUTABLE
CALLED ON NULL INPUT
PARALLEL SAFE
AS 'MODULE_PATHNAME';
+--
+-- vertex/edge to agtype cast functions
+--
+CREATE FUNCTION ag_catalog.vertex_to_agtype(vertex)
+ RETURNS agtype
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE FUNCTION ag_catalog.edge_to_agtype(edge)
+ RETURNS agtype
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+--
+-- Implicit casts from vertex/edge to agtype
+--
+CREATE CAST (vertex AS agtype)
+ WITH FUNCTION ag_catalog.vertex_to_agtype(vertex)
+AS IMPLICIT;
+
+CREATE CAST (edge AS agtype)
+ WITH FUNCTION ag_catalog.edge_to_agtype(edge)
+AS IMPLICIT;
+
+CREATE FUNCTION ag_catalog.vertex_to_json(vertex)
+ RETURNS json
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE FUNCTION ag_catalog.edge_to_json(edge)
+ RETURNS json
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE CAST (vertex AS json)
+ WITH FUNCTION ag_catalog.vertex_to_json(vertex);
+
+CREATE CAST (edge AS json)
+ WITH FUNCTION ag_catalog.edge_to_json(edge);
+
+CREATE FUNCTION ag_catalog.vertex_to_jsonb(vertex)
+ RETURNS jsonb
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE FUNCTION ag_catalog.edge_to_jsonb(edge)
+ RETURNS jsonb
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE CAST (vertex AS jsonb)
+ WITH FUNCTION ag_catalog.vertex_to_jsonb(vertex);
+
+CREATE CAST (edge AS jsonb)
+ WITH FUNCTION ag_catalog.edge_to_jsonb(edge);
+
+--
+-- Equality operators for vertex and edge (compare by id)
+--
+CREATE FUNCTION ag_catalog.vertex_eq(vertex, vertex)
+ RETURNS boolean
+ LANGUAGE sql
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS $$ SELECT $1.id = $2.id $$;
+
+CREATE OPERATOR = (
+ FUNCTION = ag_catalog.vertex_eq,
+ LEFTARG = vertex,
+ RIGHTARG = vertex,
+ COMMUTATOR = =,
+ NEGATOR = <>,
+ RESTRICT = eqsel,
+ JOIN = eqjoinsel
+);
Review Comment:
HASHES/MERGES are inert without a backing opclass, and vertex/edge have none. Hash/merge joins already work because vertex_eq inlines to a.id = b.id and uses graphid's opclass, adding the flags would just be misleading.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@age.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add vertex and edge composite types with direct field access optimization [age]
Posted by "MuhammadTahaNaveed (via GitHub)" <gi...@apache.org>.
MuhammadTahaNaveed commented on code in PR #2303:
URL: https://github.com/apache/age/pull/2303#discussion_r2678782292
##########
src/backend/parser/cypher_expr.c:
##########
@@ -2001,6 +2068,145 @@ static bool function_exists(char *funcname, char *extension)
return found;
}
+/*
+ * Check if function name is an accessor function that can be optimized
+ */
+static bool is_accessor_function(const char *func_name)
+{
+ return (strcasecmp("id", func_name) == 0 ||
+ strcasecmp("properties", func_name) == 0 ||
+ strcasecmp("type", func_name) == 0 ||
+ strcasecmp("label", func_name) == 0 ||
+ strcasecmp("start_id", func_name) == 0 ||
+ strcasecmp("end_id", func_name) == 0 ||
+ strcasecmp("startnode", func_name) == 0 ||
+ strcasecmp("endnode", func_name) == 0);
+}
+
+static Oid get_entity_record_type(Node *node)
+{
+ Oid typeid = InvalidOid;
+
+ if (IsA(node, RowExpr))
+ {
+ typeid = ((RowExpr *)node)->row_typeid;
+ }
+ else if (IsA(node, Var))
+ {
+ typeid = ((Var *)node)->vartype;
+ }
+ else
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("argument must be a vertex or edge record")));
+ }
+
+ if (typeid != VERTEXOID && typeid != EDGEOID)
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("argument must be a vertex or edge record")));
+ }
+
+ return typeid;
+}
+
+/*
+ * Optimize accessor functions when called on RECORD entities
+ * Extracts fields directly using FieldSelect instead of building and parsing agtype
+ */
+static Node *optimize_accessor_function(cypher_parsestate *cpstate,
+ const char *func_name,
+ FuncCall *fn,
+ List *targs)
+{
+ ParseState *pstate = &cpstate->pstate;
+ Node *arg;
+ AttrNumber fieldnum;
+ Oid fieldtype;
+ Node *result;
+ Oid entity_type;
+ bool is_node_func = (strcasecmp(func_name, "startNode") == 0 ||
+ strcasecmp(func_name, "endNode") == 0);
+
+ if (is_node_func)
+ {
+ if (list_length(targs) < 2)
+ return NULL;
+ arg = (Node *)lsecond(targs);
+ }
+ else
+ {
+ if (list_length(targs) < 1)
+ return NULL;
+ arg = (Node *)linitial(targs);
+ }
+
+ if (!is_vertex_or_edge(arg))
+ {
+ return NULL;
+ }
+
+ entity_type = get_entity_record_type(arg);
+ get_record_field_info((char *)func_name, entity_type, &fieldnum, &fieldtype);
+
+ if (fieldnum != InvalidAttrNumber && fieldtype != InvalidOid)
+ {
+ Node *field = NULL;
+
+ /* Validate RowExpr has enough fields */
+ if (IsA(arg, RowExpr))
+ {
+ RowExpr *re = (RowExpr *)arg;
+ if (list_length(re->args) < fieldnum)
+ {
+ return NULL;
+ }
+
+ /* RowExpr args are 0-indexed, but fieldnum is 1-indexed */
+ field = (Node *)list_nth(re->args, fieldnum - 1);
+ }
+ else if (IsA(arg, Var))
+ {
+ field = (Node *)make_field_select((Var *)arg, fieldnum, fieldtype);
+ }
+
+ /* For startNode/endNode functions on edges, look up the vertex */
+ if (is_node_func && entity_type == EDGEOID)
+ {
+ Oid func_oid;
+ Node *graph_name;
+
+ graph_name = (Node *) makeConst(TEXTOID, -1, InvalidOid, -1,
+ CStringGetTextDatum(cpstate->graph_name),
+ false, false);
+
+ /* Call _get_vertex_by_graphid(graph_name, vertex_id) */
+ func_oid = get_ag_func_oid("_get_vertex_by_graphid", 2, TEXTOID, GRAPHIDOID);
+ result = (Node *)makeFuncExpr(func_oid, AGTYPEOID,
+ list_make2(graph_name, field),
+ InvalidOid, InvalidOid,
+ COERCE_EXPLICIT_CALL);
+ }
+ else
+ {
+ result = field;
+ }
+ }
+ else
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("%s() argument must be an %s or null",
+ func_name,
+ (entity_type == VERTEXOID) ? "edge" : "vertex"),
Review Comment:
its intentional
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@age.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add vertex and edge composite types with direct field access optimization [age]
Posted by "jrgemignani (via GitHub)" <gi...@apache.org>.
jrgemignani commented on PR #2303:
URL: https://github.com/apache/age/pull/2303#issuecomment-4594391831
## Review: Logic soundness + regression-test validation
**Verdict: logic is sound, and all regression-test changes are legitimate (no masked correctness regressions).**
This PR replaces the `_agtype_build_vertex/edge(...)` construction path with native composite types (`vertex`, `edge`) plus implicit casts to agtype/json/jsonb, and adds a parser-level accessor optimization that lowers `id()/properties()/label()/type()/start_id()/end_id()/startNode()/endNode()` to direct `FieldSelect` nodes instead of building and re-parsing agtype.
### Logic soundness
The one structurally risky element — the `edge` composite field order `(id, label, end_id, start_id, properties)`, with **`end_id` before `start_id`** — is handled correctly and consistently across all four sites that must agree:
| Site | Mapping |
|---|---|
| SQL composite definition | `end_id` = attr 3, `start_id` = attr 4 |
| `edge_to_agtype` / `edge_to_json_string` (agtype.c) | reads `values[2]`→end_id, `values[3]`→start_id, calls `make_edge(id, start_id, end_id, …)` ✓ |
| `get_record_field_info` (cypher_clause.c) | `endnode`/`end_id`→field 3, `startnode`/`start_id`→field 4 ✓ |
| `make_edge_expr` RowExpr | `list_make5(id, label, end_id, start_id, props)` + matching colnames ✓ |
This is empirically confirmed by the new EXPLAIN tests: `start_id(r)` → `Output: (r.start_id)::agtype` and `end_id(r)` → `Output: (r.end_id)::agtype`. No swap.
Other verified items:
- **`_agtype_build_vertex/edge` label param cstring→agtype**: validates the value is a scalar string, errors otherwise; NULL handling intact; memory freed correctly.
- **`get_label_name(label_id, graph_oid)`** reads the existing label cache instead of a fresh `systable` scan (the perf win); returns cache memory (callers must not `pfree`).
- **`vertex_eq`/`edge_eq`** compare by `id` only — correct graph-entity identity semantics. No `HASHES`/`MERGES` declared, so no hash/merge-join hazard.
- **`optimize_accessor_function`**: the uninitialized-`result` concern is not exploitable — `startNode/endNode` on a vertex yields `InvalidAttrNumber`, which hits the `else` `ereport(ERROR)` (correct "must be an edge" message), so `result` is never read uninitialized.
- **`agtype_volatile_wrapper`** correctly extended for `GRAPHIDOID`, `VERTEXOID`, `EDGEOID`.
- **`agtype_categorize_type` / `datum_to_agtype`** correctly route composites through `vertex_to_agtype`/`edge_to_agtype` when boxing into maps/lists.
**Two non-blocking findings:**
1. **`_get_vertex_by_graphid` has no `REVOKE … FROM PUBLIC`.** Largely mitigated because the underlying `get_vertex` performs `pg_class_aclcheck(… ACL_SELECT)`, so a caller lacking SELECT on the label table errors out. It still bypasses RLS row policies, though AGE label tables don't use RLS. Adding the REVOKE would be defense-in-depth.
2. **OID-dependent error text**: `reverse() unsupported argument type 16843` embeds the dynamic `VERTEXOID`. Deterministic in a fresh regress DB, but brittle if catalog OIDs shift.
### Regression-test classification
| File | Δ | Classification | Verdict |
|---|---|---|---|
| `cypher_match.out` | 6 | **reorder only** | Same 6 (and 2) rows; only tie order changed. All ids present before & after. No `ORDER BY`. Benign. |
| `pgvector.out` | 4 | **intentional mod** (matches `.sql`) | HNSW index expression now indexes the raw `properties` column instead of `_agtype_build_vertex(...)`. Semantically equivalent. Sound. |
| `agtype.out` | 92 | **forced input mod** (matches `.sql`) | Labels changed `$$x$$`→`'"x"'` for the cstring→agtype signature. Result rows byte-identical. No behavior change. |
| `expr.out` (early hunks) | ~16 removed | **message mods + reorder** | Error text changes (still error, same semantics, now with `LINE … ^` pointer); 6 `case_statement` hunks are reorder-only (same 6 vertices; row carrying the real computed value keeps its `1`/`6`). Benign. |
| `expr.out` (final hunk) | +1099 | **additive** | New EXPLAIN/accessor coverage demonstrating the optimization. |
| `cypher_with.out` / `.sql` | +312 / +143 | **additive** | New feature coverage, zero deletions. |
**Reorder vetting:** every reordering-only change preserves the complete row set (all ids present before and after) and value-bearing rows retain their values. The reordering is a benign consequence of vertices/edges now being composite `RowExpr`s (different scan/aggregate ordering) — not a masked add, drop, or alteration of rows.
**Error-message modifications** all keep the same outcome (the query still errors with the same semantics), e.g. `cannot cast agtype vertex to type int` → `cannot cast type vertex to bigint for column "i"` (PG's native composite-coercion rejection), and accessor errors now carry an added `LINE n: … ^` position from `parser_errposition`.
### Summary
The core C logic is correct — including the bug-prone `end_id`/`start_id` composite ordering, which is consistently respected everywhere and proven by the new EXPLAIN tests. No regression-test change masks a correctness defect: changes are either (a) forced input adaptations with identical outputs, (b) intentional documented optimizations, (c) benign output reordering with full row-set preservation, or (d) purely additive new coverage. The only non-blocking nits are the missing `REVOKE` on `_get_vertex_by_graphid` (mitigated by an existing ACL check) and one OID-dependent error string.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@age.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add vertex and edge composite types with direct field access optimization [age]
Posted by "jrgemignani (via GitHub)" <gi...@apache.org>.
jrgemignani commented on PR #2303:
URL: https://github.com/apache/age/pull/2303#issuecomment-3741357175
@MuhammadTahaNaveed
**Current master branch**
```
psql-17.4-5432-pgsql=# SELECT create_graph('bug_demo');
NOTICE: graph "bug_demo" has been created
create_graph
--------------
(1 row)
psql-17.4-5432-pgsql=# SELECT * FROM cypher('bug_demo', $$ CREATE (:Person {name: 'Alice'}) $$) AS (v agtype);
v
---
(0 rows)
psql-17.4-5432-pgsql=# SELECT * FROM cypher('bug_demo', $$ CREATE (:Person {name: 'Bob'}) $$) AS (v agtype);
v
---
(0 rows)
psql-17.4-5432-pgsql=# SELECT * FROM cypher('bug_demo', $$
psql-17.4-5432-pgsql$# MATCH (a:Person), (b:Person)
psql-17.4-5432-pgsql$# WHERE a IN [a, b]
psql-17.4-5432-pgsql$# RETURN a.name
psql-17.4-5432-pgsql$# $$) AS (name agtype);
name
---------
"Alice"
"Alice"
"Bob"
"Bob"
(4 rows)
```
**PR 2303**
```
psql-17.7-5432-pgsql=# SELECT create_graph('bug_demo');
SELECT * FROM cypher('bug_demo', $$ CREATE (:Person {name: 'Alice'}) $$) AS (v agtype);
SELECT * FROM cypher('bug_demo', $$ CREATE (:Person {name: 'Bob'}) $$) AS (v agtype);
SELECT * FROM cypher('bug_demo', $$
MATCH (a:Person), (b:Person)
WHERE a IN [a, b]
RETURN a.name
$$) AS (name agtype);
NOTICE: graph "bug_demo" has been created
create_graph
--------------
(1 row)
v
---
(0 rows)
v
---
(0 rows)
ERROR: operator is not unique: vertex = vertex
LINE 3: WHERE a IN [a, b]
^
HINT: Could not choose a best candidate operator. You might need to add explicit type casts.
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@age.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add vertex and edge composite types with direct field access optimization [age]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #2303:
URL: https://github.com/apache/age/pull/2303#discussion_r2684277454
##########
src/backend/parser/cypher_expr.c:
##########
@@ -2001,6 +2068,145 @@ static bool function_exists(char *funcname, char *extension)
return found;
}
+/*
+ * Check if function name is an accessor function that can be optimized
+ */
+static bool is_accessor_function(const char *func_name)
+{
+ return (strcasecmp("id", func_name) == 0 ||
+ strcasecmp("properties", func_name) == 0 ||
+ strcasecmp("type", func_name) == 0 ||
+ strcasecmp("label", func_name) == 0 ||
+ strcasecmp("start_id", func_name) == 0 ||
+ strcasecmp("end_id", func_name) == 0 ||
+ strcasecmp("startnode", func_name) == 0 ||
+ strcasecmp("endnode", func_name) == 0);
+}
+
+static Oid get_entity_record_type(Node *node)
+{
+ Oid typeid = InvalidOid;
+
+ if (IsA(node, RowExpr))
+ {
+ typeid = ((RowExpr *)node)->row_typeid;
+ }
+ else if (IsA(node, Var))
+ {
+ typeid = ((Var *)node)->vartype;
+ }
+ else
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("argument must be a vertex or edge record")));
+ }
+
+ if (typeid != VERTEXOID && typeid != EDGEOID)
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("argument must be a vertex or edge record")));
+ }
+
+ return typeid;
+}
+
+/*
+ * Optimize accessor functions when called on RECORD entities
+ * Extracts fields directly using FieldSelect instead of building and parsing agtype
+ */
+static Node *optimize_accessor_function(cypher_parsestate *cpstate,
+ const char *func_name,
+ FuncCall *fn,
+ List *targs)
+{
+ ParseState *pstate = &cpstate->pstate;
+ Node *arg;
+ AttrNumber fieldnum;
+ Oid fieldtype;
+ Node *result;
+ Oid entity_type;
+ bool is_node_func = (strcasecmp(func_name, "startNode") == 0 ||
+ strcasecmp(func_name, "endNode") == 0);
+
+ if (is_node_func)
+ {
+ if (list_length(targs) < 2)
+ return NULL;
+ arg = (Node *)lsecond(targs);
+ }
+ else
+ {
+ if (list_length(targs) < 1)
+ return NULL;
+ arg = (Node *)linitial(targs);
+ }
+
+ if (!is_vertex_or_edge(arg))
+ {
+ return NULL;
+ }
+
+ entity_type = get_entity_record_type(arg);
+ get_record_field_info((char *)func_name, entity_type, &fieldnum, &fieldtype);
+
+ if (fieldnum != InvalidAttrNumber && fieldtype != InvalidOid)
+ {
+ Node *field = NULL;
+
+ /* Validate RowExpr has enough fields */
+ if (IsA(arg, RowExpr))
+ {
+ RowExpr *re = (RowExpr *)arg;
+ if (list_length(re->args) < fieldnum)
+ {
+ return NULL;
+ }
+
+ /* RowExpr args are 0-indexed, but fieldnum is 1-indexed */
+ field = (Node *)list_nth(re->args, fieldnum - 1);
+ }
+ else if (IsA(arg, Var))
+ {
+ field = (Node *)make_field_select((Var *)arg, fieldnum, fieldtype);
+ }
+
+ /* For startNode/endNode functions on edges, look up the vertex */
+ if (is_node_func && entity_type == EDGEOID)
+ {
+ Oid func_oid;
+ Node *graph_name;
+
+ graph_name = (Node *) makeConst(TEXTOID, -1, InvalidOid, -1,
+ CStringGetTextDatum(cpstate->graph_name),
+ false, false);
+
+ /* Call _get_vertex_by_graphid(graph_name, vertex_id) */
+ func_oid = get_ag_func_oid("_get_vertex_by_graphid", 2, TEXTOID, GRAPHIDOID);
+ result = (Node *)makeFuncExpr(func_oid, AGTYPEOID,
+ list_make2(graph_name, field),
+ InvalidOid, InvalidOid,
+ COERCE_EXPLICIT_CALL);
+ }
+ else
+ {
+ result = field;
+ }
Review Comment:
The condition at line 2176 checks for is_node_func AND EDGEOID, but startNode/endNode can only be called on edges, never on vertices. When entity_type is VERTEXOID and is_node_func is true, neither the if block (line 2176) nor the else block (line 2192) is entered, so result remains uninitialized. The logic should handle VERTEXOID with is_node_func as an error case.
##########
src/backend/parser/cypher_expr.c:
##########
@@ -2001,6 +2068,145 @@ static bool function_exists(char *funcname, char *extension)
return found;
}
+/*
+ * Check if function name is an accessor function that can be optimized
+ */
+static bool is_accessor_function(const char *func_name)
+{
+ return (strcasecmp("id", func_name) == 0 ||
+ strcasecmp("properties", func_name) == 0 ||
+ strcasecmp("type", func_name) == 0 ||
+ strcasecmp("label", func_name) == 0 ||
+ strcasecmp("start_id", func_name) == 0 ||
+ strcasecmp("end_id", func_name) == 0 ||
+ strcasecmp("startnode", func_name) == 0 ||
+ strcasecmp("endnode", func_name) == 0);
+}
+
+static Oid get_entity_record_type(Node *node)
+{
+ Oid typeid = InvalidOid;
+
+ if (IsA(node, RowExpr))
+ {
+ typeid = ((RowExpr *)node)->row_typeid;
+ }
+ else if (IsA(node, Var))
+ {
+ typeid = ((Var *)node)->vartype;
+ }
+ else
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("argument must be a vertex or edge record")));
+ }
+
+ if (typeid != VERTEXOID && typeid != EDGEOID)
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("argument must be a vertex or edge record")));
+ }
+
+ return typeid;
+}
+
+/*
+ * Optimize accessor functions when called on RECORD entities
+ * Extracts fields directly using FieldSelect instead of building and parsing agtype
+ */
+static Node *optimize_accessor_function(cypher_parsestate *cpstate,
+ const char *func_name,
+ FuncCall *fn,
+ List *targs)
+{
+ ParseState *pstate = &cpstate->pstate;
+ Node *arg;
+ AttrNumber fieldnum;
+ Oid fieldtype;
+ Node *result;
+ Oid entity_type;
+ bool is_node_func = (strcasecmp(func_name, "startNode") == 0 ||
+ strcasecmp(func_name, "endNode") == 0);
+
+ if (is_node_func)
+ {
+ if (list_length(targs) < 2)
+ return NULL;
+ arg = (Node *)lsecond(targs);
+ }
+ else
+ {
+ if (list_length(targs) < 1)
+ return NULL;
+ arg = (Node *)linitial(targs);
+ }
+
+ if (!is_vertex_or_edge(arg))
+ {
+ return NULL;
+ }
+
+ entity_type = get_entity_record_type(arg);
+ get_record_field_info((char *)func_name, entity_type, &fieldnum, &fieldtype);
+
+ if (fieldnum != InvalidAttrNumber && fieldtype != InvalidOid)
+ {
+ Node *field = NULL;
+
+ /* Validate RowExpr has enough fields */
+ if (IsA(arg, RowExpr))
+ {
+ RowExpr *re = (RowExpr *)arg;
+ if (list_length(re->args) < fieldnum)
+ {
+ return NULL;
+ }
+
+ /* RowExpr args are 0-indexed, but fieldnum is 1-indexed */
+ field = (Node *)list_nth(re->args, fieldnum - 1);
+ }
+ else if (IsA(arg, Var))
+ {
+ field = (Node *)make_field_select((Var *)arg, fieldnum, fieldtype);
+ }
+
+ /* For startNode/endNode functions on edges, look up the vertex */
+ if (is_node_func && entity_type == EDGEOID)
+ {
+ Oid func_oid;
+ Node *graph_name;
+
+ graph_name = (Node *) makeConst(TEXTOID, -1, InvalidOid, -1,
+ CStringGetTextDatum(cpstate->graph_name),
+ false, false);
+
+ /* Call _get_vertex_by_graphid(graph_name, vertex_id) */
+ func_oid = get_ag_func_oid("_get_vertex_by_graphid", 2, TEXTOID, GRAPHIDOID);
+ result = (Node *)makeFuncExpr(func_oid, AGTYPEOID,
+ list_make2(graph_name, field),
+ InvalidOid, InvalidOid,
+ COERCE_EXPLICIT_CALL);
+ }
+ else
+ {
+ result = field;
+ }
+ }
+ else
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("%s() argument must be an %s or null",
+ func_name,
+ (entity_type == VERTEXOID) ? "edge" : "vertex"),
+ parser_errposition(pstate, fn->location)));
+ }
+
+ return result;
Review Comment:
Missing return statement after the error. If the condition at line 2154 is false (fieldnum is InvalidAttrNumber or fieldtype is InvalidOid), the function reports an error at line 2199 but then continues to line 2207 to return result, which is uninitialized. Add a return after ereport or initialize result to NULL.
##########
sql/age_scalar.sql:
##########
@@ -93,6 +93,15 @@ RETURNS NULL ON NULL INPUT
PARALLEL SAFE
AS 'MODULE_PATHNAME';
+-- Helper function for optimized startNode/endNode
+CREATE FUNCTION ag_catalog._get_vertex_by_graphid(text, graphid)
+ RETURNS agtype
+ LANGUAGE c
+ STABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
Review Comment:
The new function `_get_vertex_by_graphid(text, graphid)` exposes a low-level vertex lookup to any caller without performing any privilege or RLS checks on the underlying label tables. Its C implementation uses `get_vertex`, which directly calls `table_open` / `table_beginscan` on the graph’s label tables by name, bypassing PostgreSQL `GRANT` and row-level security, so any role with `EXECUTE` on `_get_vertex_by_graphid` can fetch vertex data from graphs whose schemas/tables they may not otherwise be allowed to `SELECT`. To prevent unauthorized graph data access, restrict `EXECUTE` on `_get_vertex_by_graphid` (and similar helpers) to trusted roles only, or add explicit ACL/RLS checks before opening the target relation (e.g., verifying the caller has appropriate privileges on the resolved label table).
```suggestion
AS 'MODULE_PATHNAME';
REVOKE ALL ON FUNCTION ag_catalog._get_vertex_by_graphid(text, graphid) FROM PUBLIC;
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@age.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add vertex and edge composite types with direct field access optimization [age]
Posted by "MuhammadTahaNaveed (via GitHub)" <gi...@apache.org>.
MuhammadTahaNaveed commented on code in PR #2303:
URL: https://github.com/apache/age/pull/2303#discussion_r2678781745
##########
src/backend/utils/adt/agtype.c:
##########
@@ -2381,10 +2450,28 @@ Datum _agtype_build_edge(PG_FUNCTION_ARGS)
if (fcinfo->args[3].isnull)
{
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
- errmsg("_agtype_build_vertex() label cannot be NULL")));
+ errmsg("_agtype_build_edge() label cannot be NULL")));
}
- label = PG_GETARG_CSTRING(3);
+ label_agtype = AG_GET_ARG_AGTYPE_P(3);
+
+ /* Extract the string from the agtype label */
+ if (!AGT_ROOT_IS_SCALAR(label_agtype))
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("_agtype_build_edge() label must be a scalar string")));
+ }
+
+ label_value = get_ith_agtype_value_from_container(&label_agtype->root, 0);
+ if (label_value->type != AGTV_STRING)
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("_agtype_build_edge() label must be a string")));
+ }
+
+ label = pnstrdup(label_value->val.string.val, label_value->val.string.len);
Review Comment:
it is freed at the end of function
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@age.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add vertex and edge composite types with direct field access optimization [age]
Posted by "MuhammadTahaNaveed (via GitHub)" <gi...@apache.org>.
MuhammadTahaNaveed commented on code in PR #2303:
URL: https://github.com/apache/age/pull/2303#discussion_r2678781519
##########
src/backend/utils/adt/agtype.c:
##########
@@ -2308,7 +2356,25 @@ Datum _agtype_build_vertex(PG_FUNCTION_ARGS)
}
id = AG_GETARG_GRAPHID(0);
- label = PG_GETARG_CSTRING(1);
+ label_agtype = AG_GET_ARG_AGTYPE_P(1);
+
+ /* Extract the string from the agtype label */
+ if (!AGT_ROOT_IS_SCALAR(label_agtype))
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("_agtype_build_vertex() label must be a scalar string")));
+ }
+
+ label_value = get_ith_agtype_value_from_container(&label_agtype->root, 0);
+ if (label_value->type != AGTV_STRING)
+ {
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("_agtype_build_vertex() label must be a string")));
+ }
+
+ label = pnstrdup(label_value->val.string.val, label_value->val.string.len);
Review Comment:
it is freed at the end of function
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@age.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add vertex and edge composite types with direct field access optimization [age]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #2303:
URL: https://github.com/apache/age/pull/2303#discussion_r3335857621
##########
src/backend/utils/adt/agtype.c:
##########
@@ -2463,6 +2551,308 @@ Datum make_edge(Datum id, Datum startid, Datum endid, Datum label,
properties);
}
+PG_FUNCTION_INFO_V1(vertex_to_agtype);
+
+/*
+ * Cast function: vertex -> agtype
+ * Vertex: (id graphid, label agtype, properties agtype)
+ */
+Datum vertex_to_agtype(PG_FUNCTION_ARGS)
+{
+ HeapTupleHeader rec;
+ TupleDesc tupdesc;
+ HeapTupleData tuple;
+ Datum *values;
+ bool *nulls;
+ graphid id;
+ agtype *label;
+ agtype *properties;
+ Datum result;
+
+ rec = PG_GETARG_HEAPTUPLEHEADER(0);
+
+ tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(rec),
+ HeapTupleHeaderGetTypMod(rec));
+
+ tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+ tuple.t_data = rec;
+
+ values = (Datum *) palloc(3 * sizeof(Datum));
+ nulls = (bool *) palloc(3 * sizeof(bool));
+ heap_deform_tuple(&tuple, tupdesc, values, nulls);
+
+ if (nulls[0])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex id cannot be NULL")));
+ if (nulls[1])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex label cannot be NULL")));
+
+ id = DatumGetInt64(values[0]);
+ label = DATUM_GET_AGTYPE_P(values[1]);
+ properties = nulls[2] ? NULL : DATUM_GET_AGTYPE_P(values[2]);
+
+ if (properties == NULL)
+ {
+ agtype_build_state *bstate = init_agtype_build_state(0, AGT_FOBJECT);
+ properties = build_agtype(bstate);
+ pfree_agtype_build_state(bstate);
+ }
+
+ result = make_vertex(Int64GetDatum(id), PointerGetDatum(label),
+ PointerGetDatum(properties));
+
+ ReleaseTupleDesc(tupdesc);
+ pfree(values);
+ pfree(nulls);
+
+ return result;
+}
+
+PG_FUNCTION_INFO_V1(edge_to_agtype);
+
+/*
+ * Cast function: edge -> agtype
+ * Edge: (id graphid, label agtype, end_id graphid, start_id graphid, properties agtype)
+ */
+Datum edge_to_agtype(PG_FUNCTION_ARGS)
+{
+ HeapTupleHeader rec;
+ TupleDesc tupdesc;
+ HeapTupleData tuple;
+ Datum *values;
+ bool *nulls;
+ graphid id, start_id, end_id;
+ agtype *label;
+ agtype *properties;
+ Datum result;
+
+ rec = PG_GETARG_HEAPTUPLEHEADER(0);
+
+ tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(rec),
+ HeapTupleHeaderGetTypMod(rec));
+
+ tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+ tuple.t_data = rec;
+
+ values = (Datum *) palloc(5 * sizeof(Datum));
+ nulls = (bool *) palloc(5 * sizeof(bool));
+ heap_deform_tuple(&tuple, tupdesc, values, nulls);
+
+ if (nulls[0])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge id cannot be NULL")));
+ if (nulls[1])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge label cannot be NULL")));
+ if (nulls[2])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge end_id cannot be NULL")));
+ if (nulls[3])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge start_id cannot be NULL")));
+
+ id = DatumGetInt64(values[0]);
+ label = DATUM_GET_AGTYPE_P(values[1]);
+ end_id = DatumGetInt64(values[2]);
+ start_id = DatumGetInt64(values[3]);
+ properties = nulls[4] ? NULL : DATUM_GET_AGTYPE_P(values[4]);
+
+ if (properties == NULL)
+ {
+ agtype_build_state *bstate = init_agtype_build_state(0, AGT_FOBJECT);
+ properties = build_agtype(bstate);
+ pfree_agtype_build_state(bstate);
+ }
+
+ result = make_edge(Int64GetDatum(id), Int64GetDatum(start_id),
+ Int64GetDatum(end_id), PointerGetDatum(label),
+ PointerGetDatum(properties));
+
+ ReleaseTupleDesc(tupdesc);
+ pfree(values);
+ pfree(nulls);
+
+ return result;
+}
+
+/*
+ * Helper function to build JSON string from vertex composite type
+ */
+static char *vertex_to_json_string(HeapTupleHeader rec)
+{
+ TupleDesc tupdesc;
+ HeapTupleData tuple;
+ Datum *values;
+ bool *nulls;
+ graphid id;
+ agtype *label;
+ agtype *properties;
+ StringInfoData buf;
+ char *label_str;
+ char *props_str;
+
+ tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(rec),
+ HeapTupleHeaderGetTypMod(rec));
+
+ tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+ tuple.t_data = rec;
+
+ values = (Datum *) palloc(3 * sizeof(Datum));
+ nulls = (bool *) palloc(3 * sizeof(bool));
+ heap_deform_tuple(&tuple, tupdesc, values, nulls);
+
+ if (nulls[0])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex id cannot be NULL")));
+ if (nulls[1])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex label cannot be NULL")));
+
+ id = DatumGetInt64(values[0]);
+ label = DATUM_GET_AGTYPE_P(values[1]);
+ properties = nulls[2] ? NULL : DATUM_GET_AGTYPE_P(values[2]);
+
+ label_str = agtype_to_cstring(NULL, &label->root, VARSIZE(label));
+
+ if (properties != NULL)
+ {
+ props_str = agtype_to_cstring_worker(NULL, &properties->root,
+ VARSIZE(properties), false, false);
+ }
+ else
+ {
+ props_str = "{}";
+ }
+
+ initStringInfo(&buf);
+ appendStringInfo(&buf, "{\"id\": %ld, \"label\": %s, \"properties\": %s}",
+ id, label_str, props_str);
+
+ ReleaseTupleDesc(tupdesc);
+ pfree(values);
+ pfree(nulls);
+
+ return buf.data;
+}
+
+/*
+ * Helper function to build JSON string from edge composite type
+ * Edge: (id graphid, label agtype, end_id graphid, start_id graphid, properties agtype)
+ */
+static char *edge_to_json_string(HeapTupleHeader rec)
+{
+ TupleDesc tupdesc;
+ HeapTupleData tuple;
+ Datum *values;
+ bool *nulls;
+ graphid id, start_id, end_id;
+ agtype *label;
+ agtype *properties;
+ StringInfoData buf;
+ char *label_str;
+ char *props_str;
+
+ tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(rec),
+ HeapTupleHeaderGetTypMod(rec));
+
+ tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+ tuple.t_data = rec;
+
+ values = (Datum *) palloc(5 * sizeof(Datum));
+ nulls = (bool *) palloc(5 * sizeof(bool));
+ heap_deform_tuple(&tuple, tupdesc, values, nulls);
+
+ if (nulls[0])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge id cannot be NULL")));
+ if (nulls[1])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge label cannot be NULL")));
+ if (nulls[2])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge end_id cannot be NULL")));
+ if (nulls[3])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge start_id cannot be NULL")));
+
+ id = DatumGetInt64(values[0]);
+ label = DATUM_GET_AGTYPE_P(values[1]);
+ end_id = DatumGetInt64(values[2]);
+ start_id = DatumGetInt64(values[3]);
+ properties = nulls[4] ? NULL : DATUM_GET_AGTYPE_P(values[4]);
+
+ label_str = agtype_to_cstring(NULL, &label->root, VARSIZE(label));
+
+ if (properties != NULL)
+ {
+ props_str = agtype_to_cstring_worker(NULL, &properties->root,
+ VARSIZE(properties), false, false);
+ }
+ else
+ {
+ props_str = "{}";
+ }
+
+ initStringInfo(&buf);
+ appendStringInfo(&buf, "{\"id\": %ld, \"label\": %s, \"end_id\": %ld, \"start_id\": %ld, \"properties\": %s}",
+ id, label_str, end_id, start_id, props_str);
Review Comment:
Same portability issue as vertex JSON: `%ld` is not guaranteed to match `int64`/`graphid` and can produce incorrect JSON on some platforms. Use `INT64_FORMAT` for `id`, `start_id`, and `end_id`.
##########
src/include/utils/agtype.h:
##########
@@ -669,4 +669,11 @@ void clear_global_Oids_AGTYPE(void);
#define AGTYPEOID get_AGTYPEOID()
#define AGTYPEARRAYOID get_AGTYPEARRAYOID()
+/* Oid accessors for vertex and edge composite types */
+Oid get_VERTEXOID(void);
+Oid get_EDGEOID(void);
+void clear_global_Oids_VERTEX_EDGE(void);
+#define VERTEXOID get_VERTEXOID()
+#define EDGEOID get_EDGEOID()
Review Comment:
New cached OIDs for `vertex`/`edge` are introduced along with `clear_global_Oids_VERTEX_EDGE()`, but the extension drop path currently only clears AGTYPE and GRAPHID OIDs (see src/backend/catalog/ag_catalog.c). If AGE is dropped and recreated in the same backend, the cached VERTEX/EDGE OIDs can become stale. Please ensure the drop-extension cleanup calls `clear_global_Oids_VERTEX_EDGE()` as well.
##########
src/backend/utils/adt/agtype.c:
##########
@@ -2463,6 +2551,308 @@ Datum make_edge(Datum id, Datum startid, Datum endid, Datum label,
properties);
}
+PG_FUNCTION_INFO_V1(vertex_to_agtype);
+
+/*
+ * Cast function: vertex -> agtype
+ * Vertex: (id graphid, label agtype, properties agtype)
+ */
+Datum vertex_to_agtype(PG_FUNCTION_ARGS)
+{
+ HeapTupleHeader rec;
+ TupleDesc tupdesc;
+ HeapTupleData tuple;
+ Datum *values;
+ bool *nulls;
+ graphid id;
+ agtype *label;
+ agtype *properties;
+ Datum result;
+
+ rec = PG_GETARG_HEAPTUPLEHEADER(0);
+
+ tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(rec),
+ HeapTupleHeaderGetTypMod(rec));
+
+ tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+ tuple.t_data = rec;
+
+ values = (Datum *) palloc(3 * sizeof(Datum));
+ nulls = (bool *) palloc(3 * sizeof(bool));
+ heap_deform_tuple(&tuple, tupdesc, values, nulls);
+
+ if (nulls[0])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex id cannot be NULL")));
+ if (nulls[1])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex label cannot be NULL")));
+
+ id = DatumGetInt64(values[0]);
+ label = DATUM_GET_AGTYPE_P(values[1]);
+ properties = nulls[2] ? NULL : DATUM_GET_AGTYPE_P(values[2]);
+
+ if (properties == NULL)
+ {
+ agtype_build_state *bstate = init_agtype_build_state(0, AGT_FOBJECT);
+ properties = build_agtype(bstate);
+ pfree_agtype_build_state(bstate);
+ }
+
+ result = make_vertex(Int64GetDatum(id), PointerGetDatum(label),
+ PointerGetDatum(properties));
+
+ ReleaseTupleDesc(tupdesc);
+ pfree(values);
+ pfree(nulls);
+
+ return result;
+}
+
+PG_FUNCTION_INFO_V1(edge_to_agtype);
+
+/*
+ * Cast function: edge -> agtype
+ * Edge: (id graphid, label agtype, end_id graphid, start_id graphid, properties agtype)
+ */
+Datum edge_to_agtype(PG_FUNCTION_ARGS)
+{
+ HeapTupleHeader rec;
+ TupleDesc tupdesc;
+ HeapTupleData tuple;
+ Datum *values;
+ bool *nulls;
+ graphid id, start_id, end_id;
+ agtype *label;
+ agtype *properties;
+ Datum result;
+
+ rec = PG_GETARG_HEAPTUPLEHEADER(0);
+
+ tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(rec),
+ HeapTupleHeaderGetTypMod(rec));
+
+ tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+ tuple.t_data = rec;
+
+ values = (Datum *) palloc(5 * sizeof(Datum));
+ nulls = (bool *) palloc(5 * sizeof(bool));
+ heap_deform_tuple(&tuple, tupdesc, values, nulls);
+
+ if (nulls[0])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge id cannot be NULL")));
+ if (nulls[1])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge label cannot be NULL")));
+ if (nulls[2])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge end_id cannot be NULL")));
+ if (nulls[3])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge start_id cannot be NULL")));
+
+ id = DatumGetInt64(values[0]);
+ label = DATUM_GET_AGTYPE_P(values[1]);
+ end_id = DatumGetInt64(values[2]);
+ start_id = DatumGetInt64(values[3]);
+ properties = nulls[4] ? NULL : DATUM_GET_AGTYPE_P(values[4]);
+
+ if (properties == NULL)
+ {
+ agtype_build_state *bstate = init_agtype_build_state(0, AGT_FOBJECT);
+ properties = build_agtype(bstate);
+ pfree_agtype_build_state(bstate);
+ }
+
+ result = make_edge(Int64GetDatum(id), Int64GetDatum(start_id),
+ Int64GetDatum(end_id), PointerGetDatum(label),
+ PointerGetDatum(properties));
+
+ ReleaseTupleDesc(tupdesc);
+ pfree(values);
+ pfree(nulls);
+
+ return result;
+}
+
+/*
+ * Helper function to build JSON string from vertex composite type
+ */
+static char *vertex_to_json_string(HeapTupleHeader rec)
+{
+ TupleDesc tupdesc;
+ HeapTupleData tuple;
+ Datum *values;
+ bool *nulls;
+ graphid id;
+ agtype *label;
+ agtype *properties;
+ StringInfoData buf;
+ char *label_str;
+ char *props_str;
+
+ tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(rec),
+ HeapTupleHeaderGetTypMod(rec));
+
+ tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+ tuple.t_data = rec;
+
+ values = (Datum *) palloc(3 * sizeof(Datum));
+ nulls = (bool *) palloc(3 * sizeof(bool));
+ heap_deform_tuple(&tuple, tupdesc, values, nulls);
+
+ if (nulls[0])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex id cannot be NULL")));
+ if (nulls[1])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex label cannot be NULL")));
+
+ id = DatumGetInt64(values[0]);
+ label = DATUM_GET_AGTYPE_P(values[1]);
+ properties = nulls[2] ? NULL : DATUM_GET_AGTYPE_P(values[2]);
+
+ label_str = agtype_to_cstring(NULL, &label->root, VARSIZE(label));
+
+ if (properties != NULL)
+ {
+ props_str = agtype_to_cstring_worker(NULL, &properties->root,
+ VARSIZE(properties), false, false);
+ }
+ else
+ {
+ props_str = "{}";
+ }
+
+ initStringInfo(&buf);
+ appendStringInfo(&buf, "{\"id\": %ld, \"label\": %s, \"properties\": %s}",
+ id, label_str, props_str);
Review Comment:
The JSON builder uses `%ld` for `graphid` fields, but `graphid` is `int64` (see utils/graphid.h). `%ld` is not portable across platforms (e.g., Windows) and can mis-format 64-bit values. Use `INT64_FORMAT` for all `graphid` substitutions.
##########
sql/agtype_graphid.sql:
##########
@@ -69,14 +96,163 @@ AS 'MODULE_PATHNAME';
-- agtype - edge
--
CREATE FUNCTION ag_catalog._agtype_build_edge(graphid, graphid, graphid,
- cstring, agtype)
+ agtype, agtype)
RETURNS agtype
LANGUAGE c
IMMUTABLE
CALLED ON NULL INPUT
PARALLEL SAFE
AS 'MODULE_PATHNAME';
+--
+-- vertex/edge to agtype cast functions
+--
+CREATE FUNCTION ag_catalog.vertex_to_agtype(vertex)
+ RETURNS agtype
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE FUNCTION ag_catalog.edge_to_agtype(edge)
+ RETURNS agtype
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+--
+-- Implicit casts from vertex/edge to agtype
+--
+CREATE CAST (vertex AS agtype)
+ WITH FUNCTION ag_catalog.vertex_to_agtype(vertex)
+AS IMPLICIT;
+
+CREATE CAST (edge AS agtype)
+ WITH FUNCTION ag_catalog.edge_to_agtype(edge)
+AS IMPLICIT;
+
+CREATE FUNCTION ag_catalog.vertex_to_json(vertex)
+ RETURNS json
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE FUNCTION ag_catalog.edge_to_json(edge)
+ RETURNS json
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE CAST (vertex AS json)
+ WITH FUNCTION ag_catalog.vertex_to_json(vertex);
+
+CREATE CAST (edge AS json)
+ WITH FUNCTION ag_catalog.edge_to_json(edge);
+
+CREATE FUNCTION ag_catalog.vertex_to_jsonb(vertex)
+ RETURNS jsonb
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE FUNCTION ag_catalog.edge_to_jsonb(edge)
+ RETURNS jsonb
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE CAST (vertex AS jsonb)
+ WITH FUNCTION ag_catalog.vertex_to_jsonb(vertex);
+
+CREATE CAST (edge AS jsonb)
+ WITH FUNCTION ag_catalog.edge_to_jsonb(edge);
+
+--
+-- Equality operators for vertex and edge (compare by id)
+--
+CREATE FUNCTION ag_catalog.vertex_eq(vertex, vertex)
+ RETURNS boolean
+ LANGUAGE sql
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS $$ SELECT $1.id = $2.id $$;
+
+CREATE OPERATOR = (
+ FUNCTION = ag_catalog.vertex_eq,
+ LEFTARG = vertex,
+ RIGHTARG = vertex,
+ COMMUTATOR = =,
+ NEGATOR = <>,
+ RESTRICT = eqsel,
+ JOIN = eqjoinsel
+);
+
+CREATE FUNCTION ag_catalog.vertex_ne(vertex, vertex)
+ RETURNS boolean
+ LANGUAGE sql
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS $$ SELECT $1.id <> $2.id $$;
+
+CREATE OPERATOR <> (
+ FUNCTION = ag_catalog.vertex_ne,
+ LEFTARG = vertex,
+ RIGHTARG = vertex,
+ COMMUTATOR = <>,
+ NEGATOR = =,
+ RESTRICT = neqsel,
+ JOIN = neqjoinsel
+);
+
+CREATE FUNCTION ag_catalog.edge_eq(edge, edge)
+ RETURNS boolean
+ LANGUAGE sql
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS $$ SELECT $1.id = $2.id $$;
+
+CREATE OPERATOR = (
+ FUNCTION = ag_catalog.edge_eq,
+ LEFTARG = edge,
+ RIGHTARG = edge,
+ COMMUTATOR = =,
+ NEGATOR = <>,
+ RESTRICT = eqsel,
+ JOIN = eqjoinsel
+);
Review Comment:
Same planning concern as `vertex = vertex`: the edge equality operator isn't marked `HASHES`/`MERGES`, which can prevent hash/merge join selection when the operator is referenced directly. Adding these flags matches the pattern used by other equality operators in this extension (e.g., `graphid = graphid`).
##########
sql/age_scalar.sql:
##########
@@ -93,6 +93,15 @@ RETURNS NULL ON NULL INPUT
PARALLEL SAFE
AS 'MODULE_PATHNAME';
+-- Helper function for optimized startNode/endNode
+CREATE FUNCTION ag_catalog._get_vertex_by_graphid(text, graphid)
+ RETURNS agtype
+ LANGUAGE c
+ STABLE
+RETURNS NULL ON NULL INPUT
Review Comment:
The upgrade script revokes PUBLIC access to `ag_catalog._get_vertex_by_graphid(text, graphid)`, but the base install SQL here does not. That makes privileges differ depending on whether the function is created via fresh install vs upgrade. Consider adding the same REVOKE here (or dropping it from the upgrade script) to keep behavior consistent.
##########
src/backend/utils/adt/agtype.c:
##########
@@ -2463,6 +2551,308 @@ Datum make_edge(Datum id, Datum startid, Datum endid, Datum label,
properties);
}
+PG_FUNCTION_INFO_V1(vertex_to_agtype);
+
+/*
+ * Cast function: vertex -> agtype
+ * Vertex: (id graphid, label agtype, properties agtype)
+ */
+Datum vertex_to_agtype(PG_FUNCTION_ARGS)
+{
+ HeapTupleHeader rec;
+ TupleDesc tupdesc;
+ HeapTupleData tuple;
+ Datum *values;
+ bool *nulls;
+ graphid id;
+ agtype *label;
+ agtype *properties;
+ Datum result;
+
+ rec = PG_GETARG_HEAPTUPLEHEADER(0);
+
+ tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(rec),
+ HeapTupleHeaderGetTypMod(rec));
+
+ tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+ tuple.t_data = rec;
+
+ values = (Datum *) palloc(3 * sizeof(Datum));
+ nulls = (bool *) palloc(3 * sizeof(bool));
+ heap_deform_tuple(&tuple, tupdesc, values, nulls);
+
+ if (nulls[0])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex id cannot be NULL")));
+ if (nulls[1])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex label cannot be NULL")));
+
+ id = DatumGetInt64(values[0]);
+ label = DATUM_GET_AGTYPE_P(values[1]);
+ properties = nulls[2] ? NULL : DATUM_GET_AGTYPE_P(values[2]);
+
+ if (properties == NULL)
+ {
+ agtype_build_state *bstate = init_agtype_build_state(0, AGT_FOBJECT);
+ properties = build_agtype(bstate);
+ pfree_agtype_build_state(bstate);
+ }
+
+ result = make_vertex(Int64GetDatum(id), PointerGetDatum(label),
+ PointerGetDatum(properties));
+
+ ReleaseTupleDesc(tupdesc);
+ pfree(values);
+ pfree(nulls);
+
+ return result;
+}
+
+PG_FUNCTION_INFO_V1(edge_to_agtype);
+
+/*
+ * Cast function: edge -> agtype
+ * Edge: (id graphid, label agtype, end_id graphid, start_id graphid, properties agtype)
+ */
+Datum edge_to_agtype(PG_FUNCTION_ARGS)
+{
+ HeapTupleHeader rec;
+ TupleDesc tupdesc;
+ HeapTupleData tuple;
+ Datum *values;
+ bool *nulls;
+ graphid id, start_id, end_id;
+ agtype *label;
+ agtype *properties;
+ Datum result;
+
+ rec = PG_GETARG_HEAPTUPLEHEADER(0);
+
+ tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(rec),
+ HeapTupleHeaderGetTypMod(rec));
+
+ tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+ tuple.t_data = rec;
+
+ values = (Datum *) palloc(5 * sizeof(Datum));
+ nulls = (bool *) palloc(5 * sizeof(bool));
+ heap_deform_tuple(&tuple, tupdesc, values, nulls);
+
+ if (nulls[0])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge id cannot be NULL")));
+ if (nulls[1])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge label cannot be NULL")));
+ if (nulls[2])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge end_id cannot be NULL")));
+ if (nulls[3])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge start_id cannot be NULL")));
+
+ id = DatumGetInt64(values[0]);
+ label = DATUM_GET_AGTYPE_P(values[1]);
+ end_id = DatumGetInt64(values[2]);
+ start_id = DatumGetInt64(values[3]);
+ properties = nulls[4] ? NULL : DATUM_GET_AGTYPE_P(values[4]);
+
+ if (properties == NULL)
+ {
+ agtype_build_state *bstate = init_agtype_build_state(0, AGT_FOBJECT);
+ properties = build_agtype(bstate);
+ pfree_agtype_build_state(bstate);
+ }
+
+ result = make_edge(Int64GetDatum(id), Int64GetDatum(start_id),
+ Int64GetDatum(end_id), PointerGetDatum(label),
+ PointerGetDatum(properties));
+
+ ReleaseTupleDesc(tupdesc);
+ pfree(values);
+ pfree(nulls);
+
+ return result;
+}
+
+/*
+ * Helper function to build JSON string from vertex composite type
+ */
+static char *vertex_to_json_string(HeapTupleHeader rec)
+{
+ TupleDesc tupdesc;
+ HeapTupleData tuple;
+ Datum *values;
+ bool *nulls;
+ graphid id;
+ agtype *label;
+ agtype *properties;
+ StringInfoData buf;
+ char *label_str;
+ char *props_str;
+
+ tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(rec),
+ HeapTupleHeaderGetTypMod(rec));
+
+ tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+ tuple.t_data = rec;
+
+ values = (Datum *) palloc(3 * sizeof(Datum));
+ nulls = (bool *) palloc(3 * sizeof(bool));
+ heap_deform_tuple(&tuple, tupdesc, values, nulls);
+
+ if (nulls[0])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex id cannot be NULL")));
+ if (nulls[1])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex label cannot be NULL")));
+
+ id = DatumGetInt64(values[0]);
+ label = DATUM_GET_AGTYPE_P(values[1]);
+ properties = nulls[2] ? NULL : DATUM_GET_AGTYPE_P(values[2]);
+
+ label_str = agtype_to_cstring(NULL, &label->root, VARSIZE(label));
+
+ if (properties != NULL)
+ {
+ props_str = agtype_to_cstring_worker(NULL, &properties->root,
+ VARSIZE(properties), false, false);
+ }
+ else
+ {
+ props_str = "{}";
+ }
+
+ initStringInfo(&buf);
+ appendStringInfo(&buf, "{\"id\": %ld, \"label\": %s, \"properties\": %s}",
+ id, label_str, props_str);
Review Comment:
The JSON builder uses `%ld` for `graphid` fields, but `graphid` is `int64` (see utils/graphid.h). `%ld` is not portable across platforms (e.g., Windows) and can mis-format 64-bit values. Use `INT64_FORMAT` for all `graphid` substitutions.
##########
sql/agtype_graphid.sql:
##########
@@ -69,14 +96,163 @@ AS 'MODULE_PATHNAME';
-- agtype - edge
--
CREATE FUNCTION ag_catalog._agtype_build_edge(graphid, graphid, graphid,
- cstring, agtype)
+ agtype, agtype)
RETURNS agtype
LANGUAGE c
IMMUTABLE
CALLED ON NULL INPUT
PARALLEL SAFE
AS 'MODULE_PATHNAME';
+--
+-- vertex/edge to agtype cast functions
+--
+CREATE FUNCTION ag_catalog.vertex_to_agtype(vertex)
+ RETURNS agtype
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE FUNCTION ag_catalog.edge_to_agtype(edge)
+ RETURNS agtype
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+--
+-- Implicit casts from vertex/edge to agtype
+--
+CREATE CAST (vertex AS agtype)
+ WITH FUNCTION ag_catalog.vertex_to_agtype(vertex)
+AS IMPLICIT;
+
+CREATE CAST (edge AS agtype)
+ WITH FUNCTION ag_catalog.edge_to_agtype(edge)
+AS IMPLICIT;
+
+CREATE FUNCTION ag_catalog.vertex_to_json(vertex)
+ RETURNS json
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE FUNCTION ag_catalog.edge_to_json(edge)
+ RETURNS json
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE CAST (vertex AS json)
+ WITH FUNCTION ag_catalog.vertex_to_json(vertex);
+
+CREATE CAST (edge AS json)
+ WITH FUNCTION ag_catalog.edge_to_json(edge);
+
+CREATE FUNCTION ag_catalog.vertex_to_jsonb(vertex)
+ RETURNS jsonb
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE FUNCTION ag_catalog.edge_to_jsonb(edge)
+ RETURNS jsonb
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE CAST (vertex AS jsonb)
+ WITH FUNCTION ag_catalog.vertex_to_jsonb(vertex);
+
+CREATE CAST (edge AS jsonb)
+ WITH FUNCTION ag_catalog.edge_to_jsonb(edge);
+
+--
+-- Equality operators for vertex and edge (compare by id)
+--
+CREATE FUNCTION ag_catalog.vertex_eq(vertex, vertex)
+ RETURNS boolean
+ LANGUAGE sql
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS $$ SELECT $1.id = $2.id $$;
+
+CREATE OPERATOR = (
+ FUNCTION = ag_catalog.vertex_eq,
+ LEFTARG = vertex,
+ RIGHTARG = vertex,
+ COMMUTATOR = =,
+ NEGATOR = <>,
+ RESTRICT = eqsel,
+ JOIN = eqjoinsel
+);
Review Comment:
The vertex equality operator is intended to behave like an equality operator for planning purposes, but it isn't marked `HASHES`/`MERGES` (unlike the existing `graphid` `=` operator). Without these flags, the planner may miss hash/merge join optimizations when the operator itself (not its inlined SQL body) is used. Consider adding `HASHES, MERGES` here.
##########
src/backend/utils/adt/agtype.c:
##########
@@ -2463,6 +2551,308 @@ Datum make_edge(Datum id, Datum startid, Datum endid, Datum label,
properties);
}
+PG_FUNCTION_INFO_V1(vertex_to_agtype);
+
+/*
+ * Cast function: vertex -> agtype
+ * Vertex: (id graphid, label agtype, properties agtype)
+ */
+Datum vertex_to_agtype(PG_FUNCTION_ARGS)
+{
+ HeapTupleHeader rec;
+ TupleDesc tupdesc;
+ HeapTupleData tuple;
+ Datum *values;
+ bool *nulls;
+ graphid id;
+ agtype *label;
+ agtype *properties;
+ Datum result;
+
+ rec = PG_GETARG_HEAPTUPLEHEADER(0);
+
+ tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(rec),
+ HeapTupleHeaderGetTypMod(rec));
+
+ tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+ tuple.t_data = rec;
+
+ values = (Datum *) palloc(3 * sizeof(Datum));
+ nulls = (bool *) palloc(3 * sizeof(bool));
+ heap_deform_tuple(&tuple, tupdesc, values, nulls);
+
+ if (nulls[0])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex id cannot be NULL")));
+ if (nulls[1])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex label cannot be NULL")));
+
+ id = DatumGetInt64(values[0]);
+ label = DATUM_GET_AGTYPE_P(values[1]);
+ properties = nulls[2] ? NULL : DATUM_GET_AGTYPE_P(values[2]);
+
+ if (properties == NULL)
+ {
+ agtype_build_state *bstate = init_agtype_build_state(0, AGT_FOBJECT);
+ properties = build_agtype(bstate);
+ pfree_agtype_build_state(bstate);
+ }
+
+ result = make_vertex(Int64GetDatum(id), PointerGetDatum(label),
+ PointerGetDatum(properties));
+
+ ReleaseTupleDesc(tupdesc);
+ pfree(values);
+ pfree(nulls);
+
+ return result;
+}
+
+PG_FUNCTION_INFO_V1(edge_to_agtype);
+
+/*
+ * Cast function: edge -> agtype
+ * Edge: (id graphid, label agtype, end_id graphid, start_id graphid, properties agtype)
+ */
+Datum edge_to_agtype(PG_FUNCTION_ARGS)
+{
+ HeapTupleHeader rec;
+ TupleDesc tupdesc;
+ HeapTupleData tuple;
+ Datum *values;
+ bool *nulls;
+ graphid id, start_id, end_id;
+ agtype *label;
+ agtype *properties;
+ Datum result;
+
+ rec = PG_GETARG_HEAPTUPLEHEADER(0);
+
+ tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(rec),
+ HeapTupleHeaderGetTypMod(rec));
+
+ tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+ tuple.t_data = rec;
+
+ values = (Datum *) palloc(5 * sizeof(Datum));
+ nulls = (bool *) palloc(5 * sizeof(bool));
+ heap_deform_tuple(&tuple, tupdesc, values, nulls);
+
+ if (nulls[0])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge id cannot be NULL")));
+ if (nulls[1])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge label cannot be NULL")));
+ if (nulls[2])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge end_id cannot be NULL")));
+ if (nulls[3])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge start_id cannot be NULL")));
+
+ id = DatumGetInt64(values[0]);
+ label = DATUM_GET_AGTYPE_P(values[1]);
+ end_id = DatumGetInt64(values[2]);
+ start_id = DatumGetInt64(values[3]);
+ properties = nulls[4] ? NULL : DATUM_GET_AGTYPE_P(values[4]);
+
+ if (properties == NULL)
+ {
+ agtype_build_state *bstate = init_agtype_build_state(0, AGT_FOBJECT);
+ properties = build_agtype(bstate);
+ pfree_agtype_build_state(bstate);
+ }
+
+ result = make_edge(Int64GetDatum(id), Int64GetDatum(start_id),
+ Int64GetDatum(end_id), PointerGetDatum(label),
+ PointerGetDatum(properties));
+
+ ReleaseTupleDesc(tupdesc);
+ pfree(values);
+ pfree(nulls);
+
+ return result;
+}
+
+/*
+ * Helper function to build JSON string from vertex composite type
+ */
+static char *vertex_to_json_string(HeapTupleHeader rec)
+{
+ TupleDesc tupdesc;
+ HeapTupleData tuple;
+ Datum *values;
+ bool *nulls;
+ graphid id;
+ agtype *label;
+ agtype *properties;
+ StringInfoData buf;
+ char *label_str;
+ char *props_str;
+
+ tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(rec),
+ HeapTupleHeaderGetTypMod(rec));
+
+ tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+ tuple.t_data = rec;
+
+ values = (Datum *) palloc(3 * sizeof(Datum));
+ nulls = (bool *) palloc(3 * sizeof(bool));
+ heap_deform_tuple(&tuple, tupdesc, values, nulls);
+
+ if (nulls[0])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex id cannot be NULL")));
+ if (nulls[1])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex label cannot be NULL")));
+
+ id = DatumGetInt64(values[0]);
+ label = DATUM_GET_AGTYPE_P(values[1]);
+ properties = nulls[2] ? NULL : DATUM_GET_AGTYPE_P(values[2]);
+
+ label_str = agtype_to_cstring(NULL, &label->root, VARSIZE(label));
+
+ if (properties != NULL)
+ {
+ props_str = agtype_to_cstring_worker(NULL, &properties->root,
+ VARSIZE(properties), false, false);
+ }
+ else
+ {
+ props_str = "{}";
+ }
+
+ initStringInfo(&buf);
+ appendStringInfo(&buf, "{\"id\": %ld, \"label\": %s, \"properties\": %s}",
+ id, label_str, props_str);
+
+ ReleaseTupleDesc(tupdesc);
+ pfree(values);
+ pfree(nulls);
+
+ return buf.data;
+}
+
+/*
+ * Helper function to build JSON string from edge composite type
+ * Edge: (id graphid, label agtype, end_id graphid, start_id graphid, properties agtype)
+ */
+static char *edge_to_json_string(HeapTupleHeader rec)
+{
+ TupleDesc tupdesc;
+ HeapTupleData tuple;
+ Datum *values;
+ bool *nulls;
+ graphid id, start_id, end_id;
+ agtype *label;
+ agtype *properties;
+ StringInfoData buf;
+ char *label_str;
+ char *props_str;
+
+ tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(rec),
+ HeapTupleHeaderGetTypMod(rec));
+
+ tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+ tuple.t_data = rec;
+
+ values = (Datum *) palloc(5 * sizeof(Datum));
+ nulls = (bool *) palloc(5 * sizeof(bool));
+ heap_deform_tuple(&tuple, tupdesc, values, nulls);
+
+ if (nulls[0])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge id cannot be NULL")));
+ if (nulls[1])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge label cannot be NULL")));
+ if (nulls[2])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge end_id cannot be NULL")));
+ if (nulls[3])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge start_id cannot be NULL")));
+
+ id = DatumGetInt64(values[0]);
+ label = DATUM_GET_AGTYPE_P(values[1]);
+ end_id = DatumGetInt64(values[2]);
+ start_id = DatumGetInt64(values[3]);
+ properties = nulls[4] ? NULL : DATUM_GET_AGTYPE_P(values[4]);
+
+ label_str = agtype_to_cstring(NULL, &label->root, VARSIZE(label));
+
+ if (properties != NULL)
+ {
+ props_str = agtype_to_cstring_worker(NULL, &properties->root,
+ VARSIZE(properties), false, false);
+ }
+ else
+ {
+ props_str = "{}";
+ }
+
+ initStringInfo(&buf);
+ appendStringInfo(&buf, "{\"id\": %ld, \"label\": %s, \"end_id\": %ld, \"start_id\": %ld, \"properties\": %s}",
+ id, label_str, end_id, start_id, props_str);
Review Comment:
Same portability issue as vertex JSON: `%ld` is not guaranteed to match `int64`/`graphid` and can produce incorrect JSON on some platforms. Use `INT64_FORMAT` for `id`, `start_id`, and `end_id`.
##########
src/include/utils/agtype.h:
##########
@@ -669,4 +669,11 @@ void clear_global_Oids_AGTYPE(void);
#define AGTYPEOID get_AGTYPEOID()
#define AGTYPEARRAYOID get_AGTYPEARRAYOID()
+/* Oid accessors for vertex and edge composite types */
+Oid get_VERTEXOID(void);
+Oid get_EDGEOID(void);
+void clear_global_Oids_VERTEX_EDGE(void);
+#define VERTEXOID get_VERTEXOID()
+#define EDGEOID get_EDGEOID()
Review Comment:
New cached OIDs for `vertex`/`edge` are introduced along with `clear_global_Oids_VERTEX_EDGE()`, but the extension drop path currently only clears AGTYPE and GRAPHID OIDs (see src/backend/catalog/ag_catalog.c). If AGE is dropped and recreated in the same backend, the cached VERTEX/EDGE OIDs can become stale. Please ensure the drop-extension cleanup calls `clear_global_Oids_VERTEX_EDGE()` as well.
##########
sql/agtype_graphid.sql:
##########
@@ -69,14 +96,163 @@ AS 'MODULE_PATHNAME';
-- agtype - edge
--
CREATE FUNCTION ag_catalog._agtype_build_edge(graphid, graphid, graphid,
- cstring, agtype)
+ agtype, agtype)
RETURNS agtype
LANGUAGE c
IMMUTABLE
CALLED ON NULL INPUT
PARALLEL SAFE
AS 'MODULE_PATHNAME';
+--
+-- vertex/edge to agtype cast functions
+--
+CREATE FUNCTION ag_catalog.vertex_to_agtype(vertex)
+ RETURNS agtype
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE FUNCTION ag_catalog.edge_to_agtype(edge)
+ RETURNS agtype
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+--
+-- Implicit casts from vertex/edge to agtype
+--
+CREATE CAST (vertex AS agtype)
+ WITH FUNCTION ag_catalog.vertex_to_agtype(vertex)
+AS IMPLICIT;
+
+CREATE CAST (edge AS agtype)
+ WITH FUNCTION ag_catalog.edge_to_agtype(edge)
+AS IMPLICIT;
+
+CREATE FUNCTION ag_catalog.vertex_to_json(vertex)
+ RETURNS json
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE FUNCTION ag_catalog.edge_to_json(edge)
+ RETURNS json
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE CAST (vertex AS json)
+ WITH FUNCTION ag_catalog.vertex_to_json(vertex);
+
+CREATE CAST (edge AS json)
+ WITH FUNCTION ag_catalog.edge_to_json(edge);
+
+CREATE FUNCTION ag_catalog.vertex_to_jsonb(vertex)
+ RETURNS jsonb
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE FUNCTION ag_catalog.edge_to_jsonb(edge)
+ RETURNS jsonb
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE CAST (vertex AS jsonb)
+ WITH FUNCTION ag_catalog.vertex_to_jsonb(vertex);
+
+CREATE CAST (edge AS jsonb)
+ WITH FUNCTION ag_catalog.edge_to_jsonb(edge);
+
+--
+-- Equality operators for vertex and edge (compare by id)
+--
+CREATE FUNCTION ag_catalog.vertex_eq(vertex, vertex)
+ RETURNS boolean
+ LANGUAGE sql
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS $$ SELECT $1.id = $2.id $$;
+
+CREATE OPERATOR = (
+ FUNCTION = ag_catalog.vertex_eq,
+ LEFTARG = vertex,
+ RIGHTARG = vertex,
+ COMMUTATOR = =,
+ NEGATOR = <>,
+ RESTRICT = eqsel,
+ JOIN = eqjoinsel
+);
Review Comment:
The vertex equality operator is intended to behave like an equality operator for planning purposes, but it isn't marked `HASHES`/`MERGES` (unlike the existing `graphid` `=` operator). Without these flags, the planner may miss hash/merge join optimizations when the operator itself (not its inlined SQL body) is used. Consider adding `HASHES, MERGES` here.
##########
src/backend/utils/adt/agtype.c:
##########
@@ -2463,6 +2551,308 @@ Datum make_edge(Datum id, Datum startid, Datum endid, Datum label,
properties);
}
+PG_FUNCTION_INFO_V1(vertex_to_agtype);
+
+/*
+ * Cast function: vertex -> agtype
+ * Vertex: (id graphid, label agtype, properties agtype)
+ */
+Datum vertex_to_agtype(PG_FUNCTION_ARGS)
+{
+ HeapTupleHeader rec;
+ TupleDesc tupdesc;
+ HeapTupleData tuple;
+ Datum *values;
+ bool *nulls;
+ graphid id;
+ agtype *label;
+ agtype *properties;
+ Datum result;
+
+ rec = PG_GETARG_HEAPTUPLEHEADER(0);
+
+ tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(rec),
+ HeapTupleHeaderGetTypMod(rec));
+
+ tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+ tuple.t_data = rec;
+
+ values = (Datum *) palloc(3 * sizeof(Datum));
+ nulls = (bool *) palloc(3 * sizeof(bool));
+ heap_deform_tuple(&tuple, tupdesc, values, nulls);
+
+ if (nulls[0])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex id cannot be NULL")));
+ if (nulls[1])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex label cannot be NULL")));
+
+ id = DatumGetInt64(values[0]);
+ label = DATUM_GET_AGTYPE_P(values[1]);
+ properties = nulls[2] ? NULL : DATUM_GET_AGTYPE_P(values[2]);
+
+ if (properties == NULL)
+ {
+ agtype_build_state *bstate = init_agtype_build_state(0, AGT_FOBJECT);
+ properties = build_agtype(bstate);
+ pfree_agtype_build_state(bstate);
+ }
+
+ result = make_vertex(Int64GetDatum(id), PointerGetDatum(label),
+ PointerGetDatum(properties));
+
+ ReleaseTupleDesc(tupdesc);
+ pfree(values);
+ pfree(nulls);
+
+ return result;
+}
+
+PG_FUNCTION_INFO_V1(edge_to_agtype);
+
+/*
+ * Cast function: edge -> agtype
+ * Edge: (id graphid, label agtype, end_id graphid, start_id graphid, properties agtype)
+ */
+Datum edge_to_agtype(PG_FUNCTION_ARGS)
+{
+ HeapTupleHeader rec;
+ TupleDesc tupdesc;
+ HeapTupleData tuple;
+ Datum *values;
+ bool *nulls;
+ graphid id, start_id, end_id;
+ agtype *label;
+ agtype *properties;
+ Datum result;
+
+ rec = PG_GETARG_HEAPTUPLEHEADER(0);
+
+ tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(rec),
+ HeapTupleHeaderGetTypMod(rec));
+
+ tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+ tuple.t_data = rec;
+
+ values = (Datum *) palloc(5 * sizeof(Datum));
+ nulls = (bool *) palloc(5 * sizeof(bool));
+ heap_deform_tuple(&tuple, tupdesc, values, nulls);
+
+ if (nulls[0])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge id cannot be NULL")));
+ if (nulls[1])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge label cannot be NULL")));
+ if (nulls[2])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge end_id cannot be NULL")));
+ if (nulls[3])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge start_id cannot be NULL")));
+
+ id = DatumGetInt64(values[0]);
+ label = DATUM_GET_AGTYPE_P(values[1]);
+ end_id = DatumGetInt64(values[2]);
+ start_id = DatumGetInt64(values[3]);
+ properties = nulls[4] ? NULL : DATUM_GET_AGTYPE_P(values[4]);
+
+ if (properties == NULL)
+ {
+ agtype_build_state *bstate = init_agtype_build_state(0, AGT_FOBJECT);
+ properties = build_agtype(bstate);
+ pfree_agtype_build_state(bstate);
+ }
+
+ result = make_edge(Int64GetDatum(id), Int64GetDatum(start_id),
+ Int64GetDatum(end_id), PointerGetDatum(label),
+ PointerGetDatum(properties));
+
+ ReleaseTupleDesc(tupdesc);
+ pfree(values);
+ pfree(nulls);
+
+ return result;
+}
+
+/*
+ * Helper function to build JSON string from vertex composite type
+ */
+static char *vertex_to_json_string(HeapTupleHeader rec)
+{
+ TupleDesc tupdesc;
+ HeapTupleData tuple;
+ Datum *values;
+ bool *nulls;
+ graphid id;
+ agtype *label;
+ agtype *properties;
+ StringInfoData buf;
+ char *label_str;
+ char *props_str;
+
+ tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(rec),
+ HeapTupleHeaderGetTypMod(rec));
+
+ tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+ tuple.t_data = rec;
+
+ values = (Datum *) palloc(3 * sizeof(Datum));
+ nulls = (bool *) palloc(3 * sizeof(bool));
+ heap_deform_tuple(&tuple, tupdesc, values, nulls);
+
+ if (nulls[0])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex id cannot be NULL")));
+ if (nulls[1])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex label cannot be NULL")));
+
+ id = DatumGetInt64(values[0]);
+ label = DATUM_GET_AGTYPE_P(values[1]);
+ properties = nulls[2] ? NULL : DATUM_GET_AGTYPE_P(values[2]);
+
+ label_str = agtype_to_cstring(NULL, &label->root, VARSIZE(label));
+
+ if (properties != NULL)
+ {
+ props_str = agtype_to_cstring_worker(NULL, &properties->root,
+ VARSIZE(properties), false, false);
+ }
+ else
+ {
+ props_str = "{}";
+ }
+
+ initStringInfo(&buf);
+ appendStringInfo(&buf, "{\"id\": %ld, \"label\": %s, \"properties\": %s}",
+ id, label_str, props_str);
Review Comment:
The JSON builder uses `%ld` for `graphid` fields, but `graphid` is `int64` (see utils/graphid.h). `%ld` is not portable across platforms (e.g., Windows) and can mis-format 64-bit values. Use `INT64_FORMAT` for all `graphid` substitutions.
##########
src/backend/utils/adt/agtype.c:
##########
@@ -2463,6 +2551,308 @@ Datum make_edge(Datum id, Datum startid, Datum endid, Datum label,
properties);
}
+PG_FUNCTION_INFO_V1(vertex_to_agtype);
+
+/*
+ * Cast function: vertex -> agtype
+ * Vertex: (id graphid, label agtype, properties agtype)
+ */
+Datum vertex_to_agtype(PG_FUNCTION_ARGS)
+{
+ HeapTupleHeader rec;
+ TupleDesc tupdesc;
+ HeapTupleData tuple;
+ Datum *values;
+ bool *nulls;
+ graphid id;
+ agtype *label;
+ agtype *properties;
+ Datum result;
+
+ rec = PG_GETARG_HEAPTUPLEHEADER(0);
+
+ tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(rec),
+ HeapTupleHeaderGetTypMod(rec));
+
+ tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+ tuple.t_data = rec;
+
+ values = (Datum *) palloc(3 * sizeof(Datum));
+ nulls = (bool *) palloc(3 * sizeof(bool));
+ heap_deform_tuple(&tuple, tupdesc, values, nulls);
+
+ if (nulls[0])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex id cannot be NULL")));
+ if (nulls[1])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex label cannot be NULL")));
+
+ id = DatumGetInt64(values[0]);
+ label = DATUM_GET_AGTYPE_P(values[1]);
+ properties = nulls[2] ? NULL : DATUM_GET_AGTYPE_P(values[2]);
+
+ if (properties == NULL)
+ {
+ agtype_build_state *bstate = init_agtype_build_state(0, AGT_FOBJECT);
+ properties = build_agtype(bstate);
+ pfree_agtype_build_state(bstate);
+ }
+
+ result = make_vertex(Int64GetDatum(id), PointerGetDatum(label),
+ PointerGetDatum(properties));
+
+ ReleaseTupleDesc(tupdesc);
+ pfree(values);
+ pfree(nulls);
+
+ return result;
+}
+
+PG_FUNCTION_INFO_V1(edge_to_agtype);
+
+/*
+ * Cast function: edge -> agtype
+ * Edge: (id graphid, label agtype, end_id graphid, start_id graphid, properties agtype)
+ */
+Datum edge_to_agtype(PG_FUNCTION_ARGS)
+{
+ HeapTupleHeader rec;
+ TupleDesc tupdesc;
+ HeapTupleData tuple;
+ Datum *values;
+ bool *nulls;
+ graphid id, start_id, end_id;
+ agtype *label;
+ agtype *properties;
+ Datum result;
+
+ rec = PG_GETARG_HEAPTUPLEHEADER(0);
+
+ tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(rec),
+ HeapTupleHeaderGetTypMod(rec));
+
+ tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+ tuple.t_data = rec;
+
+ values = (Datum *) palloc(5 * sizeof(Datum));
+ nulls = (bool *) palloc(5 * sizeof(bool));
+ heap_deform_tuple(&tuple, tupdesc, values, nulls);
+
+ if (nulls[0])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge id cannot be NULL")));
+ if (nulls[1])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge label cannot be NULL")));
+ if (nulls[2])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge end_id cannot be NULL")));
+ if (nulls[3])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge start_id cannot be NULL")));
+
+ id = DatumGetInt64(values[0]);
+ label = DATUM_GET_AGTYPE_P(values[1]);
+ end_id = DatumGetInt64(values[2]);
+ start_id = DatumGetInt64(values[3]);
+ properties = nulls[4] ? NULL : DATUM_GET_AGTYPE_P(values[4]);
+
+ if (properties == NULL)
+ {
+ agtype_build_state *bstate = init_agtype_build_state(0, AGT_FOBJECT);
+ properties = build_agtype(bstate);
+ pfree_agtype_build_state(bstate);
+ }
+
+ result = make_edge(Int64GetDatum(id), Int64GetDatum(start_id),
+ Int64GetDatum(end_id), PointerGetDatum(label),
+ PointerGetDatum(properties));
+
+ ReleaseTupleDesc(tupdesc);
+ pfree(values);
+ pfree(nulls);
+
+ return result;
+}
+
+/*
+ * Helper function to build JSON string from vertex composite type
+ */
+static char *vertex_to_json_string(HeapTupleHeader rec)
+{
+ TupleDesc tupdesc;
+ HeapTupleData tuple;
+ Datum *values;
+ bool *nulls;
+ graphid id;
+ agtype *label;
+ agtype *properties;
+ StringInfoData buf;
+ char *label_str;
+ char *props_str;
+
+ tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(rec),
+ HeapTupleHeaderGetTypMod(rec));
+
+ tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+ tuple.t_data = rec;
+
+ values = (Datum *) palloc(3 * sizeof(Datum));
+ nulls = (bool *) palloc(3 * sizeof(bool));
+ heap_deform_tuple(&tuple, tupdesc, values, nulls);
+
+ if (nulls[0])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex id cannot be NULL")));
+ if (nulls[1])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("vertex label cannot be NULL")));
+
+ id = DatumGetInt64(values[0]);
+ label = DATUM_GET_AGTYPE_P(values[1]);
+ properties = nulls[2] ? NULL : DATUM_GET_AGTYPE_P(values[2]);
+
+ label_str = agtype_to_cstring(NULL, &label->root, VARSIZE(label));
+
+ if (properties != NULL)
+ {
+ props_str = agtype_to_cstring_worker(NULL, &properties->root,
+ VARSIZE(properties), false, false);
+ }
+ else
+ {
+ props_str = "{}";
+ }
+
+ initStringInfo(&buf);
+ appendStringInfo(&buf, "{\"id\": %ld, \"label\": %s, \"properties\": %s}",
+ id, label_str, props_str);
+
+ ReleaseTupleDesc(tupdesc);
+ pfree(values);
+ pfree(nulls);
+
+ return buf.data;
+}
+
+/*
+ * Helper function to build JSON string from edge composite type
+ * Edge: (id graphid, label agtype, end_id graphid, start_id graphid, properties agtype)
+ */
+static char *edge_to_json_string(HeapTupleHeader rec)
+{
+ TupleDesc tupdesc;
+ HeapTupleData tuple;
+ Datum *values;
+ bool *nulls;
+ graphid id, start_id, end_id;
+ agtype *label;
+ agtype *properties;
+ StringInfoData buf;
+ char *label_str;
+ char *props_str;
+
+ tupdesc = lookup_rowtype_tupdesc(HeapTupleHeaderGetTypeId(rec),
+ HeapTupleHeaderGetTypMod(rec));
+
+ tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
+ tuple.t_data = rec;
+
+ values = (Datum *) palloc(5 * sizeof(Datum));
+ nulls = (bool *) palloc(5 * sizeof(bool));
+ heap_deform_tuple(&tuple, tupdesc, values, nulls);
+
+ if (nulls[0])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge id cannot be NULL")));
+ if (nulls[1])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge label cannot be NULL")));
+ if (nulls[2])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge end_id cannot be NULL")));
+ if (nulls[3])
+ ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("edge start_id cannot be NULL")));
+
+ id = DatumGetInt64(values[0]);
+ label = DATUM_GET_AGTYPE_P(values[1]);
+ end_id = DatumGetInt64(values[2]);
+ start_id = DatumGetInt64(values[3]);
+ properties = nulls[4] ? NULL : DATUM_GET_AGTYPE_P(values[4]);
+
+ label_str = agtype_to_cstring(NULL, &label->root, VARSIZE(label));
+
+ if (properties != NULL)
+ {
+ props_str = agtype_to_cstring_worker(NULL, &properties->root,
+ VARSIZE(properties), false, false);
+ }
+ else
+ {
+ props_str = "{}";
+ }
+
+ initStringInfo(&buf);
+ appendStringInfo(&buf, "{\"id\": %ld, \"label\": %s, \"end_id\": %ld, \"start_id\": %ld, \"properties\": %s}",
+ id, label_str, end_id, start_id, props_str);
Review Comment:
Same portability issue as vertex JSON: `%ld` is not guaranteed to match `int64`/`graphid` and can produce incorrect JSON on some platforms. Use `INT64_FORMAT` for `id`, `start_id`, and `end_id`.
##########
src/include/utils/agtype.h:
##########
@@ -669,4 +669,11 @@ void clear_global_Oids_AGTYPE(void);
#define AGTYPEOID get_AGTYPEOID()
#define AGTYPEARRAYOID get_AGTYPEARRAYOID()
+/* Oid accessors for vertex and edge composite types */
+Oid get_VERTEXOID(void);
+Oid get_EDGEOID(void);
+void clear_global_Oids_VERTEX_EDGE(void);
+#define VERTEXOID get_VERTEXOID()
+#define EDGEOID get_EDGEOID()
Review Comment:
New cached OIDs for `vertex`/`edge` are introduced along with `clear_global_Oids_VERTEX_EDGE()`, but the extension drop path currently only clears AGTYPE and GRAPHID OIDs (see src/backend/catalog/ag_catalog.c). If AGE is dropped and recreated in the same backend, the cached VERTEX/EDGE OIDs can become stale. Please ensure the drop-extension cleanup calls `clear_global_Oids_VERTEX_EDGE()` as well.
##########
sql/agtype_graphid.sql:
##########
@@ -69,14 +96,163 @@ AS 'MODULE_PATHNAME';
-- agtype - edge
--
CREATE FUNCTION ag_catalog._agtype_build_edge(graphid, graphid, graphid,
- cstring, agtype)
+ agtype, agtype)
RETURNS agtype
LANGUAGE c
IMMUTABLE
CALLED ON NULL INPUT
PARALLEL SAFE
AS 'MODULE_PATHNAME';
+--
+-- vertex/edge to agtype cast functions
+--
+CREATE FUNCTION ag_catalog.vertex_to_agtype(vertex)
+ RETURNS agtype
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE FUNCTION ag_catalog.edge_to_agtype(edge)
+ RETURNS agtype
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+--
+-- Implicit casts from vertex/edge to agtype
+--
+CREATE CAST (vertex AS agtype)
+ WITH FUNCTION ag_catalog.vertex_to_agtype(vertex)
+AS IMPLICIT;
+
+CREATE CAST (edge AS agtype)
+ WITH FUNCTION ag_catalog.edge_to_agtype(edge)
+AS IMPLICIT;
+
+CREATE FUNCTION ag_catalog.vertex_to_json(vertex)
+ RETURNS json
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE FUNCTION ag_catalog.edge_to_json(edge)
+ RETURNS json
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE CAST (vertex AS json)
+ WITH FUNCTION ag_catalog.vertex_to_json(vertex);
+
+CREATE CAST (edge AS json)
+ WITH FUNCTION ag_catalog.edge_to_json(edge);
+
+CREATE FUNCTION ag_catalog.vertex_to_jsonb(vertex)
+ RETURNS jsonb
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE FUNCTION ag_catalog.edge_to_jsonb(edge)
+ RETURNS jsonb
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE CAST (vertex AS jsonb)
+ WITH FUNCTION ag_catalog.vertex_to_jsonb(vertex);
+
+CREATE CAST (edge AS jsonb)
+ WITH FUNCTION ag_catalog.edge_to_jsonb(edge);
+
+--
+-- Equality operators for vertex and edge (compare by id)
+--
+CREATE FUNCTION ag_catalog.vertex_eq(vertex, vertex)
+ RETURNS boolean
+ LANGUAGE sql
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS $$ SELECT $1.id = $2.id $$;
+
+CREATE OPERATOR = (
+ FUNCTION = ag_catalog.vertex_eq,
+ LEFTARG = vertex,
+ RIGHTARG = vertex,
+ COMMUTATOR = =,
+ NEGATOR = <>,
+ RESTRICT = eqsel,
+ JOIN = eqjoinsel
+);
+
+CREATE FUNCTION ag_catalog.vertex_ne(vertex, vertex)
+ RETURNS boolean
+ LANGUAGE sql
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS $$ SELECT $1.id <> $2.id $$;
+
+CREATE OPERATOR <> (
+ FUNCTION = ag_catalog.vertex_ne,
+ LEFTARG = vertex,
+ RIGHTARG = vertex,
+ COMMUTATOR = <>,
+ NEGATOR = =,
+ RESTRICT = neqsel,
+ JOIN = neqjoinsel
+);
+
+CREATE FUNCTION ag_catalog.edge_eq(edge, edge)
+ RETURNS boolean
+ LANGUAGE sql
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS $$ SELECT $1.id = $2.id $$;
+
+CREATE OPERATOR = (
+ FUNCTION = ag_catalog.edge_eq,
+ LEFTARG = edge,
+ RIGHTARG = edge,
+ COMMUTATOR = =,
+ NEGATOR = <>,
+ RESTRICT = eqsel,
+ JOIN = eqjoinsel
+);
Review Comment:
Same planning concern as `vertex = vertex`: the edge equality operator isn't marked `HASHES`/`MERGES`, which can prevent hash/merge join selection when the operator is referenced directly. Adding these flags matches the pattern used by other equality operators in this extension (e.g., `graphid = graphid`).
##########
sql/agtype_graphid.sql:
##########
@@ -69,14 +96,163 @@ AS 'MODULE_PATHNAME';
-- agtype - edge
--
CREATE FUNCTION ag_catalog._agtype_build_edge(graphid, graphid, graphid,
- cstring, agtype)
+ agtype, agtype)
RETURNS agtype
LANGUAGE c
IMMUTABLE
CALLED ON NULL INPUT
PARALLEL SAFE
AS 'MODULE_PATHNAME';
+--
+-- vertex/edge to agtype cast functions
+--
+CREATE FUNCTION ag_catalog.vertex_to_agtype(vertex)
+ RETURNS agtype
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE FUNCTION ag_catalog.edge_to_agtype(edge)
+ RETURNS agtype
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+--
+-- Implicit casts from vertex/edge to agtype
+--
+CREATE CAST (vertex AS agtype)
+ WITH FUNCTION ag_catalog.vertex_to_agtype(vertex)
+AS IMPLICIT;
+
+CREATE CAST (edge AS agtype)
+ WITH FUNCTION ag_catalog.edge_to_agtype(edge)
+AS IMPLICIT;
+
+CREATE FUNCTION ag_catalog.vertex_to_json(vertex)
+ RETURNS json
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE FUNCTION ag_catalog.edge_to_json(edge)
+ RETURNS json
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE CAST (vertex AS json)
+ WITH FUNCTION ag_catalog.vertex_to_json(vertex);
+
+CREATE CAST (edge AS json)
+ WITH FUNCTION ag_catalog.edge_to_json(edge);
+
+CREATE FUNCTION ag_catalog.vertex_to_jsonb(vertex)
+ RETURNS jsonb
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE FUNCTION ag_catalog.edge_to_jsonb(edge)
+ RETURNS jsonb
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE CAST (vertex AS jsonb)
+ WITH FUNCTION ag_catalog.vertex_to_jsonb(vertex);
+
+CREATE CAST (edge AS jsonb)
+ WITH FUNCTION ag_catalog.edge_to_jsonb(edge);
+
+--
+-- Equality operators for vertex and edge (compare by id)
+--
+CREATE FUNCTION ag_catalog.vertex_eq(vertex, vertex)
+ RETURNS boolean
+ LANGUAGE sql
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS $$ SELECT $1.id = $2.id $$;
+
+CREATE OPERATOR = (
+ FUNCTION = ag_catalog.vertex_eq,
+ LEFTARG = vertex,
+ RIGHTARG = vertex,
+ COMMUTATOR = =,
+ NEGATOR = <>,
+ RESTRICT = eqsel,
+ JOIN = eqjoinsel
+);
Review Comment:
The vertex equality operator is intended to behave like an equality operator for planning purposes, but it isn't marked `HASHES`/`MERGES` (unlike the existing `graphid` `=` operator). Without these flags, the planner may miss hash/merge join optimizations when the operator itself (not its inlined SQL body) is used. Consider adding `HASHES, MERGES` here.
##########
sql/age_scalar.sql:
##########
@@ -93,6 +93,15 @@ RETURNS NULL ON NULL INPUT
PARALLEL SAFE
AS 'MODULE_PATHNAME';
+-- Helper function for optimized startNode/endNode
+CREATE FUNCTION ag_catalog._get_vertex_by_graphid(text, graphid)
+ RETURNS agtype
+ LANGUAGE c
+ STABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
Review Comment:
The upgrade script revokes PUBLIC access to `ag_catalog._get_vertex_by_graphid(text, graphid)`, but the base install SQL here does not. That makes privileges differ depending on whether the function is created via fresh install vs upgrade. Consider adding the same REVOKE here (or dropping it from the upgrade script) to keep behavior consistent.
##########
sql/agtype_graphid.sql:
##########
@@ -69,14 +96,163 @@ AS 'MODULE_PATHNAME';
-- agtype - edge
--
CREATE FUNCTION ag_catalog._agtype_build_edge(graphid, graphid, graphid,
- cstring, agtype)
+ agtype, agtype)
RETURNS agtype
LANGUAGE c
IMMUTABLE
CALLED ON NULL INPUT
PARALLEL SAFE
AS 'MODULE_PATHNAME';
+--
+-- vertex/edge to agtype cast functions
+--
+CREATE FUNCTION ag_catalog.vertex_to_agtype(vertex)
+ RETURNS agtype
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE FUNCTION ag_catalog.edge_to_agtype(edge)
+ RETURNS agtype
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+--
+-- Implicit casts from vertex/edge to agtype
+--
+CREATE CAST (vertex AS agtype)
+ WITH FUNCTION ag_catalog.vertex_to_agtype(vertex)
+AS IMPLICIT;
+
+CREATE CAST (edge AS agtype)
+ WITH FUNCTION ag_catalog.edge_to_agtype(edge)
+AS IMPLICIT;
+
+CREATE FUNCTION ag_catalog.vertex_to_json(vertex)
+ RETURNS json
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE FUNCTION ag_catalog.edge_to_json(edge)
+ RETURNS json
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE CAST (vertex AS json)
+ WITH FUNCTION ag_catalog.vertex_to_json(vertex);
+
+CREATE CAST (edge AS json)
+ WITH FUNCTION ag_catalog.edge_to_json(edge);
+
+CREATE FUNCTION ag_catalog.vertex_to_jsonb(vertex)
+ RETURNS jsonb
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE FUNCTION ag_catalog.edge_to_jsonb(edge)
+ RETURNS jsonb
+ LANGUAGE c
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS 'MODULE_PATHNAME';
+
+CREATE CAST (vertex AS jsonb)
+ WITH FUNCTION ag_catalog.vertex_to_jsonb(vertex);
+
+CREATE CAST (edge AS jsonb)
+ WITH FUNCTION ag_catalog.edge_to_jsonb(edge);
+
+--
+-- Equality operators for vertex and edge (compare by id)
+--
+CREATE FUNCTION ag_catalog.vertex_eq(vertex, vertex)
+ RETURNS boolean
+ LANGUAGE sql
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS $$ SELECT $1.id = $2.id $$;
+
+CREATE OPERATOR = (
+ FUNCTION = ag_catalog.vertex_eq,
+ LEFTARG = vertex,
+ RIGHTARG = vertex,
+ COMMUTATOR = =,
+ NEGATOR = <>,
+ RESTRICT = eqsel,
+ JOIN = eqjoinsel
+);
+
+CREATE FUNCTION ag_catalog.vertex_ne(vertex, vertex)
+ RETURNS boolean
+ LANGUAGE sql
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS $$ SELECT $1.id <> $2.id $$;
+
+CREATE OPERATOR <> (
+ FUNCTION = ag_catalog.vertex_ne,
+ LEFTARG = vertex,
+ RIGHTARG = vertex,
+ COMMUTATOR = <>,
+ NEGATOR = =,
+ RESTRICT = neqsel,
+ JOIN = neqjoinsel
+);
+
+CREATE FUNCTION ag_catalog.edge_eq(edge, edge)
+ RETURNS boolean
+ LANGUAGE sql
+ IMMUTABLE
+RETURNS NULL ON NULL INPUT
+PARALLEL SAFE
+AS $$ SELECT $1.id = $2.id $$;
+
+CREATE OPERATOR = (
+ FUNCTION = ag_catalog.edge_eq,
+ LEFTARG = edge,
+ RIGHTARG = edge,
+ COMMUTATOR = =,
+ NEGATOR = <>,
+ RESTRICT = eqsel,
+ JOIN = eqjoinsel
+);
Review Comment:
Same planning concern as `vertex = vertex`: the edge equality operator isn't marked `HASHES`/`MERGES`, which can prevent hash/merge join selection when the operator is referenced directly. Adding these flags matches the pattern used by other equality operators in this extension (e.g., `graphid = graphid`).
##########
sql/age_scalar.sql:
##########
@@ -93,6 +93,15 @@ RETURNS NULL ON NULL INPUT
PARALLEL SAFE
AS 'MODULE_PATHNAME';
+-- Helper function for optimized startNode/endNode
+CREATE FUNCTION ag_catalog._get_vertex_by_graphid(text, graphid)
+ RETURNS agtype
+ LANGUAGE c
+ STABLE
+RETURNS NULL ON NULL INPUT
Review Comment:
The upgrade script revokes PUBLIC access to `ag_catalog._get_vertex_by_graphid(text, graphid)`, but the base install SQL here does not. That makes privileges differ depending on whether the function is created via fresh install vs upgrade. Consider adding the same REVOKE here (or dropping it from the upgrade script) to keep behavior consistent.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@age.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org