SQL Property Graph Queries (SQL/PGQ)
SQL Property Graph Queries (SQL/PGQ)
Here is a prototype implementation of SQL property graph queries (SQL/PGQ), following SQL:2023. This was talked about briefly at the FOSDEM developer meeting, and a few people were interested, so I wrapped up what I had in progress into a presentable form. There is some documentation to get started in doc/src/sgml/ddl.sgml and doc/src/sgml/queries.sgml. To learn more about this facility, here are some external resources: * An article about a competing product: https://oracle-base.com/articles/23c/sql-property-graphs-and-sql-pgq-23c (All the queries in the article work, except the ones using vertex_id() and edge_id(), which are non-standard, and the JSON examples at the end, which require some of the in-progress JSON functionality for PostgreSQL.) * An academic paper related to another competing product: https://www.cidrdb.org/cidr2023/papers/p66-wolde.pdf (The main part of this paper discusses advanced functionality that my patch doesn't have.) * A 2019 presentation about graph databases: https://www.pgcon.org/2019/schedule/events/1300.en.html (There is also a video.) * (Vik has a recent presentation "Property Graphs: When the Relational Model Is Not Enough", but I haven't found the content posted online.) The patch is quite fragile, and treading outside the tested paths will likely lead to grave misbehavior. Use with caution. But I feel that the general structure is ok, and we just need to fill in the proverbial few thousand lines of code in the designated areas.
Re: SQL Property Graph Queries (SQL/PGQ)
Hi, On 2024-02-16 15:53:11 +0100, Peter Eisentraut wrote: > The patch is quite fragile, and treading outside the tested paths will > likely lead to grave misbehavior. Use with caution. But I feel that > the general structure is ok, and we just need to fill in the > proverbial few thousand lines of code in the designated areas. One aspect that I m concerned with structurally is that the transformation, from property graph queries to something postgres understands, is done via the rewrite system. I doubt that that is a good idea. For one it bars the planner from making plans that benefit from the graph query formulation. But more importantly, we IMO should reduce usage of the rewrite system, not increase it. Greetings, Andres Freund
Re: SQL Property Graph Queries (SQL/PGQ)
On 16.02.24 20:23, Andres Freund wrote: > One aspect that I m concerned with structurally is that the transformation, > from property graph queries to something postgres understands, is done via the > rewrite system. I doubt that that is a good idea. For one it bars the planner > from making plans that benefit from the graph query formulation. But more > importantly, we IMO should reduce usage of the rewrite system, not increase > it. PGQ is meant to be implemented like that, like views expanding to joins and unions. This is what I have gathered during the specification process, and from other implementations, and from academics. There are certainly other ways to combine relational and graph database stuff, like with native graph storage and specialized execution support, but this is not that, and to some extent PGQ was created to supplant those other approaches. Many people will agree that the rewriter is sort of weird and archaic at this point. But I'm not aware of any plans or proposals to do anything about it. As long as the view expansion takes place there, it makes sense to align with that. For example, all the view security stuff (privileges, security barriers, etc.) will eventually need to be considered, and it would make sense to do that in a consistent way. So for now, I'm working with what we have, but let's see where it goes. (Note to self: Check that graph inside view inside graph inside view ... works.)
Re: SQL Property Graph Queries (SQL/PGQ)
On 2/23/24 17:15, Peter Eisentraut wrote: > On 16.02.24 20:23, Andres Freund wrote: >> One aspect that I m concerned with structurally is that the >> transformation, >> from property graph queries to something postgres understands, is done >> via the >> rewrite system. I doubt that that is a good idea. For one it bars the >> planner >> from making plans that benefit from the graph query formulation. But more >> importantly, we IMO should reduce usage of the rewrite system, not >> increase >> it. > > PGQ is meant to be implemented like that, like views expanding to joins > and unions. This is what I have gathered during the specification > process, and from other implementations, and from academics. There are > certainly other ways to combine relational and graph database stuff, > like with native graph storage and specialized execution support, but > this is not that, and to some extent PGQ was created to supplant those > other approaches. > I understand PGQ was meant to be implemented as a bit of a "syntactic sugar" on top of relations, instead of inventing some completely new ways to store/query graph data. But does that really mean it needs to be translated to relations this early / in rewriter? I haven't thought about it very deeply, but won't that discard useful information about semantics of the query, which might be useful when planning/executing the query? I've somehow imagined we'd be able to invent some new index types, or utilize some other type of auxiliary structure, maybe some special executor node, but it seems harder without this extra info ... > Many people will agree that the rewriter is sort of weird and archaic at > this point. But I'm not aware of any plans or proposals to do anything > about it. As long as the view expansion takes place there, it makes > sense to align with that. For example, all the view security stuff > (privileges, security barriers, etc.) will eventually need to be > considered, and it would make sense to do that in a consistent way. So > for now, I'm working with what we have, but let's see where it goes. > > (Note to self: Check that graph inside view inside graph inside view ... > works.) > AFAIK the "policy" regarding rewriter was that we don't want to use it for user stuff (e.g. people using it for partitioning), but I'm not sure about internal stuff. regards -- Tomas Vondra EnterpriseDB: http://www.enterprisedb.com The Enterprise PostgreSQL Company
Re: SQL Property Graph Queries (SQL/PGQ)
On Fri, Feb 23, 2024 at 11:08 PM Tomas Vondra wrote: > > On 2/23/24 17:15, Peter Eisentraut wrote: > > On 16.02.24 20:23, Andres Freund wrote: > >> One aspect that I m concerned with structurally is that the > >> transformation, > >> from property graph queries to something postgres understands, is done > >> via the > >> rewrite system. I doubt that that is a good idea. For one it bars the > >> planner > >> from making plans that benefit from the graph query formulation. But more > >> importantly, we IMO should reduce usage of the rewrite system, not > >> increase > >> it. > > > > PGQ is meant to be implemented like that, like views expanding to joins > > and unions. This is what I have gathered during the specification > > process, and from other implementations, and from academics. There are > > certainly other ways to combine relational and graph database stuff, > > like with native graph storage and specialized execution support, but > > this is not that, and to some extent PGQ was created to supplant those > > other approaches. > > > > I understand PGQ was meant to be implemented as a bit of a "syntactic > sugar" on top of relations, instead of inventing some completely new > ways to store/query graph data. > > But does that really mean it needs to be translated to relations this > early / in rewriter? I haven't thought about it very deeply, but won't > that discard useful information about semantics of the query, which > might be useful when planning/executing the query? > > I've somehow imagined we'd be able to invent some new index types, or > utilize some other type of auxiliary structure, maybe some special > executor node, but it seems harder without this extra info ... I am yet to look at the implementation but ... 1. If there are optimizations that improve performance of some path patterns, they are likely to improve the performance of joins used to implement those. In such cases, loosing some information might be ok. 2. Explicit graph annotatiion might help to automate some things like creating indexes automatically on columns that appear in specific patterns OR create extended statistics automatically on the columns participating in specific patterns. OR interpreting statistics/costing in differently than normal query execution. Those kind of things will require retaining annotations in views, planner/execution trees etc. 3. There are some things like aggregates/operations on paths which might require stuff like new execution nodes. But I am not sure we have reached that stage yet. There might be things we may not see right now in the standard e.g. indexes on graph properties. For those mapping the graph objects unto database objects might prove useful. That goes back to Peter's comment --- quote As long as the view expansion takes place there, it makes sense to align with that. For example, all the view security stuff (privileges, security barriers, etc.) will eventually need to be considered, and it would make sense to do that in a consistent way. --- unquote -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
--
Re: SQL Property Graph Queries (SQL/PGQ)
Here is a new version of this patch. I have been working together with Ashutosh on this. While the version 0 was more of a fragile demo, this version 1 has a fairly complete minimal feature set and should be useful for playing around with. We do have a long list of various internal bits that still need to be fixed or revised or looked at again, so there is by no means a claim that everything is completed. Documentation to get started is included (ddl.sgml and queries.sgml). (Of course, feedback on the getting-started documentation would be most welcome.)
Re: SQL Property Graph Queries (SQL/PGQ)
In the ddl.sgml, I’d swap the first two paragraphs. I find the first one a bit confusing as-is. As far as I can tell, it’s an implementation detail. The first paragraph should answer, “I have some data modeled as a graph G=(V, E). Can Postgres help me?”. Then, introducing property graphs makes more sense. I'd also use the examples and fake data in `graph_table.sql` in ddl/queries.sgml). I was bummed that that copy-pasting didn't work as is. I’d keep explaining how a graph query translates to a relational one later in the page. As for the implementation, I can’t have an opinion yet, but for those not familiar, Apache Age uses a slightly different approach that mimics jsonpath (parses a sublanguage expression into an internal execution engine etc.). However, the standard requires mapping this to the relational model, which makes sense for core Postgres. > On 27 Jun 2024, at 3:31 PM, Peter Eisentraut wrote: > > Here is a new version of this patch. I have been working together with Ashutosh on this. While the version 0 was more of a fragile demo, this version 1 has a fairly complete minimal feature set and should be useful for playing around with. We do have a long list of various internal bits that still need to be fixed or revised or looked at again, so there is by no means a claim that everything is completed. > > Documentation to get started is included (ddl.sgml and queries.sgml). (Of course, feedback on the getting-started documentation would be most welcome.) >
Re: SQL Property Graph Queries (SQL/PGQ)
Here is a new version of this patch. I have been working together with
Ashutosh on this. While the version 0 was more of a fragile demo, this
version 1 has a fairly complete minimal feature set and should be useful
for playing around with. We do have a long list of various internal
bits that still need to be fixed or revised or looked at again, so there
is by no means a claim that everything is completed.
Re: SQL Property Graph Queries (SQL/PGQ)
On Mon, Jul 8, 2024 at 7:07 PM Ashutosh Bapat wrote: > > > > On Thu, Jun 27, 2024 at 6:01 PM Peter Eisentraut wrote: >> >> Here is a new version of this patch. I have been working together with >> Ashutosh on this. While the version 0 was more of a fragile demo, this >> version 1 has a fairly complete minimal feature set and should be useful >> for playing around with. We do have a long list of various internal >> bits that still need to be fixed or revised or looked at again, so there >> is by no means a claim that everything is completed. > > > PFA the patchset fixing compilation error reported by CI bot. > 0001 - same as previous one > 0002 - fixes compilation error > 0003 - adds support for WHERE clause in graph pattern missing in the first patch. > There's a test failure reported by CI. Property graph related tests are failing when regression is run from perl tests. The failure is reported only on Free BSD. I have added one patch in the series which will help narrow the failure. The patch changes the code to report the location of an error reported when handling implicit properties or labels. 0001 - same as previous one 0002 - fixes pgperltidy complaints 0003 - fixes compilation failure 0004 - same as 0003 in previous set 0005 - patch to report parse location of error -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Wed, Jul 17, 2024 at 11:04 AM Ashutosh Bapat wrote: > > On Mon, Jul 8, 2024 at 7:07 PM Ashutosh Bapat > wrote: > > > > > > > > On Thu, Jun 27, 2024 at 6:01 PM Peter Eisentraut wrote: > >> > >> Here is a new version of this patch. I have been working together with > >> Ashutosh on this. While the version 0 was more of a fragile demo, this > >> version 1 has a fairly complete minimal feature set and should be useful > >> for playing around with. We do have a long list of various internal > >> bits that still need to be fixed or revised or looked at again, so there > >> is by no means a claim that everything is completed. > > > > > > PFA the patchset fixing compilation error reported by CI bot. > > 0001 - same as previous one > > 0002 - fixes compilation error > > 0003 - adds support for WHERE clause in graph pattern missing in the first patch. > > > > There's a test failure reported by CI. Property graph related tests > are failing when regression is run from perl tests. The failure is > reported only on Free BSD. I thought it's related to FreeBSD but the bug could be observed anywhere with -DRELCACHE_FORCE_RELEASE. It's also reported indirectly by valgrind. When infering properties of an element from the underlying table's attributes, the attribute name pointed to the memory in the heap tuple of pg_attribute row. Thus when the tuple was released, it pointed to a garbage instead of actual column name resulting in column not found error. Attached set of patches with an additional patch to fix the bug. 0001 - same as previous one 0002 - fixes pgperltidy complaints 0003 - fixes compilation failure 0004 - fixes issue seen on CI 0005 - adds support for WHERE clause in graph pattern missing in the first patch. Once reviewed, patches 0002 to 0005 should be merged into 0001. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Hi I am attaching a new patch for a minor feature addition. - Adding support for 'Labels and properties: EXCEPT list' Please let me know if something is missing. Thanks and Regards Imran Zaheer On Mon, Jul 22, 2024 at 9:02 PM Ashutosh Bapat wrote: > > On Wed, Jul 17, 2024 at 11:04 AM Ashutosh Bapat > wrote: > > > > On Mon, Jul 8, 2024 at 7:07 PM Ashutosh Bapat > > wrote: > > > > > > > > > > > > On Thu, Jun 27, 2024 at 6:01 PM Peter Eisentraut wrote: > > >> > > >> Here is a new version of this patch. I have been working together with > > >> Ashutosh on this. While the version 0 was more of a fragile demo, this > > >> version 1 has a fairly complete minimal feature set and should be useful > > >> for playing around with. We do have a long list of various internal > > >> bits that still need to be fixed or revised or looked at again, so there > > >> is by no means a claim that everything is completed. > > > > > > > > > PFA the patchset fixing compilation error reported by CI bot. > > > 0001 - same as previous one > > > 0002 - fixes compilation error > > > 0003 - adds support for WHERE clause in graph pattern missing in the first patch. > > > > > > > There's a test failure reported by CI. Property graph related tests > > are failing when regression is run from perl tests. The failure is > > reported only on Free BSD. > > I thought it's related to FreeBSD but the bug could be observed > anywhere with -DRELCACHE_FORCE_RELEASE. It's also reported indirectly > by valgrind. > > When infering properties of an element from the underlying table's > attributes, the attribute name pointed to the memory in the heap tuple > of pg_attribute row. Thus when the tuple was released, it pointed to a > garbage instead of actual column name resulting in column not found > error. > > Attached set of patches with an additional patch to fix the bug. > > 0001 - same as previous one > 0002 - fixes pgperltidy complaints > 0003 - fixes compilation failure > 0004 - fixes issue seen on CI > 0005 - adds support for WHERE clause in graph pattern missing in the > first patch. > > Once reviewed, patches 0002 to 0005 should be merged into 0001. > > -- > Best Wishes, > Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Mon, Jul 22, 2024 at 5:31 PM Ashutosh Bapat wrote: > I found that the patches do not support cyclic paths correctly. A cyclic path pattern is a path patterns where an element pattern variable repeats e.g. (a)->(b)->(a). In such a path pattern the element patterns with the same variable indicate the same element in the path. In the given example (a) specifies that the path should start and end with the same vertex. Patch 0006 supports cyclic path patterns. Elements which share the variable name should have the same element type. The element patterns sharing the same variable name should have same label expression. They may be constrained by different conditions which are finally ANDed since they all represent the same element. The patch creates a separate abstraction "path_factor" which combines all the GraphElementPatterns into one element pattern. SQL/PGQ standard uses path_factor for such an entity, so I chose that as the structure name. But suggestions are welcome. A path_factor is further expanded into a list of path_element objects each representing a vertex or edge table that satisfies the label expression in GraphElementPattern. In the previous patch set, the consecutive elements were considered to be connected to each other. Cyclic paths change that. For example, in path pattern (a)->(b)->(a), (b) is connected to the first element on both sides (forming a cycle) instead of first and third element. Patch 0006 has code changes to appropriately link the elements. As a side effect, I have eliminated the confusion between variables with name gep and gpe. While it's easy to imagine a repeated vertex pattern, a repeated edge pattern is slightly complex. An edge connects only two vertices, and thus a repeated edge pattern constrains the adjacent vertex patterns even if they have different variable names. Such patterns are not supported. E.g. (a)-[b]->(c)-[b]->(d) would mean that (d) and (a) represent the same vertex even if the variable names are different. Such patterns are not supported for now. But (a)-[b]->(a)-[b]->(a) OR (a)-[b]->(c)<-[b]-(a) are supported since the vertices adjacent to repeated edges are constrained by the variable name anyway. The patch also changes many foreach() to use foreach_* macros as appropriate. > 0001 - same as previous one > 0002 - fixes pgperltidy complaints > 0003 - fixes compilation failure > 0004 - fixes issue seen on CI > 0005 - adds support for WHERE clause in graph pattern missing in the > first patch. 0006 - adds full support for cyclic path patterns Once reviewed, patches 0002 to 0006 should be merged into 0001. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Imran, On Sun, Aug 4, 2024 at 12:32 PM Imran Zaheer wrote: > > Hi > I am attaching a new patch for a minor feature addition. > > - Adding support for 'Labels and properties: EXCEPT list' Do you intend to support EXCEPT in the label expression as well or just properties? > > Please let me know if something is missing. I think the code changes are in the right place. I didn't review the patch thoroughly. But here are some comments and some advice. Please do not top-post on hackers. Always sent the whole patchset. Otherwise, CI bot gets confused. It doesn't pick up patchset from the previous emails. About the functionality: It's not clear to me whether an EXCEPT should be applicable only at the time of property graph creation or it should be applicable always. I.e. when a property graph is dumped, should it have EXCEPT in it or have a list of columns surviving except list? What if a column in except list is dropped after creating a property graph? Some comments on the code 1. You could use list_member() in insert_property_records() to check whether a given column is in the list of exceptions after you have enveloped in String node. 2. The SELECT with GRAPH_TABLE queries are tested in graph_table.sql. We don't include those in create_property_graph.sql 3. Instead of creating a new property graph in the test, you may modify one of the existing property graphs to have a label with except list and then query it. We are aiming a minimal set of features in the first version. I will let Peter E. decide whether to consider this as minimal set feature or not. The feature looks useful to me. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Ashutosh, Thanks for the feedback. > Do you intend to support EXCEPT in the label expression as well or > just properties? > I only implemented it for the properties because I couldn't find any example for Label expression using EXCEPT clause. So I thought it was only meant to be for the properties. But if you can confirm that we do use EXCEPT clauses with label expressions as well then I can try supporting that too. > > Please do not top-post on hackers. > > Always sent the whole patchset. Otherwise, CI bot gets confused. It > doesn't pick up patchset from the previous emails. > Okay, I will take care of that. > About the functionality: It's not clear to me whether an EXCEPT should > be applicable only at the time of property graph creation or it should > be applicable always. I.e. when a property graph is dumped, should it > have EXCEPT in it or have a list of columns surviving except list? > What if a column in except list is dropped after creating a property > graph? > I did some testing on that, for now we are just dumping the columns surviving the except list. If an exceptional table column is deleted afterwards it doesn't show any effect on the graph. I also tested this scenario with duckdb pgq extension [1], deleting the col doesn't affect the graph. > Some comments on the code I am attaching a new patch after trying to fix according to you comments > 1. You could use list_member() in insert_property_records() to check > whether a given column is in the list of exceptions after you have > enveloped in String node. * I have changed to code to use list_member(), but I have to make ResTarget->name from `pstrdup(NameStr(att->attname));` to `NULL` We are using `xml_attribute_list` for our columns list and while making this list in gram.y we are assigning `rt->name` as NULL [2], this causes list_member() func to fail while comparing except_list nodes. That's why I am changing rt->name from string value to NULL in propgraphcmds.c in this patch. * Also, in order to use list_member() func I have to add a separate for loop to iterate through the exceptional columns to generate the error message if col is not valid. My question is, is it ok to use two separate for loops (one to check except cols validity & other(list_memeber) to check existence of scanned col in except list). In the previous patch I was using single for loop to validate both things. > 2. The SELECT with GRAPH_TABLE queries are tested in graph_table.sql. > We don't include those in create_property_graph.sql * I have moved the graph_table queries from create_property_graph.sql to graph_table.sql. * But in graph_table.sql I didn't use the existing graphs because those graphs and tables look like there for some specific test scenario, so I created my separate graph and table for my test scenario. I didn't drop the graph and the table as we will be dropping the schema at the end but Peter E has this comment "-- leave for pg_upgrade/pg_dump tests". > 3. Instead of creating a new property graph in the test, you may > modify one of the existing property graphs to have a label with except > list and then query it. > * I have modified the graphs in create_property_graph.sql in order to test except list cols in the alter command and create graph command. > We are aiming a minimal set of features in the first version. I will > let Peter E. decide whether to consider this as minimal set feature or > not. The feature looks useful to me. Thanks if you find this patch useful. I am attaching the modified patch. > 0001 - same as previous one > 0002 - fixes pgperltidy complaints > 0003 - fixes compilation failure > 0004 - fixes issue seen on CI > 0005 - adds support for WHERE clause in graph pattern missing in the > first patch. > 0006 - adds full support for cyclic path patterns 0007 - adds support for except cols list in graph properties Thanks Imran Zaheer [1]: https://github.com/cwida/duckpgq-extension [2]: https://github.com/postgres/postgres/blob/f5a1311fccd2ed24a9fb42aa47a17d1df7126039/src/backend/parser/gram.y#L16166
Re: SQL Property Graph Queries (SQL/PGQ)
Hello, With the attached patch found below error when try to use "Any directed edge" syntax. postgres=# SELECT * FROM GRAPH_TABLE (students_graph postgres(# MATCH postgres(# (a IS person ) - [] - (b IS person) postgres(# COLUMNS (a.name AS person_a, b.name AS person_b) postgres(# ); ERROR: unsupported element pattern kind: undirected edge If this syntax is supported then should behave as below, PERSON_A PERSON_B ---------- ---------- Bob John John Mary Alice Mary Mary Bob Mary John Bob Mary John Bob Mary Alice 8 rows selected. Attaching the sql file for reference. Thanks Ajay On Sat, Aug 10, 2024 at 2:52 PM Imran Zaheer wrote: > > Hi Ashutosh, > > Thanks for the feedback. > > > Do you intend to support EXCEPT in the label expression as well or > > just properties? > > > > I only implemented it for the properties because I couldn't find any > example for Label expression using EXCEPT clause. So I thought it was > only meant to be for the properties. > But if you can confirm that we do use EXCEPT clauses with label > expressions as well then I can try supporting that too. > > > > > Please do not top-post on hackers. > > > > Always sent the whole patchset. Otherwise, CI bot gets confused. It > > doesn't pick up patchset from the previous emails. > > > Okay, I will take care of that. > > > About the functionality: It's not clear to me whether an EXCEPT should > > be applicable only at the time of property graph creation or it should > > be applicable always. I.e. when a property graph is dumped, should it > > have EXCEPT in it or have a list of columns surviving except list? > > What if a column in except list is dropped after creating a property > > graph? > > > > I did some testing on that, for now we are just dumping the columns > surviving the except list. > If an exceptional table column is deleted afterwards it doesn't show > any effect on the graph. I also tested this scenario with duckdb pgq > extension [1], deleting the col doesn't affect the graph. > > > Some comments on the code > > I am attaching a new patch after trying to fix according to you comments > > > 1. You could use list_member() in insert_property_records() to check > > whether a given column is in the list of exceptions after you have > > enveloped in String node. > > * I have changed to code to use list_member(), but I have to make > ResTarget->name from `pstrdup(NameStr(att->attname));` to `NULL` > We are using `xml_attribute_list` for our columns list and while > making this list in gram.y we are assigning `rt->name` as NULL [2], > this causes list_member() func to fail while comparing except_list > nodes. That's why I am changing rt->name from string value to NULL in > propgraphcmds.c in this patch. > > * Also, in order to use list_member() func I have to add a separate > for loop to iterate through the exceptional columns to generate the > error message if col is not valid. My question is, is it ok to use two > separate for loops (one to check except cols validity & > other(list_memeber) to check existence of scanned col in except list). > In the previous patch I was using single for loop to validate both > things. > > > 2. The SELECT with GRAPH_TABLE queries are tested in graph_table.sql. > > We don't include those in create_property_graph.sql > > * I have moved the graph_table queries from create_property_graph.sql > to graph_table.sql. > * But in graph_table.sql I didn't use the existing graphs because > those graphs and tables look like there for some specific test > scenario, so I created my separate graph and table for my test > scenario. I didn't drop the graph and the table as we will be dropping > the schema at the end but Peter E has this comment "-- leave for > pg_upgrade/pg_dump tests". > > > 3. Instead of creating a new property graph in the test, you may > > modify one of the existing property graphs to have a label with except > > list and then query it. > > > > * I have modified the graphs in create_property_graph.sql in order to > test except list cols in the alter command and create graph command. > > > We are aiming a minimal set of features in the first version. I will > > let Peter E. decide whether to consider this as minimal set feature or > > not. The feature looks useful to me. > > Thanks if you find this patch useful. I am attaching the modified patch. > > > 0001 - same as previous one > > 0002 - fixes pgperltidy complaints > > 0003 - fixes compilation failure > > 0004 - fixes issue seen on CI > > 0005 - adds support for WHERE clause in graph pattern missing in the > > first patch. > > 0006 - adds full support for cyclic path patterns > > 0007 - adds support for except cols list in graph properties > > Thanks > Imran Zaheer > > [1]: https://github.com/cwida/duckpgq-extension > [2]: https://github.com/postgres/postgres/blob/f5a1311fccd2ed24a9fb42aa47a17d1df7126039/src/backend/parser/gram.y#L16166
Re: SQL Property Graph Queries (SQL/PGQ)
Hello, Further testing found that using a property graph with the plpgsql function crashed the server. Please take a look at the attached SQL file for reference tables. postgres=# create or replace function func() returns int as postgres-# $$ postgres$# declare person_av varchar; postgres$# begin postgres$# postgres$# SELECT person_a into person_av FROM GRAPH_TABLE (students_graph postgres$# MATCH postgres$# (a IS person) -[e IS friends]-> (b IS person WHERE b.name = 'Bob') postgres$# WHERE a.name='John' postgres$# COLUMNS (a.name AS person_a, b.name AS person_b) postgres$# ); postgres$# postgres$# return person_av; postgres$# end postgres$# $$ language plpgsql; CREATE FUNCTION postgres=# select func(); server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. The connection to the server was lost. Attempting reset: Failed. The connection to the server was lost. Attempting reset: Failed. !?> Please let me know if you need more details. Thanks Ajay On Tue, Aug 13, 2024 at 3:22 PM Ajay Pal wrote: > > Hello, > > With the attached patch found below error when try to use "Any > directed edge" syntax. > > postgres=# SELECT * FROM GRAPH_TABLE (students_graph > postgres(# MATCH > postgres(# (a IS person ) - [] - (b IS person) > postgres(# COLUMNS (a.name AS person_a, b.name AS person_b) > postgres(# ); > ERROR: unsupported element pattern kind: undirected edge > > If this syntax is supported then should behave as below, > > PERSON_A PERSON_B > ---------- ---------- > Bob John > John Mary > Alice Mary > Mary Bob > Mary John > Bob Mary > John Bob > Mary Alice > > 8 rows selected. > > Attaching the sql file for reference. > > Thanks > Ajay > > On Sat, Aug 10, 2024 at 2:52 PM Imran Zaheer wrote: > > > > Hi Ashutosh, > > > > Thanks for the feedback. > > > > > Do you intend to support EXCEPT in the label expression as well or > > > just properties? > > > > > > > I only implemented it for the properties because I couldn't find any > > example for Label expression using EXCEPT clause. So I thought it was > > only meant to be for the properties. > > But if you can confirm that we do use EXCEPT clauses with label > > expressions as well then I can try supporting that too. > > > > > > > > Please do not top-post on hackers. > > > > > > Always sent the whole patchset. Otherwise, CI bot gets confused. It > > > doesn't pick up patchset from the previous emails. > > > > > Okay, I will take care of that. > > > > > About the functionality: It's not clear to me whether an EXCEPT should > > > be applicable only at the time of property graph creation or it should > > > be applicable always. I.e. when a property graph is dumped, should it > > > have EXCEPT in it or have a list of columns surviving except list? > > > What if a column in except list is dropped after creating a property > > > graph? > > > > > > > I did some testing on that, for now we are just dumping the columns > > surviving the except list. > > If an exceptional table column is deleted afterwards it doesn't show > > any effect on the graph. I also tested this scenario with duckdb pgq > > extension [1], deleting the col doesn't affect the graph. > > > > > Some comments on the code > > > > I am attaching a new patch after trying to fix according to you comments > > > > > 1. You could use list_member() in insert_property_records() to check > > > whether a given column is in the list of exceptions after you have > > > enveloped in String node. > > > > * I have changed to code to use list_member(), but I have to make > > ResTarget->name from `pstrdup(NameStr(att->attname));` to `NULL` > > We are using `xml_attribute_list` for our columns list and while > > making this list in gram.y we are assigning `rt->name` as NULL [2], > > this causes list_member() func to fail while comparing except_list > > nodes. That's why I am changing rt->name from string value to NULL in > > propgraphcmds.c in this patch. > > > > * Also, in order to use list_member() func I have to add a separate > > for loop to iterate through the exceptional columns to generate the > > error message if col is not valid. My question is, is it ok to use two > > separate for loops (one to check except cols validity & > > other(list_memeber) to check existence of scanned col in except list). > > In the previous patch I was using single for loop to validate both > > things. > > > > > 2. The SELECT with GRAPH_TABLE queries are tested in graph_table.sql. > > > We don't include those in create_property_graph.sql > > > > * I have moved the graph_table queries from create_property_graph.sql > > to graph_table.sql. > > * But in graph_table.sql I didn't use the existing graphs because > > those graphs and tables look like there for some specific test > > scenario, so I created my separate graph and table for my test > > scenario. I didn't drop the graph and the table as we will be dropping > > the schema at the end but Peter E has this comment "-- leave for > > pg_upgrade/pg_dump tests". > > > > > 3. Instead of creating a new property graph in the test, you may > > > modify one of the existing property graphs to have a label with except > > > list and then query it. > > > > > > > * I have modified the graphs in create_property_graph.sql in order to > > test except list cols in the alter command and create graph command. > > > > > We are aiming a minimal set of features in the first version. I will > > > let Peter E. decide whether to consider this as minimal set feature or > > > not. The feature looks useful to me. > > > > Thanks if you find this patch useful. I am attaching the modified patch. > > > > > 0001 - same as previous one > > > 0002 - fixes pgperltidy complaints > > > 0003 - fixes compilation failure > > > 0004 - fixes issue seen on CI > > > 0005 - adds support for WHERE clause in graph pattern missing in the > > > first patch. > > > 0006 - adds full support for cyclic path patterns > > > > 0007 - adds support for except cols list in graph properties > > > > Thanks > > Imran Zaheer > > > > [1]: https://github.com/cwida/duckpgq-extension > > [2]: https://github.com/postgres/postgres/blob/f5a1311fccd2ed24a9fb42aa47a17d1df7126039/src/backend/parser/gram.y#L16166
Re: SQL Property Graph Queries (SQL/PGQ)
Hi All,
When we use a graph table and any local table, the server crashes.
Please note, It is happening when using the where clause for the local
table only.
postgres=# SELECT * FROM customers a, GRAPH_TABLE (myshop2 MATCH (c IS
customers WHERE c.address = 'US')-[IS customer_orders]->(o IS orders)
COLUMNS (c.name_redacted AS customer_name_redacted));
customer_id | name | address | customer_name_redacted
-------------+-----------+---------+------------------------
1 | customer1 | US | redacted1
2 | customer2 | CA | redacted1
3 | customer3 | GL | redacted1
(3 rows)
postgres=# SELECT * FROM customers a, GRAPH_TABLE (myshop2 MATCH (c IS
customers WHERE c.address = 'US')-[IS customer_orders]->(o IS orders)
COLUMNS (c.name_redacted AS customer_name_redacted)) where
a.customer_id=1;
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
The connection to the server was lost. Attempting reset: Failed.
The connection to the server was lost. Attempting reset: Failed.
!?> \q
Note:- I have referred to graph_table.sql to get the table structure
used in the above query.
Thanks
Ajay
On Tue, Aug 13, 2024 at 4:08 PM Ajay Pal wrote:
>
> Hello,
>
> Further testing found that using a property graph with the plpgsql
> function crashed the server. Please take a look at the attached SQL
> file for reference tables.
>
> postgres=# create or replace function func() returns int as
> postgres-# $$
> postgres$# declare person_av varchar;
> postgres$# begin
> postgres$#
> postgres$# SELECT person_a into person_av FROM GRAPH_TABLE
> (students_graph
> postgres$# MATCH
> postgres$# (a IS person) -[e IS friends]-> (b IS person
> WHERE b.name = 'Bob')
> postgres$# WHERE a.name='John'
> postgres$# COLUMNS (a.name AS person_a, b.name AS person_b)
> postgres$# );
> postgres$#
> postgres$# return person_av;
> postgres$# end
> postgres$# $$ language plpgsql;
> CREATE FUNCTION
> postgres=# select func();
> server closed the connection unexpectedly
> This probably means the server terminated abnormally
> before or while processing the request.
> The connection to the server was lost. Attempting reset: Failed.
> The connection to the server was lost. Attempting reset: Failed.
> !?>
>
> Please let me know if you need more details.
>
> Thanks
> Ajay
>
> On Tue, Aug 13, 2024 at 3:22 PM Ajay Pal wrote:
> >
> > Hello,
> >
> > With the attached patch found below error when try to use "Any
> > directed edge" syntax.
> >
> > postgres=# SELECT * FROM GRAPH_TABLE (students_graph
> > postgres(# MATCH
> > postgres(# (a IS person ) - [] - (b IS person)
> > postgres(# COLUMNS (a.name AS person_a, b.name AS person_b)
> > postgres(# );
> > ERROR: unsupported element pattern kind: undirected edge
> >
> > If this syntax is supported then should behave as below,
> >
> > PERSON_A PERSON_B
> > ---------- ----------
> > Bob John
> > John Mary
> > Alice Mary
> > Mary Bob
> > Mary John
> > Bob Mary
> > John Bob
> > Mary Alice
> >
> > 8 rows selected.
> >
> > Attaching the sql file for reference.
> >
> > Thanks
> > Ajay
> >
> > On Sat, Aug 10, 2024 at 2:52 PM Imran Zaheer wrote:
> > >
> > > Hi Ashutosh,
> > >
> > > Thanks for the feedback.
> > >
> > > > Do you intend to support EXCEPT in the label expression as well or
> > > > just properties?
> > > >
> > >
> > > I only implemented it for the properties because I couldn't find any
> > > example for Label expression using EXCEPT clause. So I thought it was
> > > only meant to be for the properties.
> > > But if you can confirm that we do use EXCEPT clauses with label
> > > expressions as well then I can try supporting that too.
> > >
> > > >
> > > > Please do not top-post on hackers.
> > > >
> > > > Always sent the whole patchset. Otherwise, CI bot gets confused. It
> > > > doesn't pick up patchset from the previous emails.
> > > >
> > > Okay, I will take care of that.
> > >
> > > > About the functionality: It's not clear to me whether an EXCEPT should
> > > > be applicable only at the time of property graph creation or it should
> > > > be applicable always. I.e. when a property graph is dumped, should it
> > > > have EXCEPT in it or have a list of columns surviving except list?
> > > > What if a column in except list is dropped after creating a property
> > > > graph?
> > > >
> > >
> > > I did some testing on that, for now we are just dumping the columns
> > > surviving the except list.
> > > If an exceptional table column is deleted afterwards it doesn't show
> > > any effect on the graph. I also tested this scenario with duckdb pgq
> > > extension [1], deleting the col doesn't affect the graph.
> > >
> > > > Some comments on the code
> > >
> > > I am attaching a new patch after trying to fix according to you comments
> > >
> > > > 1. You could use list_member() in insert_property_records() to check
> > > > whether a given column is in the list of exceptions after you have
> > > > enveloped in String node.
> > >
> > > * I have changed to code to use list_member(), but I have to make
> > > ResTarget->name from `pstrdup(NameStr(att->attname));` to `NULL`
> > > We are using `xml_attribute_list` for our columns list and while
> > > making this list in gram.y we are assigning `rt->name` as NULL [2],
> > > this causes list_member() func to fail while comparing except_list
> > > nodes. That's why I am changing rt->name from string value to NULL in
> > > propgraphcmds.c in this patch.
> > >
> > > * Also, in order to use list_member() func I have to add a separate
> > > for loop to iterate through the exceptional columns to generate the
> > > error message if col is not valid. My question is, is it ok to use two
> > > separate for loops (one to check except cols validity &
> > > other(list_memeber) to check existence of scanned col in except list).
> > > In the previous patch I was using single for loop to validate both
> > > things.
> > >
> > > > 2. The SELECT with GRAPH_TABLE queries are tested in graph_table.sql.
> > > > We don't include those in create_property_graph.sql
> > >
> > > * I have moved the graph_table queries from create_property_graph.sql
> > > to graph_table.sql.
> > > * But in graph_table.sql I didn't use the existing graphs because
> > > those graphs and tables look like there for some specific test
> > > scenario, so I created my separate graph and table for my test
> > > scenario. I didn't drop the graph and the table as we will be dropping
> > > the schema at the end but Peter E has this comment "-- leave for
> > > pg_upgrade/pg_dump tests".
> > >
> > > > 3. Instead of creating a new property graph in the test, you may
> > > > modify one of the existing property graphs to have a label with except
> > > > list and then query it.
> > > >
> > >
> > > * I have modified the graphs in create_property_graph.sql in order to
> > > test except list cols in the alter command and create graph command.
> > >
> > > > We are aiming a minimal set of features in the first version. I will
> > > > let Peter E. decide whether to consider this as minimal set feature or
> > > > not. The feature looks useful to me.
> > >
> > > Thanks if you find this patch useful. I am attaching the modified patch.
> > >
> > > > 0001 - same as previous one
> > > > 0002 - fixes pgperltidy complaints
> > > > 0003 - fixes compilation failure
> > > > 0004 - fixes issue seen on CI
> > > > 0005 - adds support for WHERE clause in graph pattern missing in the
> > > > first patch.
> > > > 0006 - adds full support for cyclic path patterns
> > >
> > > 0007 - adds support for except cols list in graph properties
> > >
> > > Thanks
> > > Imran Zaheer
> > >
> > > [1]: https://github.com/cwida/duckpgq-extension
> > > [2]: https://github.com/postgres/postgres/blob/f5a1311fccd2ed24a9fb42aa47a17d1df7126039/src/backend/parser/gram.y#L16166
Re: SQL Property Graph Queries (SQL/PGQ)
On Wed, Aug 28, 2024 at 3:48 PM Ashutosh Bapat <ashutosh.bapat.oss@gmail.com> wrote:Patches 0001 - 0006 are same as the previous set. 0007 - fixes all the problems you reported till now and also the one I found. The commit message describes the fixes in detail.Here's an updated patchset based on the latest HEAD.
I have been looking at this patchset from a user's and standards' perspective and I am quite pleased with what I am seeing for the most part. I have not been looking much at the code itself, although I do plan on reviewing some of the code in the future.
There are a few things that stick out to me.
1.
I don't see any way to view the structure of of a property graph. For example:
postgres=# CREATE TABLE objects (id INTEGER, color VARCHAR, shape VARCHAR, size INTEGER);
CREATE TABLE
postgres=# CREATE PROPERTY GRAPH propgraph VERTEX TABLES (objects KEY (id) PROPERTIES ALL COLUMNS);
CREATE PROPERTY GRAPH
postgres=# \dG propgraph
List of relations
Schema | Name | Type | Owner
-------------------+-----------+----------------+-------------
graph_table_tests | propgraph | property graph | vik.fearing
(1 row)
postgres=# \d propgraph
Property graph "graph_table_tests.propgraph"
Column | Type
--------+------
I don't really know what to do with that.
2.
There is a missing newline in the \? help of psql.
HELP0(" \\dFt[+] [PATTERN] list text search templates\n");
HELP0(" \\dg[S+] [PATTERN] list roles\n");
HELP0(" \\dG[S+] [PATTERN] list property graphs"); <---
HELP0(" \\di[S+] [PATTERN] list indexes\n");
HELP0(" \\dl[+] list large objects, same as \\lo_list\n");
3.
The noise word "ARE" is missing from the <element table properties alternatives> clause.
There is also no support for the EXCEPT clause, but I imagine that can be added at a later time.
4.
I notice that tables in pg_catalog are not allowed in a property graph. What are the reasons for this? It is true that this might cause some problems with upgrades if a column is removed, but it shouldn't cause trouble for columns being added. That case works with user tables.
5.
The ascii art characters (I am loathe to call them operators) allow junk in between them. For example:
MATCH (c) -[:lbl]-> (d)
can be written as
MATCH (c) -
[:lbl] -
/* a comment here */
> (d)
Is that intentional?
----
I will continue to review this feature from the user's perspective. Thank you for working on it, I am very excited to get this in.
--
Vik Fearing
Re: SQL Property Graph Queries (SQL/PGQ)
On Fri, Nov 22, 2024 at 7:29 PM Ashutosh Bapat
wrote:
>
> On Tue, Nov 19, 2024 at 10:08 PM Vik Fearing wrote:
> >
> >
> > On 05/11/2024 16:41, Ashutosh Bapat wrote:
> >
> > On Wed, Aug 28, 2024 at 3:48 PM Ashutosh Bapat
> > wrote:
> >
> > Patches 0001 - 0006 are same as the previous set.
> > 0007 - fixes all the problems you reported till now and also the one I
> > found. The commit message describes the fixes in detail.
> >
> > Here's an updated patchset based on the latest HEAD.
> >
> >
> >
> > I have been looking at this patchset from a user's and standards' perspective and I am quite pleased with what I am seeing for the most part. I have not been looking much at the code itself, although I do plan on reviewing some of the code in the future.
>
> Thanks for looking at the patches.
>
> >
> >
> > There are a few things that stick out to me.
> >
> >
> > 1.
> > I don't see any way to view the structure of of a property graph. For example:
> >
> >
> > postgres=# CREATE TABLE objects (id INTEGER, color VARCHAR, shape VARCHAR, size INTEGER);
> > CREATE TABLE
> > postgres=# CREATE PROPERTY GRAPH propgraph VERTEX TABLES (objects KEY (id) PROPERTIES ALL COLUMNS);
> > CREATE PROPERTY GRAPH
> > postgres=# \dG propgraph
> > List of relations
> > Schema | Name | Type | Owner
> > -------------------+-----------+----------------+-------------
> > graph_table_tests | propgraph | property graph | vik.fearing
> > (1 row)
> >
> > postgres=# \d propgraph
> > Property graph "graph_table_tests.propgraph"
> > Column | Type
> > --------+------
> >
> > I don't really know what to do with that.
>
> Yes. It is on my TODO list. IMO we should just print the first line
> property graph "...". There are no predefined columns in this
> relation. And somehow redirect them to use \dG instead.
\d+ propgraph prints the definition of property graph. I find \dG
similar to \di which doesn't print the structure of an index. Instead
\d+ prints it.
In the attached patch series I have added patch 0008 to remove
unnecessary header
> > Column | Type
> > --------+------
It still prints an extra line but I haven't found a way to eliminate
it. Hence 0008 is WIP. I have listed TODOs in the commit message of
that patch.
> >
> >
> > 2.
> > There is a missing newline in the \? help of psql.
> > HELP0(" \\dFt[+] [PATTERN] list text search templates\n");
> > HELP0(" \\dg[S+] [PATTERN] list roles\n");
> > HELP0(" \\dG[S+] [PATTERN] list property graphs"); <---
> > HELP0(" \\di[S+] [PATTERN] list indexes\n");
> > HELP0(" \\dl[+] list large objects, same as \\lo_list\n");
> >
>
> Will fix that in the next set.
Done. The fix is part of 0001 now.
>
> >
> > I will continue to review this feature from the user's perspective. Thank you for working on it, I am very excited to get this in.
>
here's patchset rebased on 792b2c7e6d926e61e8ff3b33d3e22d7d74e7a437
with conflicts in rowsecurity.sql/out fixed.
>
> 0001 - 0005 are the same as the previous set.
> 0007 - has RLS tests. It is the same as 0006 from the previous patch set.
This is same as the previous patchset.
>
> 0006 - is new addressing collation and edge-vertex link qual creation.
> This patch adds code to store collation and typmod to
> pg_propgraph_property catalog and propagate it to property graph
> references in GRAPH_TABLE. Collation is used by
> assign_query_collations and assign_expr_collations to propagate
> collation up the query and expression tree respectively. typmod is
> used to report typmod of property reference from exprTypemod().
>
> While finishing code to create vertex-edge link quals, I found that we
> need to find and store the operator to be used for key matching in
> those quals. I think we have to do something similar to what primary
> key handling code does - find the equality operator when creating edge
> descriptor and store it in pg_propgraph_element. I am not sure whether
> we should add a dependency on the operator. I will look into this
> next.
0006 in the attached patch series completes this work. Now we find the
equality operators to be used for vertex-edge quals and save it in
pg_propgraph_element catalog and also add a dependency between the
edge element and the equality operators.
0008 - has WIP fix for \d and \d+
--
Best Wishes,
Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Ashutosh,
On Fri, Dec 6, 2024 at 12:34 AM Ashutosh Bapat
wrote:
>
> Sorry, I forgot to attach patches. PFA the patches.
>
> On Thu, Dec 5, 2024 at 4:38 PM Ashutosh Bapat
> wrote:
> >
> > On Fri, Nov 22, 2024 at 7:29 PM Ashutosh Bapat
> > wrote:
> > >
> > > On Tue, Nov 19, 2024 at 10:08 PM Vik Fearing wrote:
> > > >
> > > >
> > > > On 05/11/2024 16:41, Ashutosh Bapat wrote:
> > > >
> > > > On Wed, Aug 28, 2024 at 3:48 PM Ashutosh Bapat
> > > > wrote:
> > > >
> > > > Patches 0001 - 0006 are same as the previous set.
> > > > 0007 - fixes all the problems you reported till now and also the one I
> > > > found. The commit message describes the fixes in detail.
> > > >
> > > > Here's an updated patchset based on the latest HEAD.
> > > >
> > > >
> > > >
> > > > I have been looking at this patchset from a user's and standards' perspective and I am quite pleased with what I am seeing for the most part. I have not been looking much at the code itself, although I do plan on reviewing some of the code in the future.
> > >
> > > Thanks for looking at the patches.
> > >
> > > >
> > > >
> > > > There are a few things that stick out to me.
> > > >
> > > >
> > > > 1.
> > > > I don't see any way to view the structure of of a property graph. For example:
> > > >
> > > >
> > > > postgres=# CREATE TABLE objects (id INTEGER, color VARCHAR, shape VARCHAR, size INTEGER);
> > > > CREATE TABLE
> > > > postgres=# CREATE PROPERTY GRAPH propgraph VERTEX TABLES (objects KEY (id) PROPERTIES ALL COLUMNS);
> > > > CREATE PROPERTY GRAPH
> > > > postgres=# \dG propgraph
> > > > List of relations
> > > > Schema | Name | Type | Owner
> > > > -------------------+-----------+----------------+-------------
> > > > graph_table_tests | propgraph | property graph | vik.fearing
> > > > (1 row)
> > > >
> > > > postgres=# \d propgraph
> > > > Property graph "graph_table_tests.propgraph"
> > > > Column | Type
> > > > --------+------
> > > >
> > > > I don't really know what to do with that.
> > >
> > > Yes. It is on my TODO list. IMO we should just print the first line
> > > property graph "...". There are no predefined columns in this
> > > relation. And somehow redirect them to use \dG instead.
> >
> > \d+ propgraph prints the definition of property graph. I find \dG
> > similar to \di which doesn't print the structure of an index. Instead
> > \d+ prints it.
> >
> > In the attached patch series I have added patch 0008 to remove
> > unnecessary header
> > > > Column | Type
> > > > --------+------
> >
> > It still prints an extra line but I haven't found a way to eliminate
> > it. Hence 0008 is WIP. I have listed TODOs in the commit message of
> > that patch.
> >
> >
> > > >
> > > >
> > > > 2.
> > > > There is a missing newline in the \? help of psql.
> > > > HELP0(" \\dFt[+] [PATTERN] list text search templates\n");
> > > > HELP0(" \\dg[S+] [PATTERN] list roles\n");
> > > > HELP0(" \\dG[S+] [PATTERN] list property graphs"); <---
> > > > HELP0(" \\di[S+] [PATTERN] list indexes\n");
> > > > HELP0(" \\dl[+] list large objects, same as \\lo_list\n");
> > > >
> > >
> > > Will fix that in the next set.
> >
> > Done. The fix is part of 0001 now.
> >
> >
> >
> > >
> > > >
> > > > I will continue to review this feature from the user's perspective. Thank you for working on it, I am very excited to get this in.
> > >
> >
> > here's patchset rebased on 792b2c7e6d926e61e8ff3b33d3e22d7d74e7a437
> > with conflicts in rowsecurity.sql/out fixed.
> >
> > >
> > > 0001 - 0005 are the same as the previous set.
> > > 0007 - has RLS tests. It is the same as 0006 from the previous patch set.
> >
> > This is same as the previous patchset.
> >
> > >
> > > 0006 - is new addressing collation and edge-vertex link qual creation.
> > > This patch adds code to store collation and typmod to
> > > pg_propgraph_property catalog and propagate it to property graph
> > > references in GRAPH_TABLE. Collation is used by
> > > assign_query_collations and assign_expr_collations to propagate
> > > collation up the query and expression tree respectively. typmod is
> > > used to report typmod of property reference from exprTypemod().
> > >
> > > While finishing code to create vertex-edge link quals, I found that we
> > > need to find and store the operator to be used for key matching in
> > > those quals. I think we have to do something similar to what primary
> > > key handling code does - find the equality operator when creating edge
> > > descriptor and store it in pg_propgraph_element. I am not sure whether
> > > we should add a dependency on the operator. I will look into this
> > > next.
> >
> > 0006 in the attached patch series completes this work. Now we find the
> > equality operators to be used for vertex-edge quals and save it in
> > pg_propgraph_element catalog and also add a dependency between the
> > edge element and the equality operators.
> >
> > 0008 - has WIP fix for \d and \d+
> >
> > --
> > Best Wishes,
> > Ashutosh Bapat
>
>
>
> --
> Best Wishes,
> Ashutosh Bapat
I'm looking at the catalog definition, I have some questions which
might be silly.
Each pg element can have multiple labels(whose properties belong
to the same pg element), can we have multiple elements share the
same label?
If we have a 1..* relation between element and label, I think maybe
we don't need _pg_propgraph_label_.
From the name _pg_propgraph_label_property_, I tend to think it is
referencing _pg_propgraph_label_, but actually it is referencing
_pg_propgraph_element_label_.
--
Regards
Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Junwang, > > I'm looking at the catalog definition, I have some questions which > might be silly. Thanks for your interest in SQL/PGQ. > > Each pg element can have multiple labels(whose properties belong > to the same pg element), can we have multiple elements share the > same label? Yes. A label can be shared between edges and vertices as well. > > If we have a 1..* relation between element and label, I think maybe > we don't need _pg_propgraph_label_. pg_propgraph_label is used to map a label name in a given property graph to its OID. pg_propgraph_element_label - can be used to find all the elements with a given label and all the labels of a given element. The relationship is many to many. > > From the name _pg_propgraph_label_property_, I tend to think it is > referencing _pg_propgraph_label_, but actually it is referencing > _pg_propgraph_element_label_. > Right. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Mon, Dec 16, 2024 at 6:14 PM Ashutosh Bapat wrote: > > Hi Junwang, > > > > > I'm looking at the catalog definition, I have some questions which > > might be silly. > > Thanks for your interest in SQL/PGQ. > > > > > Each pg element can have multiple labels(whose properties belong > > to the same pg element), can we have multiple elements share the > > same label? > > Yes. A label can be shared between edges and vertices as well. > > > > > If we have a 1..* relation between element and label, I think maybe > > we don't need _pg_propgraph_label_. > > pg_propgraph_label is used to map a label name in a given property > graph to its OID. pg_propgraph_element_label - can be used to find all > the elements with a given label and all the labels of a given element. > The relationship is many to many. Ok, then it makes sense to me. Thanks for the explanation. > > > > > From the name _pg_propgraph_label_property_, I tend to think it is > > referencing _pg_propgraph_label_, but actually it is referencing > > _pg_propgraph_element_label_. > > > > Right. > > -- > Best Wishes, > Ashutosh Bapat -- Regards Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Ashutosh, On Wed, Jan 1, 2025 at 5:02 PM Ashutosh Bapat wrote: > > On Wed, Jan 1, 2025 at 2:22 PM Ashutosh Bapat > wrote: > > > > On Sat, Dec 21, 2024 at 6:21 PM Junwang Zhao wrote: > > Thanks Junwang for your review. > > > > > Here are some review opinions for 0001, I haven't seen the other > > > patches, forgive me if some of the opinions have already been > > > addressed. > > > > > > 1. In propgraph_edge_get_ref_keys, when finding a matching foreign key, > > > the fk pointer will always point to last ForeignKeyCacheInfo of > > > the edge relation, which is wrong. We should add another pointer > > > that remembers the matched ForeignKeyCacheInfo to ref_rel. See > > > attached 0001. > > > > Nice catch. I fixed it in a slightly different way reducing overall > > code by using foreach_node(). I have merged this as part of 0004 which > > has fixes for several other issues. Interestingly there was a SQL that > > had revealed the problem in create_property_graph.sql. But we had > > accepted a wrong output. Corrected that as well. > > > > > > > > 2. Some of the TODOs seem easy to address, attached 0002 does this. > > > > From a cursory glance those changes look useful and mostly correct. It > > will be good if you can provide a SQL test for those, covering that > > part of the code. Please post the whole patch-set with your changes as > > a separate commit/patch. > > > > > > > > 3. Since property name and label name are unique in property graph > > > scope, some of the wording are not accurate. See attached 0003. > > > > > > - For each property graph element, all properties with the same name must > > - have the same expression for each label. For example, this would be > > + For each property graph, all properties with the same name must > > + have the same expression. For example, this would be > > > > Each property graph element may have a property with the same name > > associated with multiple labels. But each of those properties should > > have the same expression. You may see that as the same property being > > defined multiple times once in each label it is associated with OR > > multiple properties with the same name. Current wording uses the > > latter notion, so it looks fine to me. The changes made to error > > messages are not needed with this notion. > > My last email is held for moderation. It will arrive once moderators > release it. In the meantime trying to send the patches as a zip file > in a hope that it won't require moderation. > > -- > Best Wishes, > Ashutosh Bapat 0007-RLS-tests-20250101.patch introduces regression test failure: +WARNING: outfuncs/readfuncs failed to produce an equal rewritten parse tree P.S. It seems the patch set doesn't apply to master. -- Regards Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
On Fri, Jan 24, 2025 at 11:46 PM Junwang Zhao wrote: > > On Fri, Jan 24, 2025 at 9:31 PM Ashutosh Bapat > wrote: > > > > On Sun, Jan 19, 2025 at 6:45 PM Junwang Zhao wrote: > > > > > > Hi Ashutosh, > > > > > > On Wed, Jan 1, 2025 at 5:02 PM Ashutosh Bapat > > > wrote: > > > > > > > > On Wed, Jan 1, 2025 at 2:22 PM Ashutosh Bapat > > > > wrote: > > > > > > > > > > On Sat, Dec 21, 2024 at 6:21 PM Junwang Zhao wrote: > > > > > Thanks Junwang for your review. > > > > > > > > > > > Here are some review opinions for 0001, I haven't seen the other > > > > > > patches, forgive me if some of the opinions have already been > > > > > > addressed. > > > > > > > > > > > > 1. In propgraph_edge_get_ref_keys, when finding a matching foreign key, > > > > > > the fk pointer will always point to last ForeignKeyCacheInfo of > > > > > > the edge relation, which is wrong. We should add another pointer > > > > > > that remembers the matched ForeignKeyCacheInfo to ref_rel. See > > > > > > attached 0001. > > > > > > > > > > Nice catch. I fixed it in a slightly different way reducing overall > > > > > code by using foreach_node(). I have merged this as part of 0004 which > > > > > has fixes for several other issues. Interestingly there was a SQL that > > > > > had revealed the problem in create_property_graph.sql. But we had > > > > > accepted a wrong output. Corrected that as well. > > > > > > > > > > > > > > > > > 2. Some of the TODOs seem easy to address, attached 0002 does this. > > > > > > > > > > From a cursory glance those changes look useful and mostly correct. It > > > > > will be good if you can provide a SQL test for those, covering that > > > > > part of the code. Please post the whole patch-set with your changes as > > > > > a separate commit/patch. > > > > > > > > > > > > > > > > > 3. Since property name and label name are unique in property graph > > > > > > scope, some of the wording are not accurate. See attached 0003. > > > > > > > > > > > > > > > - For each property graph element, all properties with the same name must > > > > > - have the same expression for each label. For example, this would be > > > > > + For each property graph, all properties with the same name must > > > > > + have the same expression. For example, this would be > > > > > > > > > > Each property graph element may have a property with the same name > > > > > associated with multiple labels. But each of those properties should > > > > > have the same expression. You may see that as the same property being > > > > > defined multiple times once in each label it is associated with OR > > > > > multiple properties with the same name. Current wording uses the > > > > > latter notion, so it looks fine to me. The changes made to error > > > > > messages are not needed with this notion. > > > > > > > > My last email is held for moderation. It will arrive once moderators > > > > release it. In the meantime trying to send the patches as a zip file > > > > in a hope that it won't require moderation. > > > > > > > > -- > > > > Best Wishes, > > > > Ashutosh Bapat > > > > > > 0007-RLS-tests-20250101.patch introduces regression test failure: > > > > > > +WARNING: outfuncs/readfuncs failed to produce an equal rewritten parse tree > > > > > > P.S. It seems the patch set doesn't apply to master. > > > > Thanks for noticing it. > > > > Here's rebased patch set on the current head with some minor conflicts > > in various files fixed. I did not see the said failure on my laptop. > > I figured out it's because I have `-DWRITE_READ_PARSE_PLAN_TREES` this option, > removing this option clears the warning, but I'm not sure if this is a > hidden issue. Cirrus meson FreeBSD build has this setting, the regression test rowsecurity failed the same as my local machine, see [0], so I think this is an issue we have to resolve. Cirrus meson Bookworm build failed 002_pg_upgrade.pl and 027_stream_regress.pl, see [1] [0] https://cirrus-ci.com/task/5702052891852800 [1] https://cirrus-ci.com/task/6265002845274112 > > > > > 0001-0009 patches are the same as the previous set sans mergeconflict fixes. > > 0010 - is test for \dGx - to make sure that the extended format output > > works with \dG. We may decide not to have this patch in the final > > commit. But no harm in being there til that point. > > I have some changes based on the latest patch set. I attached two patches with > the following summary. > > 0001: > - doc: some of the query in ddl.sgml can not be executed > - after path factor was introduced, some comments doesn't apply > > 0002: > - add a get_propgraph_element_alias_name function and do some trivial refactor > > > -- > > Best Wishes, > > Ashutosh Bapat > > > > -- > Regards > Junwang Zhao -- Regards Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
On Tue, Jan 28, 2025 at 6:17 PM Ashutosh Bapat wrote: > > On Fri, Jan 24, 2025 at 9:16 PM Junwang Zhao wrote: > > > > I figured out it's because I have `-DWRITE_READ_PARSE_PLAN_TREES` this option, > > removing this option clears the warning, but I'm not sure if this is a > > hidden issue. > > > > Thanks for the hint. I found the issue and the fix appears in 0004. > Some members of RangeTblEntry were not being handled in read/out > functions. Thanks for the fix, I will apply and test again. > > > > > > > 0001-0009 patches are the same as the previous set sans mergeconflict fixes. > > > 0010 - is test for \dGx - to make sure that the extended format output > > > works with \dG. We may decide not to have this patch in the final > > > commit. But no harm in being there til that point. > > > > I have some changes based on the latest patch set. I attached two patches with > > the following summary. > > > > 0001: > > - doc: some of the query in ddl.sgml can not be executed > > The standard seems to require a property reference to be qualified by > element pattern variable, even if the property is referenced within > the same element pattern bound to the variable. Hence I accepted your > document fixes which qualify property reference with element pattern > variable. > > However, I didn't understand why you changed a LABEL name from order to order_. Ah, that's because `order` is a keyword of SQL(order by), so the alias is a conflict. I'm not saying `order_` is a good name though. > > > - after path factor was introduced, some comments doesn't apply > > Thanks pointing those out. Accepted after rephrasing those and also > correcting some related comments. > > > > > 0002: > > - add a get_propgraph_element_alias_name function and do some trivial refactor > > > > I see you have added some negative tests - object not found tests, but > I didn't see positive tests. Hence I haven't added those changes in > the attached patchset. But we certainly need those changes. You may > want to submit a patch with positive tests. That code needs to be > fixed before committing anyway. Ok, I'll add positive tests. > > -- > Best Wishes, > Ashutosh Bapat -- Regards Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
On Tue, Jan 28, 2025 at 4:31 PM Junwang Zhao wrote: > > On Tue, Jan 28, 2025 at 6:17 PM Ashutosh Bapat > wrote: > > > > On Fri, Jan 24, 2025 at 9:16 PM Junwang Zhao wrote: > > > > > > I figured out it's because I have `-DWRITE_READ_PARSE_PLAN_TREES` this option, > > > removing this option clears the warning, but I'm not sure if this is a > > > hidden issue. > > > > > > > Thanks for the hint. I found the issue and the fix appears in 0004. > > Some members of RangeTblEntry were not being handled in read/out > > functions. > > Thanks for the fix, I will apply and test again. > > > > > > > > > > > 0001-0009 patches are the same as the previous set sans mergeconflict fixes. > > > > 0010 - is test for \dGx - to make sure that the extended format output > > > > works with \dG. We may decide not to have this patch in the final > > > > commit. But no harm in being there til that point. > > > > > > I have some changes based on the latest patch set. I attached two patches with > > > the following summary. > > > > > > 0001: > > > - doc: some of the query in ddl.sgml can not be executed > > > > The standard seems to require a property reference to be qualified by > > element pattern variable, even if the property is referenced within > > the same element pattern bound to the variable. Hence I accepted your > > document fixes which qualify property reference with element pattern > > variable. > > > > However, I didn't understand why you changed a LABEL name from order to order_. > > Ah, that's because `order` is a keyword of SQL(order by), so the alias > is a conflict. > I'm not saying `order_` is a good name though. I didn't realize that. Thanks for catching. In that case just orders or cust_orders? > > > > > > - after path factor was introduced, some comments doesn't apply > > > > Thanks pointing those out. Accepted after rephrasing those and also > > correcting some related comments. > > > > > > > > 0002: > > > - add a get_propgraph_element_alias_name function and do some trivial refactor > > > > > > > I see you have added some negative tests - object not found tests, but > > I didn't see positive tests. Hence I haven't added those changes in > > the attached patchset. But we certainly need those changes. You may > > want to submit a patch with positive tests. That code needs to be > > fixed before committing anyway. > > Ok, I'll add positive tests. Thanks. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Tue, Jan 28, 2025 at 7:03 PM Ashutosh Bapat wrote: > > On Tue, Jan 28, 2025 at 4:31 PM Junwang Zhao wrote: > > > > On Tue, Jan 28, 2025 at 6:17 PM Ashutosh Bapat > > wrote: > > > > > > On Fri, Jan 24, 2025 at 9:16 PM Junwang Zhao wrote: > > > > > > > > I figured out it's because I have `-DWRITE_READ_PARSE_PLAN_TREES` this option, > > > > removing this option clears the warning, but I'm not sure if this is a > > > > hidden issue. > > > > > > > > > > Thanks for the hint. I found the issue and the fix appears in 0004. > > > Some members of RangeTblEntry were not being handled in read/out > > > functions. > > > > Thanks for the fix, I will apply and test again. > > > > > > > > > > > > > > > 0001-0009 patches are the same as the previous set sans mergeconflict fixes. > > > > > 0010 - is test for \dGx - to make sure that the extended format output > > > > > works with \dG. We may decide not to have this patch in the final > > > > > commit. But no harm in being there til that point. > > > > > > > > I have some changes based on the latest patch set. I attached two patches with > > > > the following summary. > > > > > > > > 0001: > > > > - doc: some of the query in ddl.sgml can not be executed > > > > > > The standard seems to require a property reference to be qualified by > > > element pattern variable, even if the property is referenced within > > > the same element pattern bound to the variable. Hence I accepted your > > > document fixes which qualify property reference with element pattern > > > variable. > > > > > > However, I didn't understand why you changed a LABEL name from order to order_. > > > > Ah, that's because `order` is a keyword of SQL(order by), so the alias > > is a conflict. > > I'm not saying `order_` is a good name though. > > I didn't realize that. Thanks for catching. In that case just orders > or cust_orders? Yeah, I think explicitly LABELed as `orders` makes sense. > > > > > > > > > > - after path factor was introduced, some comments doesn't apply > > > > > > Thanks pointing those out. Accepted after rephrasing those and also > > > correcting some related comments. > > > > > > > > > > > 0002: > > > > - add a get_propgraph_element_alias_name function and do some trivial refactor > > > > > > > > > > I see you have added some negative tests - object not found tests, but > > > I didn't see positive tests. Hence I haven't added those changes in > > > the attached patchset. But we certainly need those changes. You may > > > want to submit a patch with positive tests. That code needs to be > > > fixed before committing anyway. > > > > Ok, I'll add positive tests. > > Thanks. > > -- > Best Wishes, > Ashutosh Bapat -- Regards Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
On Thu, Feb 6, 2025 at 8:22 PM Junwang Zhao wrote: > > > > > > > I see you have added some negative tests - object not found tests, but > > I didn't see positive tests. Hence I haven't added those changes in > > the attached patchset. But we certainly need those changes. You may > > want to submit a patch with positive tests. That code needs to be > > fixed before committing anyway. > > The attached file adds the positive tests. Hi Junwang, Thanks for the patch, but please post it as a separate patch in the full patch-set, otherwise CFBot gets confused. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Mon, Feb 10, 2025 at 11:00 PM Junwang Zhao wrote: > > Hi Ashutosh, > > On Mon, Feb 10, 2025 at 2:14 PM Ashutosh Bapat > wrote: > > > > On Thu, Feb 6, 2025 at 8:22 PM Junwang Zhao wrote: > > > > > > > > > > > > > I see you have added some negative tests - object not found tests, but > > > > I didn't see positive tests. Hence I haven't added those changes in > > > > the attached patchset. But we certainly need those changes. You may > > > > want to submit a patch with positive tests. That code needs to be > > > > fixed before committing anyway. > > > > > > The attached file adds the positive tests. > > > > Hi Junwang, > > Thanks for the patch, but please post it as a separate patch in the > > full patch-set, otherwise CFBot gets confused. > > Ok, see the attached. > > 0001-0009 are the original patches of 20250127 with rebase of master > 0010 fix ci error due to `Show more-intuitive titles for psql > commands`, see a14707da564e > 0011 fix ci error due to unstable collation tests, we should not > depend on pg_catalog."default", I observed 002_pg_upgrade.pl failure > caused by this. > 0012 trivial refactor of property graph object address > > > > > -- > > Best Wishes, > > Ashutosh Bapat > > > > -- > Regards > Junwang Zhao Here is v11 with another trivial refactor, I add a seperate patch file 0013, in insert_property_record, there is no need to check `type`, `typmode` and `collation` if the property doesn't exists before, in AlterPropGraph, there is no need to call `check_all_labels_properties` for each added vertex or edge. Other files remain unchanged except I’ve added some missing document and typo fix we discussed in the list but not included in the previous patch, I included them in 0008. -- Regards Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
Hi!
I would ask about CREATE GRAPH PROPERTY. From my point of view it makes
very strong
check of types including check of typmod.
Example:
CREATE TABLE userslist (
user_id INT primary key,
name VARCHAR(40)
);
CREATE TABLE groupslist (
group_id INT primary key,
name VARCHAR(30)
);
CREATE TABLE memberslist (
member_id INT primary key,
user_id INT,
group_id INT,
CONSTRAINT members_users_fk1 FOREIGN KEY (user_id) REFERENCES userslist
(user_id),
CONSTRAINT members_groups_fk1 FOREIGN KEY (group_id) REFERENCES
groupslist (group_id)
);
CREATE PROPERTY GRAPH members_pg
VERTEX TABLES (
userslist
KEY (user_id)
LABEL luser
PROPERTIES ALL COLUMNS,
groupslist
KEY (group_id)
LABEL lgroup
PROPERTIES ALL COLUMNS
)
edge TABLES (
memberslist
KEY (member_id)
SOURCE KEY (user_id) REFERENCES userslist (user_id)
DESTINATION KEY (group_id) REFERENCES groupslist (group_id)
LABEL lmember
PROPERTIES ALL COLUMNS
);
Last command fails with error:
ERROR: property "name" data type modifier mismatch: 19 vs. 14
DETAIL: In a property graph, a property of the same name has to have
the same type modifier in each label.
Labels luser and lgroup both have property "name" originated from tables
userslist and groupslist
with types VARCHAR(40) and VARCHAR(30). Current implementation treats
them as fields with
different types. I think, they should not be treated as different types.
Typmod is additional
constrain, it does not create another type.
Documentation includes:"modifiers, that is optional constraints attached
to a type declaration,
such as char(5) or numeric(30,2)"
Operations with values using different typmod do not require cast, they
treated as the
same type.
Also I would add, that Oracle executes the code above without error.
I propose to exclude the check of typmod from the equivalence of types
check in
src/backend/commands/propgraphcmds.c .
I suppose there is other reason to make this check (not the Standart
SQL-2023 requirement,
but internal dependency), but I have not realised this reason.
--
Best regards,
Vladlen Popolitov.
Re: SQL Property Graph Queries (SQL/PGQ)
On Tue, Feb 25, 2025 at 3:17 PM Vladlen Popolitov wrote: > > Hi! > > I would ask about CREATE GRAPH PROPERTY. From my point of view it makes > very strong > check of types including check of typmod. > > Example: > > CREATE TABLE userslist ( > user_id INT primary key, > name VARCHAR(40) > ); > > CREATE TABLE groupslist ( > group_id INT primary key, > name VARCHAR(30) > ); > > CREATE TABLE memberslist ( > member_id INT primary key, > user_id INT, > group_id INT, > CONSTRAINT members_users_fk1 FOREIGN KEY (user_id) REFERENCES userslist > (user_id), > CONSTRAINT members_groups_fk1 FOREIGN KEY (group_id) REFERENCES > groupslist (group_id) > ); > > CREATE PROPERTY GRAPH members_pg > VERTEX TABLES ( > userslist > KEY (user_id) > LABEL luser > PROPERTIES ALL COLUMNS, > groupslist > KEY (group_id) > LABEL lgroup > PROPERTIES ALL COLUMNS > ) > edge TABLES ( > memberslist > KEY (member_id) > SOURCE KEY (user_id) REFERENCES userslist (user_id) > DESTINATION KEY (group_id) REFERENCES groupslist (group_id) > LABEL lmember > PROPERTIES ALL COLUMNS > ); > > Last command fails with error: > ERROR: property "name" data type modifier mismatch: 19 vs. 14 > DETAIL: In a property graph, a property of the same name has to have > the same type modifier in each label. > > Labels luser and lgroup both have property "name" originated from tables > userslist and groupslist > with types VARCHAR(40) and VARCHAR(30). Current implementation treats > them as fields with > different types. I think, they should not be treated as different types. > Typmod is additional > constrain, it does not create another type. > Documentation includes:"modifiers, that is optional constraints attached > to a type declaration, > such as char(5) or numeric(30,2)" > > Operations with values using different typmod do not require cast, they > treated as the > same type. When a property is projected in a COLUMNS clause, it will be added to the SELECT list of the rewritten query, which in turn could be a UNION query. Having the same typmod for all the properties with the same name makes it easy to write the SELECT list of UNION. Otherwise, we have to find a common typmod for all the properties. This restriction is not expected to be permanent but makes the first set of patches easy, which are quite large as is. I think in some next version, we will lift this restriction as well as lift the restriction on all properties with the same name needing the same datatype. According to the SQL standard, they can be of different data types as long as there's a common type to which they all can be cast to. It may be possible to lift this restriction in this version itself, if we find enough developer and reviewer bandwidth. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Ashutosh Bapat писал(а) 2025-02-25 17:20: > On Tue, Feb 25, 2025 at 3:17 PM Vladlen Popolitov > wrote: >> >> Hi! >> >> I would ask about CREATE GRAPH PROPERTY. From my point of view it >> makes >> very strong >> check of types including check of typmod. >> >> Example: >> >> CREATE TABLE userslist ( >> user_id INT primary key, >> name VARCHAR(40) >> ); >> >> CREATE TABLE groupslist ( >> group_id INT primary key, >> name VARCHAR(30) >> ); >> >> CREATE TABLE memberslist ( >> member_id INT primary key, >> user_id INT, >> group_id INT, >> CONSTRAINT members_users_fk1 FOREIGN KEY (user_id) REFERENCES >> userslist >> (user_id), >> CONSTRAINT members_groups_fk1 FOREIGN KEY (group_id) REFERENCES >> groupslist (group_id) >> ); >> >> CREATE PROPERTY GRAPH members_pg >> VERTEX TABLES ( >> userslist >> KEY (user_id) >> LABEL luser >> PROPERTIES ALL COLUMNS, >> groupslist >> KEY (group_id) >> LABEL lgroup >> PROPERTIES ALL COLUMNS >> ) >> edge TABLES ( >> memberslist >> KEY (member_id) >> SOURCE KEY (user_id) REFERENCES userslist (user_id) >> DESTINATION KEY (group_id) REFERENCES groupslist (group_id) >> LABEL lmember >> PROPERTIES ALL COLUMNS >> ); >> >> Last command fails with error: >> ERROR: property "name" data type modifier mismatch: 19 vs. 14 >> DETAIL: In a property graph, a property of the same name has to have >> the same type modifier in each label. >> >> Labels luser and lgroup both have property "name" originated from >> tables >> userslist and groupslist >> with types VARCHAR(40) and VARCHAR(30). Current implementation treats >> them as fields with >> different types. I think, they should not be treated as different >> types. >> Typmod is additional >> constrain, it does not create another type. >> Documentation includes:"modifiers, that is optional constraints >> attached >> to a type declaration, >> such as char(5) or numeric(30,2)" >> >> Operations with values using different typmod do not require cast, >> they >> treated as the >> same type. > > When a property is projected in a COLUMNS clause, it will be added to > the SELECT list of the rewritten query, which in turn could be a UNION > query. Having the same typmod for all the properties with the same > name makes it easy to write the SELECT list of UNION. Otherwise, we > have to find a common typmod for all the properties. This restriction > is not expected to be permanent but makes the first set of patches > easy, which are quite large as is. I think in some next version, we > will lift this restriction as well as lift the restriction on all > properties with the same name needing the same datatype. According to > the SQL standard, they can be of different data types as long as > there's a common type to which they all can be cast to. It may be > possible to lift this restriction in this version itself, if we find > enough developer and reviewer bandwidth. Hi! Thank you for explanation. I expected, that it has some internal dependency, but did not find it. I am running graph queries now, and I will see how they interact with typmod. -- Best regards, Vladlen Popolitov.
Re: SQL Property Graph Queries (SQL/PGQ)
On Sun, Feb 23, 2025 at 8:54 PM Junwang Zhao wrote:
>
> On Mon, Feb 10, 2025 at 11:00 PM Junwang Zhao wrote:
> >
> > Hi Ashutosh,
> >
> > On Mon, Feb 10, 2025 at 2:14 PM Ashutosh Bapat
> > wrote:
> > >
> > > On Thu, Feb 6, 2025 at 8:22 PM Junwang Zhao wrote:
> > > > > >
> > > > >
> > > > > I see you have added some negative tests - object not found tests, but
> > > > > I didn't see positive tests. Hence I haven't added those changes in
> > > > > the attached patchset. But we certainly need those changes. You may
> > > > > want to submit a patch with positive tests. That code needs to be
> > > > > fixed before committing anyway.
> > > >
> > > > The attached file adds the positive tests.
> > >
> > > Hi Junwang,
> > > Thanks for the patch, but please post it as a separate patch in the
> > > full patch-set, otherwise CFBot gets confused.
> >
> > Ok, see the attached.
> >
> > 0001-0009 are the original patches of 20250127 with rebase of master
> > 0010 fix ci error due to `Show more-intuitive titles for psql
> > commands`, see a14707da564e
> > 0011 fix ci error due to unstable collation tests, we should not
> > depend on pg_catalog."default", I observed 002_pg_upgrade.pl failure
> > caused by this.
> > 0012 trivial refactor of property graph object address
> >
> > >
> > > --
> > > Best Wishes,
> > > Ashutosh Bapat
> >
> >
> >
> > --
> > Regards
> > Junwang Zhao
>
> Here is v11 with another trivial refactor, I add a seperate patch file 0013, in
> insert_property_record, there is no need to check `type`, `typmode` and
> `collation` if the property doesn't exists before, in AlterPropGraph, there is
> no need to call `check_all_labels_properties` for each added vertex or edge.
>
> Other files remain unchanged except I’ve added some missing document and
> typo fix we discussed in the list but not included in the previous
> patch, I included
> them in 0008.
>
> --
> Regards
> Junwang Zhao
Current patch set failed the cfbot, I did some analysis on this, the reason for
the failure is that backend has a core dump, I extract some queries from
graph_table.sql to reproduce the issue:
----------------- queries begin -----------------
CREATE SCHEMA graph_table_tests;
GRANT USAGE ON SCHEMA graph_table_tests TO PUBLIC;
SET search_path = graph_table_tests;
CREATE TABLE products (
product_no integer PRIMARY KEY,
name varchar,
price numeric
);
CREATE TABLE customers (
customer_id integer PRIMARY KEY,
name varchar,
address varchar
);
CREATE TABLE orders (
order_id integer PRIMARY KEY,
ordered_when date
);
CREATE TABLE order_items (
order_items_id integer PRIMARY KEY,
order_id integer REFERENCES orders (order_id),
product_no integer REFERENCES products (product_no),
quantity integer
);
CREATE TABLE customer_orders (
customer_orders_id integer PRIMARY KEY,
customer_id integer REFERENCES customers (customer_id),
order_id integer REFERENCES orders (order_id)
);
CREATE VIEW customers_view AS SELECT customer_id, 'redacted' ||
customer_id AS name_redacted, address FROM customers;
CREATE PROPERTY GRAPH myshop2
VERTEX TABLES (
products,
customers_view KEY (customer_id) LABEL customers,
orders
)
EDGE TABLES (
order_items KEY (order_items_id)
SOURCE KEY (order_id) REFERENCES orders (order_id)
DESTINATION KEY (product_no) REFERENCES products (product_no),
customer_orders KEY (customer_orders_id)
SOURCE KEY (customer_id) REFERENCES customers_view (customer_id)
DESTINATION KEY (order_id) REFERENCES orders (order_id)
);
CREATE VIEW customers_us_redacted AS SELECT * FROM GRAPH_TABLE
(myshop2 MATCH (c IS customers WHERE c.address = 'US')-[IS
customer_orders]->(o IS orders) COLUMNS (c.name_redacted AS
customer_name_redacted));
SELECT * FROM customers_us_redacted; <----- abort on this query
----------------- queries end -----------------
The backend aborted in ExecCheckPermissions, a recent commit 525392d57
add the following check:
----------------- code begin -----------------
/*
* Ensure that we have at least an AccessShareLock on relations
* whose permissions need to be checked.
*
* Skip this check in a parallel worker because locks won't be
* taken until ExecInitNode() performs plan initialization.
*
* XXX: ExecCheckPermissions() in a parallel worker may be
* redundant with the checks done in the leader process, so this
* should be reviewed to ensure it’s necessary.
*/
Assert(IsParallelWorker() ||
CheckRelationOidLockedByMe(rte->relid, AccessShareLock,
true));
----------------- code end -----------------
The query causing the core dump doesn't call transformRangeGraphTable
because the graph table is not in the `from` lists, so the graph table
is not locked.
I added a trivial fix(v12-0014) that called table_open/table_close in
rewriteGraphTable, it now passed the regression test and cirrus ci test,
but I'm not sure it's the correct fix.
I hope Ashutosh can chime in and take a look at this problem.
--
Regards
Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Amit and Ashutosh,
On Tue, Mar 11, 2025 at 8:19 PM Junwang Zhao wrote:
>
> Hi Amit,
>
> On Tue, Mar 11, 2025 at 5:06 PM Amit Langote wrote:
> >
> > Hi Ashutosh, Junwang,
> >
> > On Tue, Mar 11, 2025 at 4:22 PM Ashutosh Bapat
> > wrote:
> > > On Wed, Feb 26, 2025 at 8:04 PM Junwang Zhao wrote:
> > > > I added a trivial fix(v12-0014) that called table_open/table_close in
> > > > rewriteGraphTable, it now passed the regression test and cirrus ci test,
> > > > but I'm not sure it's the correct fix.
> > > >
> > > > I hope Ashutosh can chime in and take a look at this problem.
> > >
> > > 2. Following Assertion is failing, the assertion was added recently.
> > > TRAP: failed Assert("IsParallelWorker() ||
> > > CheckRelationOidLockedByMe(rte->relid, AccessShareLock, true)"), File:
> > > "../../coderoot/pg/src/backend/executor/execMain.c", Line: 695, PID:
> > > 303994
> > > postgres: ashutosh regression [local]
> > > SELECT(ExceptionalCondition+0xbe)[0x5c838c5d7114]
> > > postgres: ashutosh regression [local]
> > > SELECT(ExecCheckPermissions+0xf8)[0x5c838c11fb9c]
> > > postgres: ashutosh regression [local] SELECT(+0x38223f)[0x5c838c12023f]
> > > postgres: ashutosh regression [local]
> > > SELECT(standard_ExecutorStart+0x2f8)[0x5c838c11f223]
> > > postgres: ashutosh regression [local] SELECT(ExecutorStart+0x69)[0x5c838c11ef22]
> > > postgres: ashutosh regression [local] SELECT(PortalStart+0x368)[0x5c838c3d991a]
> > > postgres: ashutosh regression [local] SELECT(+0x63458e)[0x5c838c3d258e]
> > > postgres: ashutosh regression [local] SELECT(PostgresMain+0x9eb)[0x5c838c3d7cf0]
> > > postgres: ashutosh regression [local] SELECT(+0x630178)[0x5c838c3ce178]
> > > postgres: ashutosh regression [local]
> > > SELECT(postmaster_child_launch+0x137)[0x5c838c2da677]
> > > postgres: ashutosh regression [local] SELECT(+0x5431b4)[0x5c838c2e11b4]
> > > postgres: ashutosh regression [local] SELECT(+0x54076a)[0x5c838c2de76a]
> > > postgres: ashutosh regression [local]
> > > SELECT(PostmasterMain+0x15f8)[0x5c838c2de04d]
> > > postgres: ashutosh regression [local] SELECT(main+0x3a1)[0x5c838c1b12be]
> > > /lib/x86_64-linux-gnu/libc.so.6(+0x29d90)[0x7eda9ea29d90]
> > > /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x80)[0x7eda9ea29e40]
> > > postgres: ashutosh regression [local] SELECT(_start+0x25)[0x5c838be7c025]
> > > 2025-03-11 11:40:01.696 IST postmaster[303081] LOG: client backend
> > > (PID 303994) was terminated by signal 6: Aborted
> > > 2025-03-11 11:40:01.696 IST postmaster[303081] DETAIL: Failed process
> > > was running: select * from atpgv1;
> > > I tried to investigate the Assertion, it's failing for property graph
> > > RTE which is turned into subquery RTE. It has the right lock mode set,
> > > but I haven't been able to figure out where the lock is supposed to be
> > > taken or where it's released. If we just prepare the failing query and
> > > execute the prepared statement, it does not trip the assertion. Will
> > > investigate it more.
> >
> > I reproduced the crash using the example Junwang gave.
> >
> > The problem seems to be that RTEs of rtekind RTE_GRAPH_TABLE are not
> > handled in AcquireRewriteLocks(). You'll need to add a case for
> > RTE_GRAPH_TABLE similar to RTE_RELATION in the following switch of
> > that function:
> >
> > /*
> > * First, process RTEs of the current query level.
> > */
> > rt_index = 0;
> > foreach(l, parsetree->rtable)
> > {
> > RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
> > Relation rel;
> > LOCKMODE lockmode;
> > List *newaliasvars;
> > Index curinputvarno;
> > RangeTblEntry *curinputrte;
> > ListCell *ll;
> >
> > ++rt_index;
> > switch (rte->rtekind)
> > {
> > case RTE_RELATION:
> >
> > which could be as simple as the following (fixes the crash!) or
> > something that's specific to RTE_GRAPH_TABLE:
> >
> > diff --git a/src/backend/rewrite/rewriteHandler.c
> > b/src/backend/rewrite/rewriteHandler.c
> > index c51dd3d2ee4..8fa6edb90eb 100644
> > --- a/src/backend/rewrite/rewriteHandler.c
> > +++ b/src/backend/rewrite/rewriteHandler.c
> > @@ -174,6 +174,7 @@ AcquireRewriteLocks(Query *parsetree,
> > switch (rte->rtekind)
> > {
> > case RTE_RELATION:
> > + case RTE_GRAPH_TABLE:
> >
> > --
> > Thanks, Amit Langote
>
> I’ve tested the fix, it works and is better than my previous solution.
> I will send a new patch set with this improvement, thanks.
>
> --
> Regards
> Junwang Zhao
Here is a new version with Amit's fix and my trivial refactors.
0001-0010 is the same as Ashutosh's last email
0011 is Amit's fix of the crash in ExecCheckPermissions
0012 is a trivial fix that remove the test with default collation, or
it will fail CI, see[1]
0013-0015 are some trivial fix and refactor, feel free to incorporate
or drop when you review them.
[1]: https://api.cirrus-ci.com/v1/artifact/task/5290818690351104/testrun/build/testrun/regress/regress/regression.diffs
--
Regards
Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Junwang,
On Wed, Feb 26, 2025 at 8:04 PM Junwang Zhao wrote:
.
>
> I added a trivial fix(v12-0014) that called table_open/table_close in
> rewriteGraphTable, it now passed the regression test and cirrus ci test,
> but I'm not sure it's the correct fix.
>
> I hope Ashutosh can chime in and take a look at this problem.
Looks like the first patch has grown some conflicts. Here's set of
rebased patches. There are two main things missing from this patchset
1. Junwang's patches - Extremely sorry, didn't get time to include
your patches. Junwang, you may want to post whole patchset rebased on
attached patch set. I hope to review and incorporate your patches some
time soon.
2. Following Assertion is failing, the assertion was added recently.
TRAP: failed Assert("IsParallelWorker() ||
CheckRelationOidLockedByMe(rte->relid, AccessShareLock, true)"), File:
"../../coderoot/pg/src/backend/executor/execMain.c", Line: 695, PID:
303994
postgres: ashutosh regression [local]
SELECT(ExceptionalCondition+0xbe)[0x5c838c5d7114]
postgres: ashutosh regression [local]
SELECT(ExecCheckPermissions+0xf8)[0x5c838c11fb9c]
postgres: ashutosh regression [local] SELECT(+0x38223f)[0x5c838c12023f]
postgres: ashutosh regression [local]
SELECT(standard_ExecutorStart+0x2f8)[0x5c838c11f223]
postgres: ashutosh regression [local] SELECT(ExecutorStart+0x69)[0x5c838c11ef22]
postgres: ashutosh regression [local] SELECT(PortalStart+0x368)[0x5c838c3d991a]
postgres: ashutosh regression [local] SELECT(+0x63458e)[0x5c838c3d258e]
postgres: ashutosh regression [local] SELECT(PostgresMain+0x9eb)[0x5c838c3d7cf0]
postgres: ashutosh regression [local] SELECT(+0x630178)[0x5c838c3ce178]
postgres: ashutosh regression [local]
SELECT(postmaster_child_launch+0x137)[0x5c838c2da677]
postgres: ashutosh regression [local] SELECT(+0x5431b4)[0x5c838c2e11b4]
postgres: ashutosh regression [local] SELECT(+0x54076a)[0x5c838c2de76a]
postgres: ashutosh regression [local]
SELECT(PostmasterMain+0x15f8)[0x5c838c2de04d]
postgres: ashutosh regression [local] SELECT(main+0x3a1)[0x5c838c1b12be]
/lib/x86_64-linux-gnu/libc.so.6(+0x29d90)[0x7eda9ea29d90]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x80)[0x7eda9ea29e40]
postgres: ashutosh regression [local] SELECT(_start+0x25)[0x5c838be7c025]
2025-03-11 11:40:01.696 IST postmaster[303081] LOG: client backend
(PID 303994) was terminated by signal 6: Aborted
2025-03-11 11:40:01.696 IST postmaster[303081] DETAIL: Failed process
was running: select * from atpgv1;
I tried to investigate the Assertion, it's failing for property graph
RTE which is turned into subquery RTE. It has the right lock mode set,
but I haven't been able to figure out where the lock is supposed to be
taken or where it's released. If we just prepare the failing query and
execute the prepared statement, it does not trip the assertion. Will
investigate it more.
--
Best Wishes,
Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Ashutosh, Junwang,
On Tue, Mar 11, 2025 at 4:22 PM Ashutosh Bapat
wrote:
> On Wed, Feb 26, 2025 at 8:04 PM Junwang Zhao wrote:
> > I added a trivial fix(v12-0014) that called table_open/table_close in
> > rewriteGraphTable, it now passed the regression test and cirrus ci test,
> > but I'm not sure it's the correct fix.
> >
> > I hope Ashutosh can chime in and take a look at this problem.
>
> 2. Following Assertion is failing, the assertion was added recently.
> TRAP: failed Assert("IsParallelWorker() ||
> CheckRelationOidLockedByMe(rte->relid, AccessShareLock, true)"), File:
> "../../coderoot/pg/src/backend/executor/execMain.c", Line: 695, PID:
> 303994
> postgres: ashutosh regression [local]
> SELECT(ExceptionalCondition+0xbe)[0x5c838c5d7114]
> postgres: ashutosh regression [local]
> SELECT(ExecCheckPermissions+0xf8)[0x5c838c11fb9c]
> postgres: ashutosh regression [local] SELECT(+0x38223f)[0x5c838c12023f]
> postgres: ashutosh regression [local]
> SELECT(standard_ExecutorStart+0x2f8)[0x5c838c11f223]
> postgres: ashutosh regression [local] SELECT(ExecutorStart+0x69)[0x5c838c11ef22]
> postgres: ashutosh regression [local] SELECT(PortalStart+0x368)[0x5c838c3d991a]
> postgres: ashutosh regression [local] SELECT(+0x63458e)[0x5c838c3d258e]
> postgres: ashutosh regression [local] SELECT(PostgresMain+0x9eb)[0x5c838c3d7cf0]
> postgres: ashutosh regression [local] SELECT(+0x630178)[0x5c838c3ce178]
> postgres: ashutosh regression [local]
> SELECT(postmaster_child_launch+0x137)[0x5c838c2da677]
> postgres: ashutosh regression [local] SELECT(+0x5431b4)[0x5c838c2e11b4]
> postgres: ashutosh regression [local] SELECT(+0x54076a)[0x5c838c2de76a]
> postgres: ashutosh regression [local]
> SELECT(PostmasterMain+0x15f8)[0x5c838c2de04d]
> postgres: ashutosh regression [local] SELECT(main+0x3a1)[0x5c838c1b12be]
> /lib/x86_64-linux-gnu/libc.so.6(+0x29d90)[0x7eda9ea29d90]
> /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x80)[0x7eda9ea29e40]
> postgres: ashutosh regression [local] SELECT(_start+0x25)[0x5c838be7c025]
> 2025-03-11 11:40:01.696 IST postmaster[303081] LOG: client backend
> (PID 303994) was terminated by signal 6: Aborted
> 2025-03-11 11:40:01.696 IST postmaster[303081] DETAIL: Failed process
> was running: select * from atpgv1;
> I tried to investigate the Assertion, it's failing for property graph
> RTE which is turned into subquery RTE. It has the right lock mode set,
> but I haven't been able to figure out where the lock is supposed to be
> taken or where it's released. If we just prepare the failing query and
> execute the prepared statement, it does not trip the assertion. Will
> investigate it more.
I reproduced the crash using the example Junwang gave.
The problem seems to be that RTEs of rtekind RTE_GRAPH_TABLE are not
handled in AcquireRewriteLocks(). You'll need to add a case for
RTE_GRAPH_TABLE similar to RTE_RELATION in the following switch of
that function:
/*
* First, process RTEs of the current query level.
*/
rt_index = 0;
foreach(l, parsetree->rtable)
{
RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
Relation rel;
LOCKMODE lockmode;
List *newaliasvars;
Index curinputvarno;
RangeTblEntry *curinputrte;
ListCell *ll;
++rt_index;
switch (rte->rtekind)
{
case RTE_RELATION:
which could be as simple as the following (fixes the crash!) or
something that's specific to RTE_GRAPH_TABLE:
diff --git a/src/backend/rewrite/rewriteHandler.c
b/src/backend/rewrite/rewriteHandler.c
index c51dd3d2ee4..8fa6edb90eb 100644
--- a/src/backend/rewrite/rewriteHandler.c
+++ b/src/backend/rewrite/rewriteHandler.c
@@ -174,6 +174,7 @@ AcquireRewriteLocks(Query *parsetree,
switch (rte->rtekind)
{
case RTE_RELATION:
+ case RTE_GRAPH_TABLE:
--
Thanks, Amit Langote
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Amit,
On Tue, Mar 11, 2025 at 5:06 PM Amit Langote wrote:
>
> Hi Ashutosh, Junwang,
>
> On Tue, Mar 11, 2025 at 4:22 PM Ashutosh Bapat
> wrote:
> > On Wed, Feb 26, 2025 at 8:04 PM Junwang Zhao wrote:
> > > I added a trivial fix(v12-0014) that called table_open/table_close in
> > > rewriteGraphTable, it now passed the regression test and cirrus ci test,
> > > but I'm not sure it's the correct fix.
> > >
> > > I hope Ashutosh can chime in and take a look at this problem.
> >
> > 2. Following Assertion is failing, the assertion was added recently.
> > TRAP: failed Assert("IsParallelWorker() ||
> > CheckRelationOidLockedByMe(rte->relid, AccessShareLock, true)"), File:
> > "../../coderoot/pg/src/backend/executor/execMain.c", Line: 695, PID:
> > 303994
> > postgres: ashutosh regression [local]
> > SELECT(ExceptionalCondition+0xbe)[0x5c838c5d7114]
> > postgres: ashutosh regression [local]
> > SELECT(ExecCheckPermissions+0xf8)[0x5c838c11fb9c]
> > postgres: ashutosh regression [local] SELECT(+0x38223f)[0x5c838c12023f]
> > postgres: ashutosh regression [local]
> > SELECT(standard_ExecutorStart+0x2f8)[0x5c838c11f223]
> > postgres: ashutosh regression [local] SELECT(ExecutorStart+0x69)[0x5c838c11ef22]
> > postgres: ashutosh regression [local] SELECT(PortalStart+0x368)[0x5c838c3d991a]
> > postgres: ashutosh regression [local] SELECT(+0x63458e)[0x5c838c3d258e]
> > postgres: ashutosh regression [local] SELECT(PostgresMain+0x9eb)[0x5c838c3d7cf0]
> > postgres: ashutosh regression [local] SELECT(+0x630178)[0x5c838c3ce178]
> > postgres: ashutosh regression [local]
> > SELECT(postmaster_child_launch+0x137)[0x5c838c2da677]
> > postgres: ashutosh regression [local] SELECT(+0x5431b4)[0x5c838c2e11b4]
> > postgres: ashutosh regression [local] SELECT(+0x54076a)[0x5c838c2de76a]
> > postgres: ashutosh regression [local]
> > SELECT(PostmasterMain+0x15f8)[0x5c838c2de04d]
> > postgres: ashutosh regression [local] SELECT(main+0x3a1)[0x5c838c1b12be]
> > /lib/x86_64-linux-gnu/libc.so.6(+0x29d90)[0x7eda9ea29d90]
> > /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x80)[0x7eda9ea29e40]
> > postgres: ashutosh regression [local] SELECT(_start+0x25)[0x5c838be7c025]
> > 2025-03-11 11:40:01.696 IST postmaster[303081] LOG: client backend
> > (PID 303994) was terminated by signal 6: Aborted
> > 2025-03-11 11:40:01.696 IST postmaster[303081] DETAIL: Failed process
> > was running: select * from atpgv1;
> > I tried to investigate the Assertion, it's failing for property graph
> > RTE which is turned into subquery RTE. It has the right lock mode set,
> > but I haven't been able to figure out where the lock is supposed to be
> > taken or where it's released. If we just prepare the failing query and
> > execute the prepared statement, it does not trip the assertion. Will
> > investigate it more.
>
> I reproduced the crash using the example Junwang gave.
>
> The problem seems to be that RTEs of rtekind RTE_GRAPH_TABLE are not
> handled in AcquireRewriteLocks(). You'll need to add a case for
> RTE_GRAPH_TABLE similar to RTE_RELATION in the following switch of
> that function:
>
> /*
> * First, process RTEs of the current query level.
> */
> rt_index = 0;
> foreach(l, parsetree->rtable)
> {
> RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
> Relation rel;
> LOCKMODE lockmode;
> List *newaliasvars;
> Index curinputvarno;
> RangeTblEntry *curinputrte;
> ListCell *ll;
>
> ++rt_index;
> switch (rte->rtekind)
> {
> case RTE_RELATION:
>
> which could be as simple as the following (fixes the crash!) or
> something that's specific to RTE_GRAPH_TABLE:
>
> diff --git a/src/backend/rewrite/rewriteHandler.c
> b/src/backend/rewrite/rewriteHandler.c
> index c51dd3d2ee4..8fa6edb90eb 100644
> --- a/src/backend/rewrite/rewriteHandler.c
> +++ b/src/backend/rewrite/rewriteHandler.c
> @@ -174,6 +174,7 @@ AcquireRewriteLocks(Query *parsetree,
> switch (rte->rtekind)
> {
> case RTE_RELATION:
> + case RTE_GRAPH_TABLE:
>
> --
> Thanks, Amit Langote
I’ve tested the fix, it works and is better than my previous solution.
I will send a new patch set with this improvement, thanks.
--
Regards
Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
Thanks On Tue, Mar 11, 2025 at 7:51 PM Junwang Zhao wrote: > > Here is a new version with Amit's fix and my trivial refactors. > > 0001-0010 is the same as Ashutosh's last email > 0011 is Amit's fix of the crash in ExecCheckPermissions I think that fix is correct and it fixes the crash. I need to think more about it - especially whether there are more places where we are missing RTE_GRAPH_TABLE. But will do that as time permits. > 0012 is a trivial fix that remove the test with default collation, or > it will fail CI, see[1] > 0013-0015 are some trivial fix and refactor, feel free to incorporate > or drop when you review them. > > [1]: https://api.cirrus-ci.com/v1/artifact/task/5290818690351104/testrun/build/testrun/regress/regress/regression.diffs > Thanks Junwang. I have added your patches to my local repository. Next time I post an updated set, I will post it along with your patches. Will merge them into the original patches as time permits. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Ashutosh and Peter,
On Wed, Mar 12, 2025 at 12:31 PM Ashutosh Bapat
wrote:
>
> Thanks
>
> On Tue, Mar 11, 2025 at 7:51 PM Junwang Zhao wrote:
>
> >
> > Here is a new version with Amit's fix and my trivial refactors.
> >
> > 0001-0010 is the same as Ashutosh's last email
> > 0011 is Amit's fix of the crash in ExecCheckPermissions
>
> I think that fix is correct and it fixes the crash. I need to think
> more about it - especially whether there are more places where we are
> missing RTE_GRAPH_TABLE. But will do that as time permits.
>
> > 0012 is a trivial fix that remove the test with default collation, or
> > it will fail CI, see[1]
> > 0013-0015 are some trivial fix and refactor, feel free to incorporate
> > or drop when you review them.
> >
> > [1]: https://api.cirrus-ci.com/v1/artifact/task/5290818690351104/testrun/build/testrun/regress/regress/regression.diffs
> >
>
> Thanks Junwang. I have added your patches to my local repository. Next
> time I post an updated set, I will post it along with your patches.
> Will merge them into the original patches as time permits.
>
> --
> Best Wishes,
> Ashutosh Bapat
Since this PGQ feature won't be in PG 18, I'd like to raise a discussion of
the possibility of implementing the quantifier feature, which I think is a
quite useful feature in the graph database area.
I'll start with a graph definition first.
`Person(id, name, age, sex)` with id as PK
`Knows(id, start_id, end_id, since)` with id as PK, start_id and
end_id FK referencing Person's id
insert into Person values(1, 'A', 31, 'M'), (2, 'B', 30, 'F'), (3,
'C', 33, 'M'), (4, 'D', 31, 'F'), (5, 'E', 32, 'M'), (6, 'F', 33,
'M');
insert into Knows values (1, 1, 2, '2020'); -- A knows B since 2020
insert into Knows values (2, 1, 3, '2021'); -- A knows C since 2021
insert into Knows values (3, 1, 4, '2020'); -- A knows D since 2020
insert into Knows values (4, 2, 4, '2023'); -- B knows D since 2023
insert into Knows values (5, 3, 5, '2022'); -- C knows E since 2022
insert into Knows values (6, 2, 6, '2021'); -- B knows F since 2021
insert into Knows values (7, 4, 6, '2020'); -- D knows F since 2020
Then we create a property graph:
CREATE property graph new_graph
VERTEX TABLES (Person)
EDGE TABLES (Knows);
If we want to find A's non-directly known friends within 3 hops, we can query:
select name from graph_table (new_graph match (a:Person WHERE a.name =
'A') --> (b:Person) --> (c:Person) COLUMNS (c.name))
union
select name from graph_table (new_graph match (a:Person WHERE a.name =
'A') --> (b:Person) -->(c:Person)-->(d:Person) COLUMNS (d.name));
Or if we support quantifier, we can simply the query as:
select name from graph_table (new_graph match (a:Person WHERE a.name =
'A') -->{2,3} (b:Person) COLUMNS (b.name));
In the current design of PostgreSQL, we can rewrite this pattern with
quantifiers to
the union form with some effort.
But what if the pattern is more complicated, for example:
1. select name, since from graph_table (new_graph match (a:Person
WHERE a.name = 'A') -[r:Knows]->{2,3} (b:Person) COLUMNS (b.name,
r.since));
Can we support the r.since column? I guess not, in this case r is a
variable length edge.
2. select name, count from graph_table (new_graph match (a:Person
WHERE a.name = 'A') -[r:Knows]->{2,3} (b:Person) COLUMNS (b.name,
count(r)));
Can we support this count aggregation(this is called horizontal
aggregation in Oracle's pgql)? How can the executor know the length of
the variable length edge?
3. What if the query doesn't specify the Label of edge, and there can
be different edge labels of r, can we easily do the rewrite?
I did some study of the apache age, they have fixed columns for node
labels(id, agtype)
and edge labels(id, source_id, end_id, agtype), agtype is kind of
json. So they can
resolve the above question easily.
Above are just my random thoughts of the quantifier feature, I don't have a copy
of the PGQ standard, so I'd like to hear your opinion about this.
[1] https://pgql-lang.org/spec/1.2/#horizontal-aggregation-using-group-variables
--
Regards
Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
On Sat, Apr 5, 2025 at 6:20 PM Junwang Zhao wrote:
>
> Hi Ashutosh and Peter,
>
> Since this PGQ feature won't be in PG 18, I'd like to raise a discussion of
> the possibility of implementing the quantifier feature, which I think is a
> quite useful feature in the graph database area.
I agree that quantifiers feature is very useful; it's being used in
many usecases. However, it's a bit of a complex feature. IMO, we
should keep that discussion as well as the patch in a separate thread,
so that this patchset doesn't grow too large to review and also
discussion in this thread can remain focused. Once we get the current
patch set reviewed and committed we can tackle the quantifier problem
in a separate discussion. Of course that doesn't mean that we can not
start discussion, try POC and even a working patch for quantifier
support.
Peter may think otherwise.
>
> I'll start with a graph definition first.
>
> `Person(id, name, age, sex)` with id as PK
> `Knows(id, start_id, end_id, since)` with id as PK, start_id and
> end_id FK referencing Person's id
>
> insert into Person values(1, 'A', 31, 'M'), (2, 'B', 30, 'F'), (3,
> 'C', 33, 'M'), (4, 'D', 31, 'F'), (5, 'E', 32, 'M'), (6, 'F', 33,
> 'M');
> insert into Knows values (1, 1, 2, '2020'); -- A knows B since 2020
> insert into Knows values (2, 1, 3, '2021'); -- A knows C since 2021
> insert into Knows values (3, 1, 4, '2020'); -- A knows D since 2020
> insert into Knows values (4, 2, 4, '2023'); -- B knows D since 2023
> insert into Knows values (5, 3, 5, '2022'); -- C knows E since 2022
> insert into Knows values (6, 2, 6, '2021'); -- B knows F since 2021
> insert into Knows values (7, 4, 6, '2020'); -- D knows F since 2020
>
> Then we create a property graph:
>
> CREATE property graph new_graph
> VERTEX TABLES (Person)
> EDGE TABLES (Knows);
>
> If we want to find A's non-directly known friends within 3 hops, we can query:
>
> select name from graph_table (new_graph match (a:Person WHERE a.name =
> 'A') --> (b:Person) --> (c:Person) COLUMNS (c.name))
> union
> select name from graph_table (new_graph match (a:Person WHERE a.name =
> 'A') --> (b:Person) -->(c:Person)-->(d:Person) COLUMNS (d.name));
>
> Or if we support quantifier, we can simply the query as:
>
> select name from graph_table (new_graph match (a:Person WHERE a.name =
> 'A') -->{2,3} (b:Person) COLUMNS (b.name));
>
> In the current design of PostgreSQL, we can rewrite this pattern with
> quantifiers to
> the union form with some effort.
>
> But what if the pattern is more complicated, for example:
>
> 1. select name, since from graph_table (new_graph match (a:Person
> WHERE a.name = 'A') -[r:Knows]->{2,3} (b:Person) COLUMNS (b.name,
> r.since));
> Can we support the r.since column? I guess not, in this case r is a
> variable length edge.
>
> 2. select name, count from graph_table (new_graph match (a:Person
> WHERE a.name = 'A') -[r:Knows]->{2,3} (b:Person) COLUMNS (b.name,
> count(r)));
> Can we support this count aggregation(this is called horizontal
> aggregation in Oracle's pgql)? How can the executor know the length of
> the variable length edge?
>
> 3. What if the query doesn't specify the Label of edge, and there can
> be different edge labels of r, can we easily do the rewrite?
>
> I did some study of the apache age, they have fixed columns for node
> labels(id, agtype)
> and edge labels(id, source_id, end_id, agtype), agtype is kind of
> json. So they can
> resolve the above question easily.
>
> Above are just my random thoughts of the quantifier feature, I don't have a copy
> of the PGQ standard, so I'd like to hear your opinion about this.
>
I think the questions you have raised are valid. If we decide to
discuss this in a separate thread, I will start that thread just by
responding to these questions and design I have in mind.
--
Best Wishes,
Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Ashutosh,
On Mon, Apr 7, 2025 at 1:19 PM Ashutosh Bapat
wrote:
>
> On Sat, Apr 5, 2025 at 6:20 PM Junwang Zhao wrote:
> >
> > Hi Ashutosh and Peter,
> >
> > Since this PGQ feature won't be in PG 18, I'd like to raise a discussion of
> > the possibility of implementing the quantifier feature, which I think is a
> > quite useful feature in the graph database area.
>
> I agree that quantifiers feature is very useful; it's being used in
> many usecases. However, it's a bit of a complex feature. IMO, we
> should keep that discussion as well as the patch in a separate thread,
> so that this patchset doesn't grow too large to review and also
> discussion in this thread can remain focused. Once we get the current
> patch set reviewed and committed we can tackle the quantifier problem
> in a separate discussion. Of course that doesn't mean that we can not
> start discussion, try POC and even a working patch for quantifier
> support.
>
> Peter may think otherwise.
>
> >
> > I'll start with a graph definition first.
> >
> > `Person(id, name, age, sex)` with id as PK
> > `Knows(id, start_id, end_id, since)` with id as PK, start_id and
> > end_id FK referencing Person's id
> >
> > insert into Person values(1, 'A', 31, 'M'), (2, 'B', 30, 'F'), (3,
> > 'C', 33, 'M'), (4, 'D', 31, 'F'), (5, 'E', 32, 'M'), (6, 'F', 33,
> > 'M');
> > insert into Knows values (1, 1, 2, '2020'); -- A knows B since 2020
> > insert into Knows values (2, 1, 3, '2021'); -- A knows C since 2021
> > insert into Knows values (3, 1, 4, '2020'); -- A knows D since 2020
> > insert into Knows values (4, 2, 4, '2023'); -- B knows D since 2023
> > insert into Knows values (5, 3, 5, '2022'); -- C knows E since 2022
> > insert into Knows values (6, 2, 6, '2021'); -- B knows F since 2021
> > insert into Knows values (7, 4, 6, '2020'); -- D knows F since 2020
> >
> > Then we create a property graph:
> >
> > CREATE property graph new_graph
> > VERTEX TABLES (Person)
> > EDGE TABLES (Knows);
> >
> > If we want to find A's non-directly known friends within 3 hops, we can query:
> >
> > select name from graph_table (new_graph match (a:Person WHERE a.name =
> > 'A') --> (b:Person) --> (c:Person) COLUMNS (c.name))
> > union
> > select name from graph_table (new_graph match (a:Person WHERE a.name =
> > 'A') --> (b:Person) -->(c:Person)-->(d:Person) COLUMNS (d.name));
> >
> > Or if we support quantifier, we can simply the query as:
> >
> > select name from graph_table (new_graph match (a:Person WHERE a.name =
> > 'A') -->{2,3} (b:Person) COLUMNS (b.name));
> >
> > In the current design of PostgreSQL, we can rewrite this pattern with
> > quantifiers to
> > the union form with some effort.
> >
> > But what if the pattern is more complicated, for example:
> >
> > 1. select name, since from graph_table (new_graph match (a:Person
> > WHERE a.name = 'A') -[r:Knows]->{2,3} (b:Person) COLUMNS (b.name,
> > r.since));
> > Can we support the r.since column? I guess not, in this case r is a
> > variable length edge.
> >
> > 2. select name, count from graph_table (new_graph match (a:Person
> > WHERE a.name = 'A') -[r:Knows]->{2,3} (b:Person) COLUMNS (b.name,
> > count(r)));
> > Can we support this count aggregation(this is called horizontal
> > aggregation in Oracle's pgql)? How can the executor know the length of
> > the variable length edge?
> >
> > 3. What if the query doesn't specify the Label of edge, and there can
> > be different edge labels of r, can we easily do the rewrite?
> >
> > I did some study of the apache age, they have fixed columns for node
> > labels(id, agtype)
> > and edge labels(id, source_id, end_id, agtype), agtype is kind of
> > json. So they can
> > resolve the above question easily.
> >
> > Above are just my random thoughts of the quantifier feature, I don't have a copy
> > of the PGQ standard, so I'd like to hear your opinion about this.
> >
>
> I think the questions you have raised are valid. If we decide to
> discuss this in a separate thread, I will start that thread just by
> responding to these questions and design I have in mind.
I'm ok with starting a new thread for quantifier discussion, and I'd
really happy to know your design on this.
>
> --
> Best Wishes,
> Ashutosh Bapat
--
Regards
Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
What is the current thinking about getting PGQ committed ?
The attached fixes *ONLY* the duplicate OIDs error to get it build again in CI
On Mon, Apr 7, 2025 at 10:13 AM Junwang Zhao wrote:
>
> Hi Ashutosh,
>
> On Mon, Apr 7, 2025 at 1:19 PM Ashutosh Bapat
> wrote:
> >
> > On Sat, Apr 5, 2025 at 6:20 PM Junwang Zhao wrote:
> > >
> > > Hi Ashutosh and Peter,
> > >
> > > Since this PGQ feature won't be in PG 18, I'd like to raise a discussion of
> > > the possibility of implementing the quantifier feature, which I think is a
> > > quite useful feature in the graph database area.
> >
> > I agree that quantifiers feature is very useful; it's being used in
> > many usecases. However, it's a bit of a complex feature. IMO, we
> > should keep that discussion as well as the patch in a separate thread,
> > so that this patchset doesn't grow too large to review and also
> > discussion in this thread can remain focused. Once we get the current
> > patch set reviewed and committed we can tackle the quantifier problem
> > in a separate discussion. Of course that doesn't mean that we can not
> > start discussion, try POC and even a working patch for quantifier
> > support.
> >
> > Peter may think otherwise.
> >
> > >
> > > I'll start with a graph definition first.
> > >
> > > `Person(id, name, age, sex)` with id as PK
> > > `Knows(id, start_id, end_id, since)` with id as PK, start_id and
> > > end_id FK referencing Person's id
> > >
> > > insert into Person values(1, 'A', 31, 'M'), (2, 'B', 30, 'F'), (3,
> > > 'C', 33, 'M'), (4, 'D', 31, 'F'), (5, 'E', 32, 'M'), (6, 'F', 33,
> > > 'M');
> > > insert into Knows values (1, 1, 2, '2020'); -- A knows B since 2020
> > > insert into Knows values (2, 1, 3, '2021'); -- A knows C since 2021
> > > insert into Knows values (3, 1, 4, '2020'); -- A knows D since 2020
> > > insert into Knows values (4, 2, 4, '2023'); -- B knows D since 2023
> > > insert into Knows values (5, 3, 5, '2022'); -- C knows E since 2022
> > > insert into Knows values (6, 2, 6, '2021'); -- B knows F since 2021
> > > insert into Knows values (7, 4, 6, '2020'); -- D knows F since 2020
> > >
> > > Then we create a property graph:
> > >
> > > CREATE property graph new_graph
> > > VERTEX TABLES (Person)
> > > EDGE TABLES (Knows);
> > >
> > > If we want to find A's non-directly known friends within 3 hops, we can query:
> > >
> > > select name from graph_table (new_graph match (a:Person WHERE a.name =
> > > 'A') --> (b:Person) --> (c:Person) COLUMNS (c.name))
> > > union
> > > select name from graph_table (new_graph match (a:Person WHERE a.name =
> > > 'A') --> (b:Person) -->(c:Person)-->(d:Person) COLUMNS (d.name));
> > >
> > > Or if we support quantifier, we can simply the query as:
> > >
> > > select name from graph_table (new_graph match (a:Person WHERE a.name =
> > > 'A') -->{2,3} (b:Person) COLUMNS (b.name));
> > >
> > > In the current design of PostgreSQL, we can rewrite this pattern with
> > > quantifiers to
> > > the union form with some effort.
> > >
> > > But what if the pattern is more complicated, for example:
> > >
> > > 1. select name, since from graph_table (new_graph match (a:Person
> > > WHERE a.name = 'A') -[r:Knows]->{2,3} (b:Person) COLUMNS (b.name,
> > > r.since));
> > > Can we support the r.since column? I guess not, in this case r is a
> > > variable length edge.
> > >
> > > 2. select name, count from graph_table (new_graph match (a:Person
> > > WHERE a.name = 'A') -[r:Knows]->{2,3} (b:Person) COLUMNS (b.name,
> > > count(r)));
> > > Can we support this count aggregation(this is called horizontal
> > > aggregation in Oracle's pgql)? How can the executor know the length of
> > > the variable length edge?
> > >
> > > 3. What if the query doesn't specify the Label of edge, and there can
> > > be different edge labels of r, can we easily do the rewrite?
> > >
> > > I did some study of the apache age, they have fixed columns for node
> > > labels(id, agtype)
> > > and edge labels(id, source_id, end_id, agtype), agtype is kind of
> > > json. So they can
> > > resolve the above question easily.
> > >
> > > Above are just my random thoughts of the quantifier feature, I don't have a copy
> > > of the PGQ standard, so I'd like to hear your opinion about this.
> > >
> >
> > I think the questions you have raised are valid. If we decide to
> > discuss this in a separate thread, I will start that thread just by
> > responding to these questions and design I have in mind.
>
> I'm ok with starting a new thread for quantifier discussion, and I'd
> really happy to know your design on this.
>
> >
> > --
> > Best Wishes,
> > Ashutosh Bapat
>
>
>
> --
> Regards
> Junwang Zhao
>
>
Re: SQL Property Graph Queries (SQL/PGQ)
On Wed, Mar 12, 2025 at 10:01 AM Ashutosh Bapat wrote: > > > > Thanks Junwang. I have added your patches to my local repository. Next > time I post an updated set, I will post it along with your patches. > Will merge them into the original patches as time permits. I have reviewed your patches. adjusted them as described below. 0001 - is original patch by Peter but it has now accumulated a lot of conflict resolution fixes, compilation fixes and bug fixes. The commit message has a list of all the fixes. 0002 - WHERE clause support in graph pattern 0003 - supports cyclic path patterns 0004 - contains a variety of fixes, described in the commit message 0005 - Fixes access permission checks on property graph 0006 - support collation specification for property and handles collation of vertex - edge quals, this includes Junwang's 0012 and some part of his 0015. The edit related to reducing number of call sites didn't look like a net improvement. Having two callsites each surrounded by the caller's context is better than one. 0007 - pg_overexplain support for property graph (description of GRAPH_TABLE RTE) 0008 - documentation fixes 0009 - support \d variants for property graph, includes Junwang's 0013 0010 - handles RTE_GRAPH_TABLE at some more places. This includes Amit's fix for crash in ExecCheckPermissions. 0011 - deals with functions related to object addresses. It's clear what should be the output of pg_describe_object(), pg_identify_object() and pg_identify_object_as_address() for property graph elements, property graph labels and property graph properties. Those changes are included in the patch. But in order to support those objects in pg_get_object_address() we need to add ObjectTypes corresponding to those objects. Every object that is supported by pg_describe_object(), pg_identify_object() and pg_identify_object_as_address() is not supported by pg_get_object_address(). The objects which are not supported do not have their object types defined in the ObjectTypes enum. E.g. "index column" or "view column" etc. So I have not implemented that support for now. If required, we will need to add the corresponding types in ObjectTypes and then handle them in all the places where ObjectType enum is used. This contains Junwang's 0014. 0012 - A change to in the properties of labels or expression associated with an element property requires the cached plans for queries referring to the corresponding property graph. For that CacheInvalidateHeapTupleCommon() needs to lookup OID of property graph given a Form_pg_propgraph_label_property or Form_pg_propgraph_element_label tuple. These catalogs do not store the property graph OID directly. Instead they store label or property or element oid. From those OIDs it is possible to get the property graph ID from the corresponding label or property or element tuples. However, when tuples in those catalogs are added along with the label, element or property tuples, the latter are not visible. So either we have to add property graph id to pg_propgraph_label_property and pg_propgraph_element_label catalogs or add a CommandCounterIncrement() after inserting element, property or label tuples. The latter may cause some unwanted changes to be visible other than the desired ones, so seems risky. Hence going with the first option. However, that option consumes more space in the catalog. Once the catalog changes are visible, the property graph id in the tuple won't be useful while consuming space. 0013 and 0014 - minimum RLS related tests. In previous patchsets this patch was too large and probably not all tests in that patch were necessary. Now it's broken into two patches .0013 which has extra tests for the combinations. 0014 which I think are tested indirectly in our regression suite. We may include some of those tests in the main patchset. I think two more changes are necessary but not included in the patchset 1. graph_table.sql uses mixed cases in SQL queries (e.g. it uses both SELECT and select). I think we should use a uniform. 2. We have enhanced 002_pg_upgrade.pl to test dump and restore using regression database. I think we should use that facility instead of property graph specific dump/restore tests. Here's the patchset rebased on the latest master. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Ashutosh, On Tue, Jul 22, 2025 at 8:40 PM Ashutosh Bapat wrote: > Here's the patchset rebased on the latest master. Thanks for the update. I was going through the patch series today and had a few comments on the structure that might help with reviewing and eventually committing, whoever ends up doing that. :) I noticed that some functions, like graph_table_property_reference(), are introduced in one patch and then renamed or removed in a later one. It’s easier to review if such refactoring is avoided across patches -- ideally, each patch should introduce code in its final intended form. That also helps reduce the number of patches and makes each one more self-contained. One of the later patches (0004) collects several follow-up changes. While it fixes a real bug -- a crash when GRAPH_TABLE is used inside plpgsql due to a conflict with the columnref hook -- it also includes incidental cleanups like switching to foreach_node(), updating comments, and adjusting function signatures. Those would be better folded into the patches that introduced the relevant code, rather than grouped into a catch-all at the end. That keeps each patch focused and easier to review -- and easier to merge when committing. A general principle that might help: if you're refactoring existing code, a standalone preliminary patch makes sense. But if you're tweaking something just added in the same series, it’s usually better to squash that into the original patch. The rename from graph_table_property_reference() to transformGraphTablePropertyRef() may be a fair exception since it reflects a shift prompted by the bug fix -- but most other adjustments could be folded in without loss of clarity. I understand the intent to spell out each change, but if the details are incidental to the overall design, they don’t necessarily need to be split out. Explaining the reasoning in the thread is always helpful, but consolidating the patches once the design has settled makes things easier for both reviewers and committers. Finally, attaching the patches directly, with versioned names like v8-000x, instead of zipping them helps. Many folks (myself included) will casually skip a zip file because of the small hassle of unzipping just to read a patch. I once postponed reading such a patch and didn’t get back to it for quite a while. :) -- Thanks, Amit Langote
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Andreas, On Sun, Dec 22, 2024 at 3:15 AM Andreas Karlsson wrote: > > On 10/29/24 8:55 PM, Andreas Karlsson wrote: > > I especially dislike the static variable in our patch. And as far as I > > understand it you can avoid the static by changing the lexer to use the > > push parser so it can emit multiple terminal tokens from one parsed > > token, but I have not looked into push parsers and have no idea how this > > would affect performance. > > Updated the patch to remove the static variable. No clue why I thought > that one was necessary. I have not included this patch in the latest patchset. Given that Peter E has written the grammar, it best be handled by him. Please feel free to post it again as an additional patch in the latest patchset. A standalone patch like this confused CI Bot. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Amit, Thanks for your comments On Wed, Jul 23, 2025 at 2:08 PM Amit Langote wrote: > > Hi Ashutosh, > > On Tue, Jul 22, 2025 at 8:40 PM Ashutosh Bapat > wrote: > > Here's the patchset rebased on the latest master. > > Thanks for the update. I was going through the patch series today and > had a few comments on the structure that might help with reviewing and > eventually committing, whoever ends up doing that. :) > > I noticed that some functions, like graph_table_property_reference(), > are introduced in one patch and then renamed or removed in a later > one. It’s easier to review if such refactoring is avoided across > patches -- ideally, each patch should introduce code in its final > intended form. That also helps reduce the number of patches and makes > each one more self-contained. > > One of the later patches (0004) collects several follow-up changes. > While it fixes a real bug -- a crash when GRAPH_TABLE is used inside > plpgsql due to a conflict with the columnref hook -- it also includes > incidental cleanups like switching to foreach_node(), updating > comments, and adjusting function signatures. Those would be better > folded into the patches that introduced the relevant code, rather than > grouped into a catch-all at the end. That keeps each patch focused and > easier to review -- and easier to merge when committing. > > A general principle that might help: if you're refactoring existing > code, a standalone preliminary patch makes sense. But if you're > tweaking something just added in the same series, it’s usually better > to squash that into the original patch. The rename from > graph_table_property_reference() to transformGraphTablePropertyRef() > may be a fair exception since it reflects a shift prompted by the bug > fix -- but most other adjustments could be folded in without loss of > clarity. > > I understand the intent to spell out each change, but if the details > are incidental to the overall design, they don’t necessarily need to > be split out. Explaining the reasoning in the thread is always > helpful, but consolidating the patches once the design has settled > makes things easier for both reviewers and committers. 0001 is almost the same patch that Peter posted almost a year ago. Each of 0002 onwards patches contains logically grouped changes. I have changed 0001 minimally (so that it continues to apply, compile and pass regression). I think this arrangement will make it easy for Peter to review the changes. It will help him understand what all changed since 0001 and each change in its own context. That has led to a lot of overlap between 0002 and 0001 which I think should be squashed together even now. But I would like to know what Peter thinks - what would make his review easier. This arrangement might also help Junwang, who has reviewed some patches, to continue his incremental review. I have rearranged the patches 0002 to 0014 so that the same change isn't revised in multiple patches. Hope that helps. I am also attaching a single patch as well to this email, so that newer reviewers can review the changes as a whole. SQL_PGQ_20250807.zip is separate patches zipped together. SQL_PGQ_one_patch_20250807.zip is a single diff with changes from all the patches squashed together. It's still zipped to avoid the email being held for moderation. > > Finally, attaching the patches directly, with versioned names like > v8-000x, instead of zipping them helps. Many folks (myself included) > will casually skip a zip file because of the small hassle of unzipping > just to read a patch. I once postponed reading such a patch and didn’t > get back to it for quite a while. :) I used to attach those as separate patches till [1], but after that the total size of the patchset grew so much that my emails used to get held back for moderation. So I started attaching zip files. The increase in size is mostly due to the 0014 patch. If we think that it's not needed or can be trimmed down, we will be able to attach the patchset as separate attachments. Here's what changed between the last patchset and this 0001 has some TODOs, FIXMEs and XXXs. I and Junwang had fixed some of them earlier. This patchset fixes some more. Below is my analysis of each of them. + + + + I think we should remove these TODOs since we are not going to support these cases in this patchset. We will add the documentation when we implement these features. +/* + * 15.2 + * PG_DEFINED_LABEL_SETS view + */ + +-- TODO + + +/* + * 15.3 + * PG_DEFINED_LABEL_SET_LABELS view + */ + +-- TODO + + +/* + * 15.4 + * PG_EDGE_DEFINED_LABEL_SETS view + */ + +-- TODO + +/* + * 15.6 + * PG_EDGE_TRIPLETS view + */ + +-- TODO + +/* + * 15.15 + * PG_VERTEX_DEFINED_LABEL_SETS view + */ + +-- TODO All these views are related to the defined label set. IIUC, defined label set is a set of labels which is shared by multiple edges or vertices of a property graph. Please note it's the whole set shared; not just individual labels in the set. In that sense, I think, the labels associated with each edge or vertex table in a property graph form a defined label set. That way the property graph element's OID becomes the defined label set's identifier. I am not sure if this view has any practical use for tabular property graphs. It's not clear to me what these views will contain. Since they are not essential for SQL/PGQ functionality, I have not implemented them. + /* + * Now check number and names. + * + * XXX We could provide more detail in the error messages, but that would + * probably only be useful for some ALTER commands, because otherwise it's + * not really clear which label definition is the wrong one, and so you'd + * have to construct a rather verbose report to be of any use. Let's keep + * it simple for now. + */ Agree with XXX. I think the code is good enough as is. We can leave XXX there in case we expect someone to improve it in future. Otherwise we should remove XXX as well. + + rel = table_open(PropgraphLabelPropertyRelationId, RowShareLock); + ScanKeyInit(&key[0], + Anum_pg_propgraph_label_property_plppropid, + BTEqualStrategyNumber, F_OIDEQ, + ObjectIdGetDatum(propoid)); + scan = systable_beginscan(rel, InvalidOid /* FIXME */ , + true, NULL, 1, key); I think the FIXME is to add the correct index OID. pg_propgraph_label_property_label_prop_index contains plppropid as a key but it's not the first column. So probably some other, yet not defined, index is expected here? +ALTER PROPERTY GRAPH g3 ALTER VERTEX TABLE t3 DROP LABEL t3l3; +ALTER PROPERTY GRAPH g3 DROP VERTEX TABLES (t2); -- fail (TODO: dubious error message) +ERROR: cannot drop vertex t2 of property graph g3 because other objects depend on it +DETAIL: edge e1 of property graph g3 depends on vertex t2 of property graph g3 +HINT: Use DROP ... CASCADE to drop the dependent objects too. I don't see what's dubious about this error message. edge e1 connects t2 and t1. Dropping t2 would leave e1 dangling; error is preventing it. Looks similar to how we prevent a referenced table being dropped. Or is it expected that e1 be dropped without specifying cascade when t2 is dropped since e1 has no existence without t2? Also the patchset fixes the CI failure from the previous patchset. The patches are reordered slightly. Each patch contains a commit message that explains the changes in that patch. [1] https://www.postgresql.org/message-id/CAExHW5sM+ZGVzR1428FsDHuWc-FU2-6zQr5j91KLh6vZaWY0ow@mail.gmail.com -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
I have browsed this patch set a bit to get myself up to date. General thoughts: This is a large patch set, and it's not going to be perfect at the first try. Especially, some of the parsing rules, query semantics, that kind of thing. So I'm thinking that we should aim at integrating this with an understanding that it would be somewhat experimental, and then iterate on some of the details in the tree. Obviously, that would still require that the overall architecture is ok, that it doesn't crash, that it satisfies security requirements. Also, it should as much as possible follow the "if you don't use it, it doesn't affect you" rule. So I'm specifically looking at where the patch intersects with existing code in critical ways, especially in parse analysis. I want to spend more time reviewing that in particular. Much of the rest of patch is almost-boilerplate: New DDL commands, new catalogs, associated tests and documentation. It looks a lot, but most of it is not very surprising. I found two areas where a bit more work could be done to separate the new code from existing code: src/backend/utils/cache/inval.c: This looks suspicious. The existing code only deals with very fundamental catalogs such as pg_class and pg_index. It doesn't feel right to hardcode additional arguably very high-level PGQ-related catalogs there. We should think of a different approach here. src/test/regress/sql/rowsecurity.sql: I think it would be better to separate the new test cases into a separate file. This test file is already large and complicated, and sprinkling a bunch of more stuff all over the place is going to make review and maintenance more complicated. We also need to make sure that property graphs have security features equivalent to views. For example, I suspect we need to integrate them with restrict_nonsystem_relation_kind. There might be other similar things, to be checked.
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Peter, On Mon, Aug 11, 2025 at 7:12 PM Peter Eisentraut wrote: > > I have browsed this patch set a bit to get myself up to date. > > General thoughts: > > This is a large patch set, and it's not going to be perfect at the first > try. Especially, some of the parsing rules, query semantics, that kind > of thing. So I'm thinking that we should aim at integrating this with > an understanding that it would be somewhat experimental, and then > iterate on some of the details in the tree. FWIW, I agree with this plan. > Obviously, that would still > require that the overall architecture is ok, that it doesn't crash, that > it satisfies security requirements. Also, it should as much as possible > follow the "if you don't use it, it doesn't affect you" rule. +1. > > I found two areas where a bit more work could be done to separate the > new code from existing code: > > src/backend/utils/cache/inval.c: This looks suspicious. The existing > code only deals with very fundamental catalogs such as pg_class and > pg_index. It doesn't feel right to hardcode additional arguably very > high-level PGQ-related catalogs there. We should think of a different > approach here. I implemented it that way considering similarity between properties and attributes. But I agree with you. I think it's a matter of calling CacheInvalidateRelcacheByRelid with OID of property graph at appropriate places in AlterPropGraph(), which is the only place where components of the property graph are changed without changing property graph's pg_class tuple. Creating and dropping a property graph will touch the pg_class tuple which will trigger the current invalidation mechanism. > > We also need to make sure that property graphs have security features > equivalent to views. For example, I suspect we need to integrate them > with restrict_nonsystem_relation_kind. There might be other similar > things, to be checked. > Thanks for pointing me to restrict_nonsystem_relation_kind. I can take care of that. Apart from that views have two security related settings - security_invoker and security_barrier. As mentioned in the commit message of 0003, property graphs behave like views with security_invoker set to true. This will avoid any privilege escalations through property graphs. This should be the safest MVP. But it's different from the default security_invoker setting for views. I was thinking that we will integrate the patches with this behaviour and add security_invoker semantics in the next iteration. Please let me know if you think that security_invoker and security_definer semantics should both be supported before the first commit itself. Property graphs do not have security_barrier setting right now. Property graphs do not have any conditions of their own. But GRAPH_TABLE() may have. WHERE conditions in the GRAPH_TABLE are executed like other conditions on the underlying table (if our optimizer can push the conditions below UNION). I guess we need to support security_barrier semantics on property graph so that WHERE conditions in GRAPH_TABLE are executed before other conditions, but it doesn't seem to be critical to me for the first cut as users can leverage security_barrier views for the same, if required. But please let me know if you think that security_barrier semantics should also be supported before the first commit. RLS is already covered. Is there anything that is missing? > > src/test/regress/sql/rowsecurity.sql: I think it would be better to > separate the new test cases into a separate file. This test file is > already large and complicated, and sprinkling a bunch of more stuff all > over the place is going to make review and maintenance more complicated. I sprinkled the queries in that file since the tables, RLS rules, scenarios to test were readily available there. But I agree with you that a file would be better. In fact, it's better to create a separate file graph_table_security.sql for tests related to security aspects of property graph covering RLS, restrict_nonsystem_relation_kind, security_invoker and security_barrier. What do you think? I will work on that. From the first sentence in this email, it seems that you are planning a thorough review of this patch set. Are you waiting for the above issues to be addressed before continuing the review? -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Ashutosh,
Thanks for the new patch set.
On Thu, Aug 7, 2025 at 6:47 PM Ashutosh Bapat
wrote:
>
> Hi Amit,
> Thanks for your comments
>
> On Wed, Jul 23, 2025 at 2:08 PM Amit Langote wrote:
> >
> > Hi Ashutosh,
> >
> > On Tue, Jul 22, 2025 at 8:40 PM Ashutosh Bapat
> > wrote:
> > > Here's the patchset rebased on the latest master.
> >
> > Thanks for the update. I was going through the patch series today and
> > had a few comments on the structure that might help with reviewing and
> > eventually committing, whoever ends up doing that. :)
> >
> > I noticed that some functions, like graph_table_property_reference(),
> > are introduced in one patch and then renamed or removed in a later
> > one. It’s easier to review if such refactoring is avoided across
> > patches -- ideally, each patch should introduce code in its final
> > intended form. That also helps reduce the number of patches and makes
> > each one more self-contained.
> >
> > One of the later patches (0004) collects several follow-up changes.
> > While it fixes a real bug -- a crash when GRAPH_TABLE is used inside
> > plpgsql due to a conflict with the columnref hook -- it also includes
> > incidental cleanups like switching to foreach_node(), updating
> > comments, and adjusting function signatures. Those would be better
> > folded into the patches that introduced the relevant code, rather than
> > grouped into a catch-all at the end. That keeps each patch focused and
> > easier to review -- and easier to merge when committing.
> >
> > A general principle that might help: if you're refactoring existing
> > code, a standalone preliminary patch makes sense. But if you're
> > tweaking something just added in the same series, it’s usually better
> > to squash that into the original patch. The rename from
> > graph_table_property_reference() to transformGraphTablePropertyRef()
> > may be a fair exception since it reflects a shift prompted by the bug
> > fix -- but most other adjustments could be folded in without loss of
> > clarity.
> >
> > I understand the intent to spell out each change, but if the details
> > are incidental to the overall design, they don’t necessarily need to
> > be split out. Explaining the reasoning in the thread is always
> > helpful, but consolidating the patches once the design has settled
> > makes things easier for both reviewers and committers.
>
> 0001 is almost the same patch that Peter posted almost a year ago.
> Each of 0002 onwards patches contains logically grouped changes. I
> have changed 0001 minimally (so that it continues to apply, compile
> and pass regression). I think this arrangement will make it easy for
> Peter to review the changes. It will help him understand what all
> changed since 0001 and each change in its own context. That has led to
> a lot of overlap between 0002 and 0001 which I think should be
> squashed together even now. But I would like to know what Peter thinks
> - what would make his review easier. This arrangement might also help
> Junwang, who has reviewed some patches, to continue his incremental
> review.
>
> I have rearranged the patches 0002 to 0014 so that the same change
> isn't revised in multiple patches. Hope that helps.
>
> I am also attaching a single patch as well to this email, so that
> newer reviewers can review the changes as a whole.
>
> SQL_PGQ_20250807.zip is separate patches zipped together.
> SQL_PGQ_one_patch_20250807.zip is a single diff with changes from all
> the patches squashed together. It's still zipped to avoid the email
> being held for moderation.
>
> >
> > Finally, attaching the patches directly, with versioned names like
> > v8-000x, instead of zipping them helps. Many folks (myself included)
> > will casually skip a zip file because of the small hassle of unzipping
> > just to read a patch. I once postponed reading such a patch and didn’t
> > get back to it for quite a while. :)
>
> I used to attach those as separate patches till [1], but after that
> the total size of the patchset grew so much that my emails used to get
> held back for moderation. So I started attaching zip files. The
> increase in size is mostly due to the 0014 patch. If we think that
> it's not needed or can be trimmed down, we will be able to attach the
> patchset as separate attachments.
>
> Here's what changed between the last patchset and this
>
> 0001 has some TODOs, FIXMEs and XXXs. I and Junwang had fixed some of
> them earlier. This patchset fixes some more. Below is my analysis of
> each of them.
> +
> +
> +
> +
>
> I think we should remove these TODOs since we are not going to support
> these cases in this patchset. We will add the documentation when we
> implement these features.
>
> +/*
> + * 15.2
> + * PG_DEFINED_LABEL_SETS view
> + */
> +
> +-- TODO
> +
> +
> +/*
> + * 15.3
> + * PG_DEFINED_LABEL_SET_LABELS view
> + */
> +
> +-- TODO
> +
> +
> +/*
> + * 15.4
> + * PG_EDGE_DEFINED_LABEL_SETS view
> + */
> +
> +-- TODO
> +
> +/*
> + * 15.6
> + * PG_EDGE_TRIPLETS view
> + */
> +
> +-- TODO
> +
> +/*
> + * 15.15
> + * PG_VERTEX_DEFINED_LABEL_SETS view
> + */
> +
> +-- TODO
>
> All these views are related to the defined label set. IIUC, defined
> label set is a set of labels which is shared by multiple edges or
> vertices of a property graph. Please note it's the whole set shared;
> not just individual labels in the set. In that sense, I think, the
> labels associated with each edge or vertex table in a property graph
> form a defined label set. That way the property graph element's OID
> becomes the defined label set's identifier. I am not sure if this view
> has any practical use for tabular property graphs. It's not clear to
> me what these views will contain. Since they are not essential for
> SQL/PGQ functionality, I have not implemented them.
>
> + /*
> + * Now check number and names.
> + *
> + * XXX We could provide more detail in the error messages, but that would
> + * probably only be useful for some ALTER commands, because otherwise it's
> + * not really clear which label definition is the wrong one, and so you'd
> + * have to construct a rather verbose report to be of any use. Let's keep
> + * it simple for now.
> + */
>
> Agree with XXX. I think the code is good enough as is. We can leave
> XXX there in case we expect someone to improve it in future. Otherwise
> we should remove XXX as well.
>
> +
> + rel = table_open(PropgraphLabelPropertyRelationId, RowShareLock);
> + ScanKeyInit(&key[0],
> + Anum_pg_propgraph_label_property_plppropid,
> + BTEqualStrategyNumber, F_OIDEQ,
> + ObjectIdGetDatum(propoid));
> + scan = systable_beginscan(rel, InvalidOid /* FIXME */ ,
> + true, NULL, 1, key);
>
> I think the FIXME is to add the correct index OID.
> pg_propgraph_label_property_label_prop_index contains plppropid as a
> key but it's not the first column. So probably some other, yet not
> defined, index is expected here?
>
> +ALTER PROPERTY GRAPH g3 ALTER VERTEX TABLE t3 DROP LABEL t3l3;
> +ALTER PROPERTY GRAPH g3 DROP VERTEX TABLES (t2); -- fail (TODO:
> dubious error message)
> +ERROR: cannot drop vertex t2 of property graph g3 because other
> objects depend on it
> +DETAIL: edge e1 of property graph g3 depends on vertex t2 of property graph g3
> +HINT: Use DROP ... CASCADE to drop the dependent objects too.
>
> I don't see what's dubious about this error message. edge e1 connects
> t2 and t1. Dropping t2 would leave e1 dangling; error is preventing
> it. Looks similar to how we prevent a referenced table being dropped.
> Or is it expected that e1 be dropped without specifying cascade when
> t2 is dropped since e1 has no existence without t2?
>
> Also the patchset fixes the CI failure from the previous patchset.
>
> The patches are reordered slightly. Each patch contains a commit
> message that explains the changes in that patch.
>
> [1] https://www.postgresql.org/message-id/CAExHW5sM+ZGVzR1428FsDHuWc-FU2-6zQr5j91KLh6vZaWY0ow@mail.gmail.com
>
>
>
>
>
> --
> Best Wishes,
> Ashutosh Bapat
I have some review comments, and hope some of them are helpful.
1.
doc/src/sgml/ddl.sgml
+
+CREATE PROPERTY GRAPH myshop
+ VERTEX TABLES (
+ products LABEL product,
+ customers LABEL customer,
+ orders LABEL order
+ )
+ EDGE TABLES (
+ order_items SOURCE orders DESTINATION products LABEL contains,
+ customer_orders SOURCE customers DESTINATION orders LABEL has
+ );
+
order is a reserved keyword, so the following example will fail, we
should not give a wrong example in our document.
2.
doc/src/sgml/information_schema.sgml
+ <literal>pg_element_table_key_columns</literal>
+
+
+ The view pg_element_key_columns identifies which columns
+ are part of the keys of the element tables of property graphs defined in
+ the current database. Only those property graphs are shown that the
+ current user has access to (by way of being the owner or having some
+ privilege).
+
+ <literal>pg_element_table_properties</literal>
+
+
+ The view pg_element_table_labels shows the definitions
+ of the properties for the element tables of property graphs defined in the
+ current database. Only those property graphs are shown that the current
+ user has access to (by way of being the owner or having some privilege).
+
the and the <para> doesn't match.
3.
doc/src/sgml/queries.sgml
+ <para>
+ A path pattern thus matches a sequence of vertices and edges. The
+ simplest possible path pattern is
+<programlisting>
+()
+</programlisting>
+ which matches a single vertex. The next simplest pattern would be
+<programlisting>
+()-[]->()
+</programlisting>
+ which matches a vertex followed by an edge followed by a vertex. The
+ characters <literal>()</literal> are a vertex pattern and the characters
+ <literal>-[]-></literal> are an edge pattern.
+ </para>
the description seems wrong, when a user writes (), it should match
all vertices in a property graph, for example:
explain SELECT customer_name FROM GRAPH_TABLE (myshop MATCH () COLUMNS
(1 AS customer_name));
[local] zjw@postgres:5432-73666=# explain SELECT customer_name FROM
GRAPH_TABLE (myshop MATCH () COLUMNS (1 AS customer_name));
QUERY PLAN
------------------------------------------------------------------
Append (cost=0.00..89.40 rows=3960 width=4)
-> Seq Scan on customers (cost=0.00..18.50 rows=850 width=4)
-> Seq Scan on orders (cost=0.00..32.60 rows=2260 width=4)
-> Seq Scan on products (cost=0.00..18.50 rows=850 width=4)
(4 rows)
4.
doc/src/sgml/ref/create_property_graph.sgml
+<programlisting>
+CREATE PROPERTY GRAPH g1
+ VERTEX TABLES (
+ v1 LABEL foo PROPERTIES (x AS a * 2) LABEL bar PROPERTIES (x AS a * 2)
+ ) ...
+</programlisting>
+ but this would not:
+<programlisting>
+CREATE PROPERTY GRAPH g1
+ VERTEX TABLES (
+ v1 LABEL foo PROPERTIES (x AS a * 2) LABEL bar PROPERTIES (x AS a * 10)
+ ) ...
+</programlisting></para>
The expr after PROPERTIES should be (a * 2 AS x)
5.
src/backend/catalog/sql_features.txt
+G034 Path concatenation YES SQL/PGQ required
Do we support path concatenation?
+G070 Label expression: label disjunction NO SQL/PGQ required
I think this should be a YES?
6.
src/backend/commands/tablecmds.c
The description RenameRelation and RemoveRelations should adapt
property graph, below are diffs I suggest:
/*
- * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/MATERIALIZED VIEW/FOREIGN TABLE
+ * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/MATERIALIZED VIEW/FOREIGN
TABLE/PROPERTY GRAPH
* RENAME
*/
ObjectAddress
@@ -4210,8 +4210,8 @@ RenameRelation(RenameStmt *stmt)
/*
* Grab an exclusive lock on the target table, index, sequence, view,
- * materialized view, or foreign table, which we will NOT release until
- * end of transaction.
+ * materialized view, foreign table or property graph, which we will NOT
+ * release until end of transaction.
/*
* RemoveRelations
* Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW,
- * DROP MATERIALIZED VIEW, DROP FOREIGN TABLE
+ * DROP MATERIALIZED VIEW, DROP FOREIGN TABLE, DROP PROPERTY GRAPH
7.
src/backend/nodes/nodeFuncs.c
exprLocation should have an arm for T_GraphPropertyRef? I suggest:
@@ -1811,6 +1811,9 @@ exprLocation(const Node *expr)
case T_PartitionRangeDatum:
loc = ((const PartitionRangeDatum *) expr)->location;
break;
+ case T_GraphPropertyRef:
+ loc = ((const GraphPropertyRef *) expr)->location;
+ break;
8.
src/backend/rewrite/rewriteGraphTable.c
patch 0002
+ /*
+ * Label expressions from two element patterns need to be
+ * conjucted. Label conjuction is not supported right now
typo, should be conjuncted and conjunction.
9.
The line length of some code is quite long, which isn't ideal, but
it's not a major issue. It can be formatted before being committed.
BTW, the patch set seems not to apply to the current master.
I will go another round of review of the test cases, thanks.
--
Regards
Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Junwang, On Sun, Aug 31, 2025 at 4:35 PM Junwang Zhao wrote: > > > I have some review comments, and hope some of them are helpful. > > 1. > > doc/src/sgml/ddl.sgml > > + > +CREATE PROPERTY GRAPH myshop > + VERTEX TABLES ( > + products LABEL product, > + customers LABEL customer, > + orders LABEL order > + ) > + EDGE TABLES ( > + order_items SOURCE orders DESTINATION products LABEL contains, > + customer_orders SOURCE customers DESTINATION orders LABEL has > + ); > + > > order is a reserved keyword, so the following example will fail, we > should not give a wrong example in our document. > I tried those examples and they all worked. What error are you getting? What is not working for you? > 2. > > doc/src/sgml/information_schema.sgml > > + <literal>pg_element_table_key_columns</literal> > + > + > + The view pg_element_key_columns identifies which columns > + are part of the keys of the element tables of property graphs defined in > + the current database. Only those property graphs are shown that the > + current user has access to (by way of being the owner or having some > + privilege). > + > > > + <literal>pg_element_table_properties</literal> > + > + > + The view pg_element_table_labels shows the definitions > + of the properties for the element tables of property graphs defined in the > + current database. Only those property graphs are shown that the current > + user has access to (by way of being the owner or having some privilege). > + > > the and the <para> doesn't match. Don't understand this. What isn't matching here. May be provide a patch with what you think is correct. > > 3. > > doc/src/sgml/queries.sgml > > + <para> > + A path pattern thus matches a sequence of vertices and edges. The > + simplest possible path pattern is > +<programlisting> > +() > +</programlisting> > + which matches a single vertex. The next simplest pattern would be > +<programlisting> > +()-[]->() > +</programlisting> > + which matches a vertex followed by an edge followed by a vertex. The > + characters <literal>()</literal> are a vertex pattern and the characters > + <literal>-[]-></literal> are an edge pattern. > + </para> > > the description seems wrong, when a user writes (), it should match > all vertices in a property graph, for example: This description is a continuation of the previous sentence. It should be read as "() which matches a single vertex (in a sequence of vertices and edges)." See how the next sentence is written. This looks ok to me. > > 4. > > doc/src/sgml/ref/create_property_graph.sgml > > +<programlisting> > +CREATE PROPERTY GRAPH g1 > + VERTEX TABLES ( > + v1 LABEL foo PROPERTIES (x AS a * 2) LABEL bar PROPERTIES (x AS a * 2) > + ) ... > +</programlisting> > + but this would not: > +<programlisting> > +CREATE PROPERTY GRAPH g1 > + VERTEX TABLES ( > + v1 LABEL foo PROPERTIES (x AS a * 2) LABEL bar PROPERTIES (x AS a * 10) > + ) ... > +</programlisting></para> > > The expr after PROPERTIES should be (a * 2 AS x) Good catch. Fixed. > > 5. > > src/backend/catalog/sql_features.txt > > +G034 Path concatenation YES SQL/PGQ required > > Do we support path concatenation? I don't think so. But let Peter confirm it. > > +G070 Label expression: label disjunction NO SQL/PGQ required > > I think this should be a YES? Nice catch. Fixed. > > 6. > > src/backend/commands/tablecmds.c > > The description RenameRelation and RemoveRelations should adapt > property graph, below are diffs I suggest: > > /* > - * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/MATERIALIZED VIEW/FOREIGN TABLE > + * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/MATERIALIZED VIEW/FOREIGN > TABLE/PROPERTY GRAPH > * RENAME > */ > ObjectAddress > @@ -4210,8 +4210,8 @@ RenameRelation(RenameStmt *stmt) > > /* > * Grab an exclusive lock on the target table, index, sequence, view, > - * materialized view, or foreign table, which we will NOT release until > - * end of transaction. > + * materialized view, foreign table or property graph, which we will NOT > + * release until end of transaction. > > > /* > * RemoveRelations > * Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW, > - * DROP MATERIALIZED VIEW, DROP FOREIGN TABLE > + * DROP MATERIALIZED VIEW, DROP FOREIGN TABLE, DROP PROPERTY GRAPH > Nice catch. Fixed. > 7. > > src/backend/nodes/nodeFuncs.c > > exprLocation should have an arm for T_GraphPropertyRef? I suggest: > > @@ -1811,6 +1811,9 @@ exprLocation(const Node *expr) > case T_PartitionRangeDatum: > loc = ((const PartitionRangeDatum *) expr)->location; > break; > + case T_GraphPropertyRef: > + loc = ((const GraphPropertyRef *) expr)->location; > + break; > > 8. > > src/backend/rewrite/rewriteGraphTable.c > > patch 0002 > > + /* > + * Label expressions from two element patterns need to be > + * conjucted. Label conjuction is not supported right now > > typo, should be conjuncted and conjunction. Done and improved that comment a bit. Attaching the patchset with the next email. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Hi, Sending the email again since my earlier email was held for moderation because of patchset size. Attached as a zip here. On Thu, Nov 20, 2025 at 8:31 PM Ashutosh Bapat wrote: > > On Mon, Aug 18, 2025 at 5:01 PM Ashutosh Bapat > wrote: > > > > > > > > > I found two areas where a bit more work could be done to separate the > > > new code from existing code: > > > > > > src/backend/utils/cache/inval.c: This looks suspicious. The existing > > > code only deals with very fundamental catalogs such as pg_class and > > > pg_index. It doesn't feel right to hardcode additional arguably very > > > high-level PGQ-related catalogs there. We should think of a different > > > approach here. > > > > I implemented it that way considering similarity between properties > > and attributes. But I agree with you. I think it's a matter of calling > > CacheInvalidateRelcacheByRelid with OID of property graph at > > appropriate places in AlterPropGraph(), which is the only place where > > components of the property graph are changed without changing property > > graph's pg_class tuple. Creating and dropping a property graph will > > touch the pg_class tuple which will trigger the current invalidation > > mechanism. > > > > Done. > > > > > > > We also need to make sure that property graphs have security features > > > equivalent to views. For example, I suspect we need to integrate them > > > with restrict_nonsystem_relation_kind. There might be other similar > > > things, to be checked. > > > > > > > Thanks for pointing me to restrict_nonsystem_relation_kind. I can take > > care of that. > > Reading commit message of 66e94448abec3aad04faf0a79cab4881ae08e08a > which introduced this GUC and CVE > https://www.postgresql.org/support/security/CVE-2024-7348/, it does > not seem likely that property graphs can be used that way. SELECT * > FROM will end up in an error. A property graph > reference is allowed only in GRAPH_TABLE(), which pg_dump does not > use. Do you have something else in mind? > > As part of this investigation, I found that a property graph reference > outside GRAPH_TABLE does throw error, but from unexpected places. > Added error messages in addRangeTableEntry and > addRangeTableEntryForRelation instead. > > > Apart from that views have two security related settings > > - security_invoker and security_barrier. > > > > As mentioned in the commit message of 0003, property graphs behave > > like views with security_invoker set to true. This will avoid any > > privilege escalations through property graphs. This should be the > > safest MVP. But it's different from the default security_invoker > > setting for views. I was thinking that we will integrate the patches > > with this behaviour and add security_invoker semantics in the next > > iteration. Please let me know if you think that security_invoker and > > security_definer semantics should both be supported before the first > > commit itself. > > > > Property graphs do not have security_barrier setting right now. > > Property graphs do not have any conditions of their own. But > > GRAPH_TABLE() may have. WHERE conditions in the GRAPH_TABLE are > > executed like other conditions on the underlying table (if our > > optimizer can push the conditions below UNION). I guess we need to > > support security_barrier semantics on property graph so that WHERE > > conditions in GRAPH_TABLE are executed before other conditions, but it > > doesn't seem to be critical to me for the first cut as users can > > leverage security_barrier views for the same, if required. But please > > let me know if you think that security_barrier semantics should also > > be supported before the first commit. > > > > RLS is already covered. > > > > Is there anything that is missing? > > Waiting for your response here. > > > > > > > > > > src/test/regress/sql/rowsecurity.sql: I think it would be better to > > > separate the new test cases into a separate file. This test file is > > > already large and complicated, and sprinkling a bunch of more stuff all > > > over the place is going to make review and maintenance more complicated. > > > > I sprinkled the queries in that file since the tables, RLS rules, > > scenarios to test were readily available there. But I agree with you > > that a file would be better. In fact, it's better to create a separate > > file graph_table_security.sql for tests related to security aspects of > > property graph covering RLS, restrict_nonsystem_relation_kind, > > security_invoker and security_barrier. What do you think? I will work > > on that. > > Done. Added a new test file graph_table_rls.sql. in 0012. > > -- > Best Wishes, > Ashutosh Bapat -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Ashutosh,
On Thu, Nov 20, 2025 at 11:01 PM Ashutosh Bapat
wrote:
>
> Hi Junwang,
>
> On Sun, Aug 31, 2025 at 4:35 PM Junwang Zhao wrote:
> >
> >
> > I have some review comments, and hope some of them are helpful.
> >
> > 1.
> >
> > doc/src/sgml/ddl.sgml
> >
> > +
> > +CREATE PROPERTY GRAPH myshop
> > + VERTEX TABLES (
> > + products LABEL product,
> > + customers LABEL customer,
> > + orders LABEL order
> > + )
> > + EDGE TABLES (
> > + order_items SOURCE orders DESTINATION products LABEL contains,
> > + customer_orders SOURCE customers DESTINATION orders LABEL has
> > + );
> > +
> >
> > order is a reserved keyword, so the following example will fail, we
> > should not give a wrong example in our document.
> >
>
> I tried those examples and they all worked. What error are you
> getting? What is not working for you?
Here is what I got, pay attention to the queries with singular `order`, it's a
reserved keyword.
[local] zjw@postgres:5432-24494=# CREATE PROPERTY GRAPH myshop
VERTEX TABLES (
products LABEL product,
customers LABEL customer,
orders LABEL order
)
EDGE TABLES (
order_items SOURCE orders DESTINATION products LABEL contains,
customer_orders SOURCE customers DESTINATION orders LABEL has
);
ERROR: syntax error at or near "order"
LINE 5: orders LABEL order
^
Time: 1.369 ms
[local] zjw@postgres:5432-24494=# SELECT customer_name FROM
GRAPH_TABLE (myshop MATCH (c:customer)-[:has]->(o:order WHERE
o.ordered_when = current_date) COLUMNS (c.name AS customr_name));
ERROR: syntax error at or near "order"
LINE 1: ...GRAPH_TABLE (myshop MATCH (c:customer)-[:has]->(o:order WHER...
^
Time: 0.999 ms
>
> > 2.
> >
> > doc/src/sgml/information_schema.sgml
> >
> > + <literal>pg_element_table_key_columns</literal>
> > +
> > +
> > + The view pg_element_key_columns identifies which columns
> > + are part of the keys of the element tables of property graphs defined in
> > + the current database. Only those property graphs are shown that the
> > + current user has access to (by way of being the owner or having some
> > + privilege).
> > +
> >
> >
> > + <literal>pg_element_table_properties</literal>
> > +
> > +
> > + The view pg_element_table_labels shows the definitions
> > + of the properties for the element tables of property graphs defined in the
> > + current database. Only those property graphs are shown that the current
> > + user has access to (by way of being the owner or having some privilege).
> > +
> >
> > the and the <para> doesn't match.
>
> Don't understand this. What isn't matching here. May be provide a
> patch with what you think is correct.
I checked this again, I think I'm wrong about this, sorry about that.
>
> >
> > 3.
> >
> > doc/src/sgml/queries.sgml
> >
> > + <para>
> > + A path pattern thus matches a sequence of vertices and edges. The
> > + simplest possible path pattern is
> > +<programlisting>
> > +()
> > +</programlisting>
> > + which matches a single vertex. The next simplest pattern would be
> > +<programlisting>
> > +()-[]->()
> > +</programlisting>
> > + which matches a vertex followed by an edge followed by a vertex. The
> > + characters <literal>()</literal> are a vertex pattern and the characters
> > + <literal>-[]-></literal> are an edge pattern.
> > + </para>
> >
> > the description seems wrong, when a user writes (), it should match
> > all vertices in a property graph, for example:
>
> This description is a continuation of the previous sentence. It should
> be read as "() which matches a single vertex (in a sequence of
> vertices and edges)." See how the next sentence is written. This
> looks ok to me.
Sure, WFM.
>
> >
> > 4.
> >
> > doc/src/sgml/ref/create_property_graph.sgml
> >
> > +<programlisting>
> > +CREATE PROPERTY GRAPH g1
> > + VERTEX TABLES (
> > + v1 LABEL foo PROPERTIES (x AS a * 2) LABEL bar PROPERTIES (x AS a * 2)
> > + ) ...
> > +</programlisting>
> > + but this would not:
> > +<programlisting>
> > +CREATE PROPERTY GRAPH g1
> > + VERTEX TABLES (
> > + v1 LABEL foo PROPERTIES (x AS a * 2) LABEL bar PROPERTIES (x AS a * 10)
> > + ) ...
> > +</programlisting></para>
> >
> > The expr after PROPERTIES should be (a * 2 AS x)
>
> Good catch. Fixed.
>
> >
> > 5.
> >
> > src/backend/catalog/sql_features.txt
> >
> > +G034 Path concatenation YES SQL/PGQ required
> >
> > Do we support path concatenation?
>
> I don't think so. But let Peter confirm it.
>
> >
> > +G070 Label expression: label disjunction NO SQL/PGQ required
> >
> > I think this should be a YES?
>
> Nice catch. Fixed.
>
> >
> > 6.
> >
> > src/backend/commands/tablecmds.c
> >
> > The description RenameRelation and RemoveRelations should adapt
> > property graph, below are diffs I suggest:
> >
> > /*
> > - * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/MATERIALIZED VIEW/FOREIGN TABLE
> > + * Execute ALTER TABLE/INDEX/SEQUENCE/VIEW/MATERIALIZED VIEW/FOREIGN
> > TABLE/PROPERTY GRAPH
> > * RENAME
> > */
> > ObjectAddress
> > @@ -4210,8 +4210,8 @@ RenameRelation(RenameStmt *stmt)
> >
> > /*
> > * Grab an exclusive lock on the target table, index, sequence, view,
> > - * materialized view, or foreign table, which we will NOT release until
> > - * end of transaction.
> > + * materialized view, foreign table or property graph, which we will NOT
> > + * release until end of transaction.
> >
> >
> > /*
> > * RemoveRelations
> > * Implements DROP TABLE, DROP INDEX, DROP SEQUENCE, DROP VIEW,
> > - * DROP MATERIALIZED VIEW, DROP FOREIGN TABLE
> > + * DROP MATERIALIZED VIEW, DROP FOREIGN TABLE, DROP PROPERTY GRAPH
> >
>
> Nice catch. Fixed.
>
> > 7.
> >
> > src/backend/nodes/nodeFuncs.c
> >
> > exprLocation should have an arm for T_GraphPropertyRef? I suggest:
> >
> > @@ -1811,6 +1811,9 @@ exprLocation(const Node *expr)
> > case T_PartitionRangeDatum:
> > loc = ((const PartitionRangeDatum *) expr)->location;
> > break;
> > + case T_GraphPropertyRef:
> > + loc = ((const GraphPropertyRef *) expr)->location;
> > + break;
> >
> > 8.
> >
> > src/backend/rewrite/rewriteGraphTable.c
> >
> > patch 0002
> >
> > + /*
> > + * Label expressions from two element patterns need to be
> > + * conjucted. Label conjuction is not supported right now
> >
> > typo, should be conjuncted and conjunction.
>
> Done and improved that comment a bit.
>
> Attaching the patchset with the next email.
>
> --
> Best Wishes,
> Ashutosh Bapat
--
Regards
Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Junwang, On Mon, Nov 24, 2025 at 8:01 AM Junwang Zhao wrote: > > Hi Ashutosh, > > On Thu, Nov 20, 2025 at 11:01 PM Ashutosh Bapat > wrote: > > > > Hi Junwang, > > > > On Sun, Aug 31, 2025 at 4:35 PM Junwang Zhao wrote: > > > > > > > > > I have some review comments, and hope some of them are helpful. > > > > > > 1. > > > > > > doc/src/sgml/ddl.sgml > > > > > > + > > > +CREATE PROPERTY GRAPH myshop > > > + VERTEX TABLES ( > > > + products LABEL product, > > > + customers LABEL customer, > > > + orders LABEL order > > > + ) > > > + EDGE TABLES ( > > > + order_items SOURCE orders DESTINATION products LABEL contains, > > > + customer_orders SOURCE customers DESTINATION orders LABEL has > > > + ); > > > + > > > > > > order is a reserved keyword, so the following example will fail, we > > > should not give a wrong example in our document. > > > > > > > I tried those examples and they all worked. What error are you > > getting? What is not working for you? > > Here is what I got, pay attention to the queries with singular `order`, it's a > reserved keyword. I see it now. Sorry for missing it earlier. I think something like attached should fix the problem, if we want to continue with the current example. FWIW, it demos that quotes can be used with labels, but we don't necessarily do that with other objects. I am not sure whether Peter would like to continue with the example or use a different one avoiding this subtlety altogether. Hence not including it in the overall patchset. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Mon, Nov 24, 2025 at 1:00 PM Ashutosh Bapat wrote: > > Hi Junwang, > > On Mon, Nov 24, 2025 at 8:01 AM Junwang Zhao wrote: > > > > Hi Ashutosh, > > > > On Thu, Nov 20, 2025 at 11:01 PM Ashutosh Bapat > > wrote: > > > > > > Hi Junwang, > > > > > > On Sun, Aug 31, 2025 at 4:35 PM Junwang Zhao wrote: > > > > > > > > > > > > I have some review comments, and hope some of them are helpful. > > > > > > > > 1. > > > > > > > > doc/src/sgml/ddl.sgml > > > > > > > > + > > > > +CREATE PROPERTY GRAPH myshop > > > > + VERTEX TABLES ( > > > > + products LABEL product, > > > > + customers LABEL customer, > > > > + orders LABEL order > > > > + ) > > > > + EDGE TABLES ( > > > > + order_items SOURCE orders DESTINATION products LABEL contains, > > > > + customer_orders SOURCE customers DESTINATION orders LABEL has > > > > + ); > > > > + > > > > > > > > order is a reserved keyword, so the following example will fail, we > > > > should not give a wrong example in our document. > > > > > > > > > > I tried those examples and they all worked. What error are you > > > getting? What is not working for you? > > > > Here is what I got, pay attention to the queries with singular `order`, it's a > > reserved keyword. > > I see it now. Sorry for missing it earlier. > > I think something like attached should fix the problem, if we want to > continue with the current example. FWIW, it demos that quotes can be > used with labels, but we don't necessarily do that with other objects. > I am not sure whether Peter would like to continue with the example or > use a different one avoiding this subtlety altogether. Hence not > including it in the overall patchset. > The patch WFM. Using a different one also works, maybe we can adopt part of the schema from LDBC SNB [1] [1] https://ldbcouncil.org/benchmarks/snb/ > > -- > Best Wishes, > Ashutosh Bapat -- Regards Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
I have done a rough review of the patch set version 20251120.
- There are "No newline at end of file" warnings from git diff for a
couple of files:
contrib/pg_overexplain/sql/pg_overexplain.sql
src/test/regress/sql/graph_table_rls.sql
Please fix those in the next patch set, and maybe check your editor
settings.
- Attached are two small patches with some small fixes I found in
passing. (I think some of them were also reported by Junwang Zhao in
the meantime.)
- In the test files, especially src/test/regress/sql/graph_table.sql,
there are wildly different SQL styles (capitalization, formatting) used,
depending on who added the test case (I guess). Let's keep that more
consistent.
- In src/backend/parser/analyze.c, the extracted function
constructSetOpTargetlist() needs a detailed comment.
- I'm not so sure about the semantics chosen in the patch "Access
permissions on property graph". I think according to the SQL standard,
once you have access to the property graph, you don't need access to the
underlying tables as well. I guess you did this to align with how views
work? We might need to think about this a bit more, and document
whatever the conclusion is. But for now it's just small amount of code
affected.
I think you could collapse all the patches into one patch now. I have
reviewed all the incremental patches and they all look ok to me. I have
made some notes about which things I want to review in more detail, such
as the access control issue, but that doesn't need to be kept as a
separate patch.
When you create future patches, consider using the git format-patch -v
option.
And then you can also just gzip the patch. That should make it even
smaller than the .zip file.
Re: SQL Property Graph Queries (SQL/PGQ)
On 20.11.25 16:00, Ashutosh Bapat wrote: >> 5. >> >> src/backend/catalog/sql_features.txt >> >> +G034 Path concatenation YES SQL/PGQ required >> >> Do we support path concatenation? > I don't think so. But let Peter confirm it. AFAICT, path concatenation just allows that you can write multiple element patterns in a row, like ()-[]->(). I don't see how it could make sense to not support that.
Re: SQL Property Graph Queries (SQL/PGQ)
On 24.11.25 06:00, Ashutosh Bapat wrote: > I think something like attached should fix the problem, if we want to > continue with the current example. FWIW, it demos that quotes can be > used with labels, but we don't necessarily do that with other objects. > I am not sure whether Peter would like to continue with the example or > use a different one avoiding this subtlety altogether. Hence not > including it in the overall patchset. Let's just quote it. I think this example set is nice because it is aligned with examples used elsewhere in the ddl.sgml chapter, such as foreign keys and as of recently temporal tables.
Re: SQL Property Graph Queries (SQL/PGQ)
On Tue, Nov 25, 2025 at 9:58 PM Peter Eisentraut wrote:
>
> On 20.11.25 16:00, Ashutosh Bapat wrote:
> >> 5.
> >>
> >> src/backend/catalog/sql_features.txt
> >>
> >> +G034 Path concatenation YES SQL/PGQ required
> >>
> >> Do we support path concatenation?
> > I don't think so. But let Peter confirm it.
>
> AFAICT, path concatenation just allows that you can write multiple
> element patterns in a row, like ()-[]->(). I don't see how it could
> make sense to not support that.
Yeah, I just took a look at the SQL/PGQ standard
::=
Now I understand, thanks.
--
Regards
Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
On Tue, Nov 25, 2025 at 7:28 PM Peter Eisentraut wrote: > > On 20.11.25 16:00, Ashutosh Bapat wrote: > >> 5. > >> > >> src/backend/catalog/sql_features.txt > >> > >> +G034 Path concatenation YES SQL/PGQ required > >> > >> Do we support path concatenation? > > I don't think so. But let Peter confirm it. > > AFAICT, path concatenation just allows that you can write multiple > element patterns in a row, like ()-[]->(). I don't see how it could > make sense to not support that. Ah! I confused path concatenation with either path pattern list or path pattern multiset alternation. Sorry. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Tue, Nov 25, 2025 at 7:22 PM Peter Eisentraut wrote: > > I have done a rough review of the patch set version 20251120. > > - There are "No newline at end of file" warnings from git diff for a > couple of files: > > contrib/pg_overexplain/sql/pg_overexplain.sql > src/test/regress/sql/graph_table_rls.sql > > Please fix those in the next patch set, and maybe check your editor > settings. I was assuming that pg_indent will fix it or at least git diff --check will show it. But it seems only git diff shows it. I am trying to find a way to automate the task of detection of such warnings. Is `git diff | grep '^\\'` a good way to highlight the existence of such warnings? It still won't show the file which contains those warnings. I didn't find a non-cumbersome way to list the files where such warnings exist. Any ideas? > > - Attached are two small patches with some small fixes I found in > passing. (I think some of them were also reported by Junwang Zhao in > the meantime.) > Included in the attached patch. > - In the test files, especially src/test/regress/sql/graph_table.sql, > there are wildly different SQL styles (capitalization, formatting) used, > depending on who added the test case (I guess). Let's keep that more > consistent. Done. I have also fixed some inconsistent styles in create_property_graph.sql and examined other modified SQL files. I have done a couple rounds of fixing inconsistencies, so there shouldn't be many (if not none) remaining now. privileges.sql already uses inconsistent styles. The new changes there just match the surrounding style. Also removed the DROP SCHEMA statement from graph_table.sql and create_property_graph.sql but left the command behind. > > - In src/backend/parser/analyze.c, the extracted function > constructSetOpTargetlist() needs a detailed comment. I have added a prologue to this function, describing what it does. There are detailed comments in the function itself, which cover the "how" and "why" part. Let me know if this suffices. > > - I'm not so sure about the semantics chosen in the patch "Access > permissions on property graph". I think according to the SQL standard, > once you have access to the property graph, you don't need access to the > underlying tables as well. I guess you did this to align with how views > work? We might need to think about this a bit more, and document > whatever the conclusion is. But for now it's just small amount of code > affected. Section 7.1 Access rules seem to just require that the session user should have SELECT privileges on the property graph. I didn't find an answer to the question: What privileges should be used while accessing the element tables. Application of RLS policies depends upon the answer, for example. They can be either the owner's privileges (security_definer semantics) or the privileges of session user (security_invoker semantics). A view can define what data it exposes precisely upto a row and column; hence a security_definer view can be made safer. But a property graph can not constrain rows that it exposes. So I feel, by default, security_invoker semantics are safer for property graphs. We may support security_definer semantics later, but it has to be an explicit choice by the user. There's another deviation from standard. Section 11.19, Access rule 2 and General rule 4 talk about the privileges on the element tables required by the owner of the property graph. AFAIU, Access rule 2 and General Rule 4 together say that the owner of the property graph (per Syntax rule 9), should have SELECT permission on every column that is mentioned in the property graph definition, SELECT permission on every element table. It does not require the property graph owner to be the owner of the element tables. But patch 0001, in the previous patchset, requires that the owner of the property graph should be the owner of the element tables or superuser. Assume two users u1 and u2, both with CREATE permissions on schema public. postgres@147235=#set session authorization u1; SET postgres@147235=#create table t1 (a int, b int); CREATE TABLE postgres@147235=#set session authorization u2; SET postgres@147235=#create property GRAPH g1 vertex tables (t1 key (a)); ERROR: must be owner of table t1 postgres@147235=#set session authorization u1; SET postgres@147235=#create property GRAPH g1 vertex tables (t1 key (a)); CREATE PROPERTY GRAPH However, the owner may transfer the ownership to another user who need not be the owner of the element tables #alter property graph g1 owner to u2; ALTER PROPERTY GRAPH CreatePropGraph() does not mention the reason behind this choice. Should we remove this constraint and implement what the standard says? If we allow any user to create a property graph containing elements owned by other users per the standard, those users in turn may extend their privileges to other users who do not have access to those tables, if we don't implement security_invoker semantics. That's another reason why behaviour as implemented in the patch. I have added following comment in generate_query_for_graph_path() /* * Create RangeTblEntry for this element table. * * SQL/PGQ standard (Ref. Section 11.19, Access rule 2 and General rule * 4) does not specify whose access privileges to use when accessing the * element tables: property graph owner's or current user's. It is safer * to use current user's privileges so as not to make property graphs as * a hole for unpriviledged data access. This is inline with the views * being security_invoker by default. */ The documentation of CREATE PROPERTY GRAPH already has Access to the base relations underlying the GRAPH_TABLE clause is determined by the permissions of the user executing the query, rather than the property graph owner. Thus, the user of a property graph must have the relevant permissions on the property graph and base relations underlying the GRAPH_TABLE clause. Any other place which needs documentation? > > I think you could collapse all the patches into one patch now. I have > reviewed all the incremental patches and they all look ok to me. I have > made some notes about which things I want to review in more detail, such > as the access control issue, but that doesn't need to be kept as a > separate patch. > Ok. Attached only a single patch. I have consolidated the earlier commit messages in the Notes section of the collapsed patch for future reference. I don't think we need those detailed comments in the final commit message. However, parts may be useful. We should also remove WIP from the commit message subject line, but that can be done just before commit. > When you create future patches, consider using the git format-patch -v > option. > I am still using timestamp as a version but passing it to -v instead of treating it as a suffix. I like datestamp as versionstamp for the reasons mentioned upthread. > And then you can also just gzip the patch. That should make it even > smaller than the .zip file. > This time the total patch size seems to be below 1MB, so hopefully it will not attract moderator's attention. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Tue, Dec 2, 2025 at 3:30 PM Ashutosh Bapat wrote: > > On Tue, Nov 25, 2025 at 7:22 PM Peter Eisentraut wrote: > > > > > - I'm not so sure about the semantics chosen in the patch "Access > > permissions on property graph". I think according to the SQL standard, > > once you have access to the property graph, you don't need access to the > > underlying tables as well. I guess you did this to align with how views > > work? We might need to think about this a bit more, and document > > whatever the conclusion is. But for now it's just small amount of code > > affected. > > Section 7.1 Access rules seem to just require that the session user > should have SELECT privileges on the property graph. I didn't find an > answer to the question: What privileges should be used while accessing > the element tables. Application of RLS policies depends upon the > answer, for example. They can be either the owner's privileges > (security_definer semantics) or the privileges of session user > (security_invoker semantics). A view can define what data it exposes > precisely upto a row and column; hence a security_definer view can be > made safer. But a property graph can not constrain rows that it > exposes. So I feel, by default, security_invoker semantics are safer > for property graphs. We may support security_definer semantics later, > but it has to be an explicit choice by the user. A view definition contains all the functions, operators and objects which will be accessed when executing the view. However, when creating a property graph, the user creating it, can not restrict the functions, operators or other objects which will be used in the GRAPH_TABLE clause. If we allow security_definer property graphs, a malicious user can use it easily to escalate privileges. So, I think supporting security_defined semantic on a property graph is very dangerous. We should allow only security_invoker semantics. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Thu, Dec 4, 2025 at 2:23 AM Ashutosh Bapat wrote: > On Tue, Dec 2, 2025 at 3:30 PM Ashutosh Bapat > wrote: > > On Tue, Nov 25, 2025 at 7:22 PM Peter Eisentraut wrote: > > > > > > > > - I'm not so sure about the semantics chosen in the patch "Access > > > permissions on property graph". I think according to the SQL standard, > > > once you have access to the property graph, you don't need access to the > > > underlying tables as well. I guess you did this to align with how views > > > work? We might need to think about this a bit more, and document > > > whatever the conclusion is. But for now it's just small amount of code > > > affected. > > > > Section 7.1 Access rules seem to just require that the session user > > should have SELECT privileges on the property graph. I didn't find an > > answer to the question: What privileges should be used while accessing > > the element tables. Application of RLS policies depends upon the > > answer, for example. They can be either the owner's privileges > > (security_definer semantics) or the privileges of session user > > (security_invoker semantics). A view can define what data it exposes > > precisely upto a row and column; hence a security_definer view can be > > made safer. But a property graph can not constrain rows that it > > exposes. So I feel, by default, security_invoker semantics are safer > > for property graphs. We may support security_definer semantics later, > > but it has to be an explicit choice by the user. > > A view definition contains all the functions, operators and objects > which will be accessed when executing the view. However, when creating > a property graph, the user creating it, can not restrict the > functions, operators or other objects which will be used in the > GRAPH_TABLE clause. If we allow security_definer property graphs, a > malicious user can use it easily to escalate privileges. So, I think > supporting security_defined semantic on a property graph is very > dangerous. We should allow only security_invoker semantics. +1 for invoker semantics as the default initially, and work on adding a security-definer option if that’s needed in the future, which I imagine might be trickier than what we have for views, not sure. In your commit message: 4. We have not implemented security definer property graphs since SQL/PGQ standard does not mention those. My reading of the access rules is that, from the caller’s point of view, the standard expects behavior that is quite close to security-definer semantics -- once the session user has SELECT on the property graph, they do not need privileges on the element tables. Is that also how you read it, or do you see the standard as intentionally leaving room for invoker semantics like you've currently implemented? -- Thanks, Amit Langote
Re: SQL Property Graph Queries (SQL/PGQ)
On Mon, Dec 8, 2025 at 5:56 PM Amit Langote wrote: > > On Thu, Dec 4, 2025 at 2:23 AM Ashutosh Bapat > > In your commit message: > > 4. We have not implemented security definer property graphs since > SQL/PGQ standard does not mention those. > > My reading of the access rules is that, from the caller’s point of > view, the standard expects behavior that is quite close to > security-definer semantics -- once the session user has SELECT on the > property graph, they do not need privileges on the element tables. Is > that also how you read it, or do you see the standard as intentionally > leaving room for invoker semantics like you've currently implemented? > The standard specifies that in order to reference a property graph in the query, the query invoker has to have SELECT privileges on the property graph. I am not able to find a specification which answers: who's privileges should be used to access the underlying tables. So I can't say whether it's close to security-definer semantics or not. I also can not infer any intent. But as I have explained above, security-definer semantics seem to be too dangerous to implement. But may be there's some other safe interpretation of standard specification, which I am missing. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On 02.12.25 11:00, Ashutosh Bapat wrote: >> When you create future patches, consider using the git format-patch -v >> option. >> > I am still using timestamp as a version but passing it to -v instead > of treating it as a suffix. I like datestamp as versionstamp for the > reasons mentioned upthread. Date stamps are great, but why is there a hyphen between the "v" and the number? I have committed the parse.pl patch, mainly to test it out so that we don't have surprises later. (I had problems in the past making it work with older Perl versions, but things seems to have shifted forward now.) It can live on its own, I think. It looks like undirected matching -[ ]- (without arrows) doesn't work correctly. It seems to just match in one direction. I don't see any tests. Is this implemented? Also, make sure the role names in graph_table_rls.sql start with regress_: CREATE USER graph_rls_alice NOLOGIN; +WARNING: roles created by regression test cases should have names starting with "regress_" (This is the FreeBSD CI failure.)
Re: SQL Property Graph Queries (SQL/PGQ)
On Mon, Dec 8, 2025 at 9:24 PM Peter Eisentraut wrote: > > On 02.12.25 11:00, Ashutosh Bapat wrote: > >> When you create future patches, consider using the git format-patch -v > >> option. > >> > > I am still using timestamp as a version but passing it to -v instead > > of treating it as a suffix. I like datestamp as versionstamp for the > > reasons mentioned upthread. > > Date stamps are great, but why is there a hyphen between the "v" and the > number? I was using -v= instead of -v . Fixed. > > I have committed the parse.pl patch, mainly to test it out so that we > don't have surprises later. (I had problems in the past making it work > with older Perl versions, but things seems to have shifted forward now.) > It can live on its own, I think. +1. Buildfarm seems to be happy with the change. > > It looks like undirected matching -[ ]- (without arrows) doesn't work > correctly. It seems to just match in one direction. I don't see any > tests. Is this implemented? > -[]- is called full edge any direction ::= ~[]~ is defined as full edge undirected ::= The patch supports full edge any direction since [1] in response to Ajay Pal's report. Such a pattern matches edges in both the directions. There's also a test -- edges directed in both ways - to and from v2 SELECT * FROM GRAPH_TABLE (g1 MATCH (v1 IS vl2)-[conn]-(v2) COLUMNS (v1.vname AS v1name, conn.ename AS cname, v2.vname AS v2name)); v1name | cname | v2name --------+-------+-------- v21 | e122 | v12 v22 | e121 | v11 v22 | e231 | v32 (3 rows) SELECT * FROM GRAPH_TABLE (g1 MATCH (v1 IS vl2)-(v2) COLUMNS (v1.vname AS v1name, v2.vname AS v2name)); v1name | v2name --------+-------- v21 | v12 v22 | v11 v22 | v32 (3 rows) it's matching edges to and from vertices in v2. For example e121 is an edge from v11 to v22 whereas e231 is an edge from v22 to v32. We do not support full edge undirected. gram.y doesn't have grammar for the same. In fact, I don't think we have a way to specify undirected edges in the property graph DDL itself. Do you think we should implement ~[ ] ~? > Also, make sure the role names in graph_table_rls.sql start with regress_: > > CREATE USER graph_rls_alice NOLOGIN; > +WARNING: roles created by regression test cases should have names > starting with "regress_" > > (This is the FreeBSD CI failure.) > Thanks for pointing that out. I can reproduce the failure on my laptop. Fixed in the attached patch. I have used regress_graph_rls_ as a user or role name prefix. It's a bit long but I see other tests also using longer names regress_file_fdw_superuser. If we want a shorter name we could use regress_pg_rls (pg: for property graph) but that can be easily confused with PostgreSQL. [1] https://www.postgresql.org/message-id/CAExHW5vqo7iTcVznspb3HHD87Ps3Q%3DJF6_gg%2Bh5mhyuwhd3Q4Q%40mail.gmail.com -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On 09.12.25 11:21, Ashutosh Bapat wrote: >> It looks like undirected matching -[ ]- (without arrows) doesn't work >> correctly. It seems to just match in one direction. I don't see any >> tests. Is this implemented? >> > -[]- is called full edge any direction > ::= > > > ~[]~ is defined as full edge undirected > ::= > > > The patch supports full edge any direction since [1] in response to > Ajay Pal's report. Such a pattern matches edges in both the > directions. There's also a test > -- edges directed in both ways - to and from v2 > SELECT * FROM GRAPH_TABLE (g1 MATCH (v1 IS vl2)-[conn]-(v2) COLUMNS > (v1.vname AS v1name, conn.ename AS cname, v2.vname AS v2name)); > v1name | cname | v2name > --------+-------+-------- > v21 | e122 | v12 > v22 | e121 | v11 > v22 | e231 | v32 > (3 rows) > > SELECT * FROM GRAPH_TABLE (g1 MATCH (v1 IS vl2)-(v2) COLUMNS (v1.vname > AS v1name, v2.vname AS v2name)); > v1name | v2name > --------+-------- > v21 | v12 > v22 | v11 > v22 | v32 > (3 rows) > > it's matching edges to and from vertices in v2. For example e121 is an > edge from v11 to v22 whereas e231 is an edge from v22 to v32. Attached is a test case from an Oracle web site (the URL is in the file). At the end there are three queries, one left, one right, one any direction. The latter should result in the union of the first two, but it doesn't.
Re: SQL Property Graph Queries (SQL/PGQ)
On Sun, Dec 14, 2025 at 1:28 AM Peter Eisentraut wrote: > > On 09.12.25 11:21, Ashutosh Bapat wrote: > >> It looks like undirected matching -[ ]- (without arrows) doesn't work > >> correctly. It seems to just match in one direction. I don't see any > >> tests. Is this implemented? > >> > > -[]- is called full edge any direction > > ::= > > > > > > ~[]~ is defined as full edge undirected > > ::= > > > > > > The patch supports full edge any direction since [1] in response to > > Ajay Pal's report. Such a pattern matches edges in both the > > directions. There's also a test > > -- edges directed in both ways - to and from v2 > > SELECT * FROM GRAPH_TABLE (g1 MATCH (v1 IS vl2)-[conn]-(v2) COLUMNS > > (v1.vname AS v1name, conn.ename AS cname, v2.vname AS v2name)); > > v1name | cname | v2name > > --------+-------+-------- > > v21 | e122 | v12 > > v22 | e121 | v11 > > v22 | e231 | v32 > > (3 rows) > > > > SELECT * FROM GRAPH_TABLE (g1 MATCH (v1 IS vl2)-(v2) COLUMNS (v1.vname > > AS v1name, v2.vname AS v2name)); > > v1name | v2name > > --------+-------- > > v21 | v12 > > v22 | v11 > > v22 | v32 > > (3 rows) > > > > it's matching edges to and from vertices in v2. For example e121 is an > > edge from v11 to v22 whereas e231 is an edge from v22 to v32. > > Attached is a test case from an Oracle web site (the URL is in the > file). At the end there are three queries, one left, one right, one any > direction. The latter should result in the union of the first two, but > it doesn't. Thanks for the example. I see it now. The code, in previous patch, works when the vertices adjacent to an edge come from different tables. In such a case only right or left direction is possible. When the adjacent vertices of an edge come from the same table edge can be from left or right and we need to match both the directions. The edge link quals should have conditions for edges in both directions connected by OR. Done that way in the attached patch. Also added a few more queries containing edges in any direction. I also noticed the following mistakes in the patch and fixed those. 1. e3_3 entry for property graph g1 in graph_table.sql was using the same column as both source and destination key. Fixed that to use appropriate columns. 2. When GRAPH_TABLE has no conditions whatsoever, e.g. GRAPH_TABLE (g1 MATCH () COLUMNS (1)), generate_query_for_graph_path() constructed a bool expression representing NIL quals. This does not cause a problem since somewhere down the line, a bool expression without any clause is appropriately replaced with true or false. However, it crashed when passed through pg_get_querydef() since get_rule_expr() calls linitial on expr->args without checking for NIL-ness. Fixed the construction of bool expression in generate_query_for_graph_path(). rewriteGraphTable() has following code #if 0 elog(INFO, "rewritten:\n%s", pg_get_querydef(copyObject(parsetree), false)); #endif Do we want to remove it or keep it with some note or under #ifdef DEBUG_GRAPH_TABLE_REWRITE or some such? I am mildly leaning towards keeping it under the #ifdef, but not a whole lot. Anybody who wants to debug can add that single line, if they want. I have added the fixes as a separate 0002 patch. Once reviewed I will squash it into 0001 in the next round. Rebased patches on the latest HEAD which required me to move graph_table.sql to another parallel group. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Mon, Dec 15, 2025 at 6:43 PM Ashutosh Bapat wrote: > > > Rebased patches on the latest HEAD which required me to move > graph_table.sql to another parallel group. Huh, the movement resulted in losing that test from parallel_schedule. Fixed in the attached patches. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On 17.12.25 06:32, Ashutosh Bapat wrote: > On Mon, Dec 15, 2025 at 6:43 PM Ashutosh Bapat > wrote: >> >> Rebased patches on the latest HEAD which required me to move >> graph_table.sql to another parallel group. > > Huh, the movement resulted in losing that test from parallel_schedule. > Fixed in the attached patches. A couple of items: 1) I was running some tests that involved properties with mismatching typmods, and I got an error message like ERROR: property "p1" data type modifier mismatch: 14 vs. 19 but the actual types were varchar(10) and varchar(15). So to improve that, we need to run these through the typmod formatting routines, not just print the raw typmod numbers. I actually just combined that with the check for the type itself. Also, there was no test covering this, so I added one. See attached patches. I did another investigation about whether this level of checking is necessary. I think according to the letter of the SQL standard, the typmods must indeed match. It seems Oracle does not check (the example mentioned above came from an Oracle source). But I think it's okay to keep the check. In PostgreSQL, it is much less common to write like varchar(1000). And we can always consider relaxing it later. 2) I had it in my notes to consider whether we should support the colon syntax for label expressions. I think we might have talked about that before. I'm now leaning toward not supporting it in the first iteration. I don't know that we have fully explored possible conflicts with host variable syntax in ecpg and psql and the like. Maybe avoid that for now. There was also a bit of an inconsistency in the presentation: The documentation introduced the colon as seemingly the preferred syntax, but ruleutils.c dumped out the IS syntax. (It was also a bit curious that some test code put spaces around the colon, which is not idiomatic.) Looking around at other implementations: Oracle does not support it; DuckDB supports it, but it doesn't seem to be very up to date, so I don't know what the thinking there is; Google does support it, but it seems their syntax is more of a PGQ-GQL hybrid, so it's not a good reference. Attached is a patch that shows how to revert the colon support. It's pretty simple, and it would be easy to add it back in later, I think.
Re: SQL Property Graph Queries (SQL/PGQ)
On Wed, Dec 17, 2025 at 2:28 PM Peter Eisentraut wrote: > > On 17.12.25 06:32, Ashutosh Bapat wrote: > > On Mon, Dec 15, 2025 at 6:43 PM Ashutosh Bapat > > wrote: > >> > >> Rebased patches on the latest HEAD which required me to move > >> graph_table.sql to another parallel group. > > > > Huh, the movement resulted in losing that test from parallel_schedule. > > Fixed in the attached patches. > > A couple of items: > > 1) I was running some tests that involved properties with mismatching > typmods, and I got an error message like > > ERROR: property "p1" data type modifier mismatch: 14 vs. 19 > > but the actual types were varchar(10) and varchar(15). So to improve > that, we need to run these through the typmod formatting routines, not > just print the raw typmod numbers. I actually just combined that with > the check for the type itself. Also, there was no test covering this, > so I added one. See attached patches. +1. The error message is better. > > I did another investigation about whether this level of checking is > necessary. I think according to the letter of the SQL standard, the > typmods must indeed match. It seems Oracle does not check (the example > mentioned above came from an Oracle source). But I think it's okay to > keep the check. In PostgreSQL, it is much less common to write like > varchar(1000). And we can always consider relaxing it later. +1. Attached patch adds a couple more test statements. > > 2) I had it in my notes to consider whether we should support the colon > syntax for label expressions. I think we might have talked about that > before. > > I'm now leaning toward not supporting it in the first iteration. I > don't know that we have fully explored possible conflicts with host > variable syntax in ecpg and psql and the like. Maybe avoid that for now. > I was aware of ecpg and I vaguely remember we fixed something in ECPG to allow : in MATCH statement. Probably following changes in psqlscan.l and pgc.l -self [,()\[\].;\:\+\-\*\/\%\^\<\>\=] +self [,()\[\].;\:\|\+\-\*\/\%\^\<\>\=] Those changes add | after : (and not the : itself) so maybe they are not about supporting : . Do you remember what those are? However, I see that : in psql can be a problem #create table t1 (a int, b int); #create property graph g1 vertex tables (t1 key (a)); #select * from GRAPH_TABLE (g1 MATCH (a :t1) COLUMNS (a.a)); a --- (0 rows) #\set t1 blank #select * from GRAPH_TABLE (g1 MATCH (a :t1) COLUMNS (a.a)); ERROR: syntax error at or near "blank" LINE 1: select * from GRAPH_TABLE (g1 MATCH (a blank) COLUMNS (a.a))... > There was also a bit of an inconsistency in the presentation: The > documentation introduced the colon as seemingly the preferred syntax, > but ruleutils.c dumped out the IS syntax. > > (It was also a bit curious that some test code put spaces around the > colon, which is not idiomatic.) > That might have been just me trying to type one letter less and yet keeping the query readable. A column between variable name and the label is not always noticeable. > Attached is a patch that shows how to revert the colon support. It's > pretty simple, and it would be easy to add it back in later, I think. I agree that it's better not to support it now. It requires more work and it's optional. When we come to support it, we will need thorough testing. I spotted some examples that use : in ddl.sgml. SELECT customer_name FROM GRAPH_TABLE (myshop MATCH (c:customer)-[:has]->(o:"order" WHERE o.ordered_when = current_date) COLUMNS (c.name AS customer_name)); The query demonstrates that one can use label names in a way that will make the pattern look like an English sentence. Replacing : with IS defeats that purpose. As written in that paragraph, the labels serve the purpose of exposing the table with a different logical view (using different label and property names). So we need that paragraph, but I think we should change the example to use IS instead of :. Attached is suggested minimal change, but I am not happy with it. Another possibility is we completely remove that paragraph; I don't think we need to discuss all possible usages the users will come up with. The patch changes one more instance of : by IS. But that's straight forward. In ddl.sgml I noticed a seemingly incomplete sentence A property graph is a way to represent database contents, instead of using relational structures such as tables. Represent the contents as what? I feel the complete sentence should be one of the following property graph is a way to represent database contents as a graph, instead of representing those as relational structures OR property graph is another way to represent database contents instead of using relational structures such as tables But I can't figure out what was originally intended. I have squashed 0002 from my earlier patchset and your 3 patches into 0001. 0002 has extra tests mentioned above. It also removes "TODO: dubious error message" from a comment. I don't see anything dubious in the error message. I think this patch is safe to be merged into 0001. 0003 is changed to ddl.sgml. Those need a bit more work as described above. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Hi hackers,
Apologies for jumping into the SQL/PGQ discussion mid-stream. I've been
working on implementing the LABELS() graph element function and ran into
an issue I'd like to get some guidance on.
== What LABELS() does ==
LABELS(element_variable) returns a text[] array containing all labels
associated with a graph element. For example:
SELECT * FROM GRAPH_TABLE (myshop
MATCH (n IS customers)
COLUMNS (n.name, LABELS(n) AS lbls)
);
name | lbls
------------+-------------
customer1 | {customers}
customer2 | {customers}
== Implementation approach ==
A naive approach would return LABELS() as a constant (e.g., ARRAY['customers']
directly). However, this prevents the optimizer from pushing down predicates
involving LABELS() through UNION ALL branches.
To enable optimizer pushdown, I wrap each element table in a subquery that
adds a virtual __labels__ column containing a constant array. This way,
LABELS(n) returns a Var referencing that column, allowing the optimizer to
evaluate it per-branch and prune accordingly:
-- Conceptually, the rewrite produces:
SELECT name, __labels__ AS lbls FROM (
SELECT *, ARRAY['customers']::text[] AS __labels__ FROM customers
) ...
This allows the optimizer to perform constant folding and prune UNION ALL
branches when filtering by label:
-- Filter in outer WHERE clause
EXPLAIN SELECT * FROM GRAPH_TABLE (myshop
MATCH (n IS lists) -- lists label shared by orders and wishlists
COLUMNS (LABELS(n) AS lbls, n.node_id)
) WHERE 'orders' = ANY(lbls);
QUERY PLAN
------------------------------------------------------
Seq Scan on orders
Output: '{orders,lists}'::text[], orders.order_id
-- Filter in MATCH WHERE clause without IS (both tables scanned)
EXPLAIN SELECT * FROM GRAPH_TABLE (myshop
MATCH (n) WHERE 'lists' = ANY(LABELS(n))
COLUMNS (LABELS(n) AS lbls, n.node_id)
);
QUERY PLAN
------------------------------------------------------
Append
-> Seq Scan on orders
Output: '{orders,lists}'::text[], orders.order_id
-> Seq Scan on wishlists
Output: '{lists,wishlists}'::text[], wishlists.wishlist_id
The first example prunes the wishlists branch since 'orders' is not in its
label set. The second example uses LABELS() without an IS clause to filter
across all element tables that have the 'lists' label.
== The problem ==
The subquery wrapping breaks column-level privilege checking.
Test case from privileges.sql:
-- regress_priv_user4 has SELECT on atest5(one, four) only
-- lttc label maps atest5.three -> lttck (no privilege)
SET ROLE regress_priv_user4;
SELECT * FROM graph_table (ptg1 MATCH (v IS lttc) COLUMNS (v.lttck));
-- Expected: ERROR: permission denied for table atest5
-- Actual: query succeeds (returns rows without error)
I haven't yet identified the exact root cause of this issue. Has anyone
encountered a similar issue? Any pointers would be appreciated.
Thanks,
Henson
On Wed, Dec 17, 2025 at 2:28 PM Peter Eisentraut <peter@eisentraut.org> wrote:
>
> On 17.12.25 06:32, Ashutosh Bapat wrote:
> > On Mon, Dec 15, 2025 at 6:43 PM Ashutosh Bapat
> > <ashutosh.bapat.oss@gmail.com> wrote:
> >>
> >> Rebased patches on the latest HEAD which required me to move
> >> graph_table.sql to another parallel group.
> >
> > Huh, the movement resulted in losing that test from parallel_schedule.
> > Fixed in the attached patches.
>
> A couple of items:
>
> 1) I was running some tests that involved properties with mismatching
> typmods, and I got an error message like
>
> ERROR: property "p1" data type modifier mismatch: 14 vs. 19
>
> but the actual types were varchar(10) and varchar(15). So to improve
> that, we need to run these through the typmod formatting routines, not
> just print the raw typmod numbers. I actually just combined that with
> the check for the type itself. Also, there was no test covering this,
> so I added one. See attached patches.
+1. The error message is better.
>
> I did another investigation about whether this level of checking is
> necessary. I think according to the letter of the SQL standard, the
> typmods must indeed match. It seems Oracle does not check (the example
> mentioned above came from an Oracle source). But I think it's okay to
> keep the check. In PostgreSQL, it is much less common to write like
> varchar(1000). And we can always consider relaxing it later.
+1.
Attached patch adds a couple more test statements.
>
> 2) I had it in my notes to consider whether we should support the colon
> syntax for label expressions. I think we might have talked about that
> before.
>
> I'm now leaning toward not supporting it in the first iteration. I
> don't know that we have fully explored possible conflicts with host
> variable syntax in ecpg and psql and the like. Maybe avoid that for now.
>
I was aware of ecpg and I vaguely remember we fixed something in ECPG
to allow : in MATCH statement. Probably following changes in
psqlscan.l and pgc.l
-self [,()\[\].;\:\+\-\*\/\%\^\<\>\=]
+self [,()\[\].;\:\|\+\-\*\/\%\^\<\>\=]
Those changes add | after : (and not the : itself) so maybe they are
not about supporting : . Do you remember what those are?
However, I see that : in psql can be a problem
#create table t1 (a int, b int);
#create property graph g1 vertex tables (t1 key (a));
#select * from GRAPH_TABLE (g1 MATCH (a :t1) COLUMNS (a.a));
a
---
(0 rows)
#\set t1 blank
#select * from GRAPH_TABLE (g1 MATCH (a :t1) COLUMNS (a.a));
ERROR: syntax error at or near "blank"
LINE 1: select * from GRAPH_TABLE (g1 MATCH (a blank) COLUMNS (a.a))...
> There was also a bit of an inconsistency in the presentation: The
> documentation introduced the colon as seemingly the preferred syntax,
> but ruleutils.c dumped out the IS syntax.
>
> (It was also a bit curious that some test code put spaces around the
> colon, which is not idiomatic.)
>
That might have been just me trying to type one letter less and yet
keeping the query readable. A column between variable name and the
label is not always noticeable.
> Attached is a patch that shows how to revert the colon support. It's
> pretty simple, and it would be easy to add it back in later, I think.
I agree that it's better not to support it now. It requires more work
and it's optional. When we come to support it, we will need thorough
testing.
I spotted some examples that use : in ddl.sgml.
<programlisting>
SELECT customer_name FROM GRAPH_TABLE (myshop MATCH
(c:customer)-[:has]->(o:"order" WHERE o.ordered_when = current_date)
COLUMNS (c.name AS customer_name));
</programlisting>
The query demonstrates that one can use label names in a way that will
make the pattern look like an English sentence. Replacing : with IS
defeats that purpose.
As written in that paragraph, the labels serve the purpose of exposing
the table with a different logical view (using different label and
property names). So we need that paragraph, but I think we should
change the example to use IS instead of :. Attached is suggested
minimal change, but I am not happy with it. Another possibility is we
completely remove that paragraph; I don't think we need to discuss all
possible usages the users will come up with.
The patch changes one more instance of : by IS. But that's straight forward.
In ddl.sgml I noticed a seemingly incomplete sentence
A property graph is a way to represent database contents, instead of using
relational structures such as tables.
Represent the contents as what? I feel the complete sentence should be
one of the following
property graph is a way to represent database contents as a graph,
instead of representing those as relational structures OR
property graph is another way to represent database contents instead
of using relational structures such as tables
But I can't figure out what was originally intended.
I have squashed 0002 from my earlier patchset and your 3 patches into 0001.
0002 has extra tests mentioned above. It also removes "TODO: dubious
error message" from a comment. I don't see anything dubious in the
error message. I think this patch is safe to be merged into 0001.
0003 is changed to ddl.sgml. Those need a bit more work as described above.
--
Best Wishes,
Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
1. LABELS() function
- Returns text[] of element labels
- Fixed privilege checking from previous version
- Enables optimizer pushdown for branch pruning
2. PROPERTY_NAMES() function
- Returns text[] of property names
- Similar approach to LABELS()
3. Multiple path patterns
- Syntax: MATCH (a)->(b), (b)->(c)
- Implements SQL/PGQ standard feature (was TODO)
Patches attached.
Best regards,
Henson Choi
---
Background: Currently at Inzent (PostgreSQL-based TDE). Previously
at AgensGraph (PostgreSQL-based graph DB, 2017-2020).
Subject: Re: SQL Property Graph Queries (SQL/PGQ)
Hi hackers,
Apologies for jumping into the SQL/PGQ discussion mid-stream. I've been
working on implementing the LABELS() graph element function and ran into
an issue I'd like to get some guidance on.
== What LABELS() does ==
LABELS(element_variable) returns a text[] array containing all labels
associated with a graph element. For example:
SELECT * FROM GRAPH_TABLE (myshop
MATCH (n IS customers)
COLUMNS (n.name, LABELS(n) AS lbls)
);
name | lbls
------------+-------------
customer1 | {customers}
customer2 | {customers}
== Implementation approach ==
A naive approach would return LABELS() as a constant (e.g., ARRAY['customers']
directly). However, this prevents the optimizer from pushing down predicates
involving LABELS() through UNION ALL branches.
To enable optimizer pushdown, I wrap each element table in a subquery that
adds a virtual __labels__ column containing a constant array. This way,
LABELS(n) returns a Var referencing that column, allowing the optimizer to
evaluate it per-branch and prune accordingly:
-- Conceptually, the rewrite produces:
SELECT name, __labels__ AS lbls FROM (
SELECT *, ARRAY['customers']::text[] AS __labels__ FROM customers
) ...
This allows the optimizer to perform constant folding and prune UNION ALL
branches when filtering by label:
-- Filter in outer WHERE clause
EXPLAIN SELECT * FROM GRAPH_TABLE (myshop
MATCH (n IS lists) -- lists label shared by orders and wishlists
COLUMNS (LABELS(n) AS lbls, n.node_id)
) WHERE 'orders' = ANY(lbls);
QUERY PLAN
------------------------------------------------------
Seq Scan on orders
Output: '{orders,lists}'::text[], orders.order_id
-- Filter in MATCH WHERE clause without IS (both tables scanned)
EXPLAIN SELECT * FROM GRAPH_TABLE (myshop
MATCH (n) WHERE 'lists' = ANY(LABELS(n))
COLUMNS (LABELS(n) AS lbls, n.node_id)
);
QUERY PLAN
------------------------------------------------------
Append
-> Seq Scan on orders
Output: '{orders,lists}'::text[], orders.order_id
-> Seq Scan on wishlists
Output: '{lists,wishlists}'::text[], wishlists.wishlist_id
The first example prunes the wishlists branch since 'orders' is not in its
label set. The second example uses LABELS() without an IS clause to filter
across all element tables that have the 'lists' label.
== The problem ==
The subquery wrapping breaks column-level privilege checking.
Test case from privileges.sql:
-- regress_priv_user4 has SELECT on atest5(one, four) only
-- lttc label maps atest5.three -> lttck (no privilege)
SET ROLE regress_priv_user4;
SELECT * FROM graph_table (ptg1 MATCH (v IS lttc) COLUMNS (v.lttck));
-- Expected: ERROR: permission denied for table atest5
-- Actual: query succeeds (returns rows without error)
I haven't yet identified the exact root cause of this issue. Has anyone
encountered a similar issue? Any pointers would be appreciated.
Thanks,
Henson2025년 12월 18일 (목) PM 6:16, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>님이 작성:On Wed, Dec 17, 2025 at 2:28 PM Peter Eisentraut <peter@eisentraut.org> wrote:
>
> On 17.12.25 06:32, Ashutosh Bapat wrote:
> > On Mon, Dec 15, 2025 at 6:43 PM Ashutosh Bapat
> > <ashutosh.bapat.oss@gmail.com> wrote:
> >>
> >> Rebased patches on the latest HEAD which required me to move
> >> graph_table.sql to another parallel group.
> >
> > Huh, the movement resulted in losing that test from parallel_schedule.
> > Fixed in the attached patches.
>
> A couple of items:
>
> 1) I was running some tests that involved properties with mismatching
> typmods, and I got an error message like
>
> ERROR: property "p1" data type modifier mismatch: 14 vs. 19
>
> but the actual types were varchar(10) and varchar(15). So to improve
> that, we need to run these through the typmod formatting routines, not
> just print the raw typmod numbers. I actually just combined that with
> the check for the type itself. Also, there was no test covering this,
> so I added one. See attached patches.
+1. The error message is better.
>
> I did another investigation about whether this level of checking is
> necessary. I think according to the letter of the SQL standard, the
> typmods must indeed match. It seems Oracle does not check (the example
> mentioned above came from an Oracle source). But I think it's okay to
> keep the check. In PostgreSQL, it is much less common to write like
> varchar(1000). And we can always consider relaxing it later.
+1.
Attached patch adds a couple more test statements.
>
> 2) I had it in my notes to consider whether we should support the colon
> syntax for label expressions. I think we might have talked about that
> before.
>
> I'm now leaning toward not supporting it in the first iteration. I
> don't know that we have fully explored possible conflicts with host
> variable syntax in ecpg and psql and the like. Maybe avoid that for now.
>
I was aware of ecpg and I vaguely remember we fixed something in ECPG
to allow : in MATCH statement. Probably following changes in
psqlscan.l and pgc.l
-self [,()\[\].;\:\+\-\*\/\%\^\<\>\=]
+self [,()\[\].;\:\|\+\-\*\/\%\^\<\>\=]
Those changes add | after : (and not the : itself) so maybe they are
not about supporting : . Do you remember what those are?
However, I see that : in psql can be a problem
#create table t1 (a int, b int);
#create property graph g1 vertex tables (t1 key (a));
#select * from GRAPH_TABLE (g1 MATCH (a :t1) COLUMNS (a.a));
a
---
(0 rows)
#\set t1 blank
#select * from GRAPH_TABLE (g1 MATCH (a :t1) COLUMNS (a.a));
ERROR: syntax error at or near "blank"
LINE 1: select * from GRAPH_TABLE (g1 MATCH (a blank) COLUMNS (a.a))...
> There was also a bit of an inconsistency in the presentation: The
> documentation introduced the colon as seemingly the preferred syntax,
> but ruleutils.c dumped out the IS syntax.
>
> (It was also a bit curious that some test code put spaces around the
> colon, which is not idiomatic.)
>
That might have been just me trying to type one letter less and yet
keeping the query readable. A column between variable name and the
label is not always noticeable.
> Attached is a patch that shows how to revert the colon support. It's
> pretty simple, and it would be easy to add it back in later, I think.
I agree that it's better not to support it now. It requires more work
and it's optional. When we come to support it, we will need thorough
testing.
I spotted some examples that use : in ddl.sgml.
<programlisting>
SELECT customer_name FROM GRAPH_TABLE (myshop MATCH
(c:customer)-[:has]->(o:"order" WHERE o.ordered_when = current_date)
COLUMNS (c.name AS customer_name));
</programlisting>
The query demonstrates that one can use label names in a way that will
make the pattern look like an English sentence. Replacing : with IS
defeats that purpose.
As written in that paragraph, the labels serve the purpose of exposing
the table with a different logical view (using different label and
property names). So we need that paragraph, but I think we should
change the example to use IS instead of :. Attached is suggested
minimal change, but I am not happy with it. Another possibility is we
completely remove that paragraph; I don't think we need to discuss all
possible usages the users will come up with.
The patch changes one more instance of : by IS. But that's straight forward.
In ddl.sgml I noticed a seemingly incomplete sentence
A property graph is a way to represent database contents, instead of using
relational structures such as tables.
Represent the contents as what? I feel the complete sentence should be
one of the following
property graph is a way to represent database contents as a graph,
instead of representing those as relational structures OR
property graph is another way to represent database contents instead
of using relational structures such as tables
But I can't figure out what was originally intended.
I have squashed 0002 from my earlier patchset and your 3 patches into 0001.
0002 has extra tests mentioned above. It also removes "TODO: dubious
error message" from a comment. I don't see anything dubious in the
error message. I think this patch is safe to be merged into 0001.
0003 is changed to ddl.sgml. Those need a bit more work as described above.
--
Best Wishes,
Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
I apologize for the confusion caused by my partial patch submission.
The patch was intended to be applied on top of the PGQ base patch,
but I was not aware that CFBot would try to apply it directly to master.
Next time, I will use a .txt extension so that the original authors
can review it before CFBot processes it.
Sorry for the inconvenience.
Regards,
Henson Choi
Subject: Re: SQL Property Graph Queries (SQL/PGQ)
Hi hackers,
Apologies for jumping into the SQL/PGQ discussion mid-stream. I've been
working on implementing the LABELS() graph element function and ran into
an issue I'd like to get some guidance on.
== What LABELS() does ==
LABELS(element_variable) returns a text[] array containing all labels
associated with a graph element. For example:
SELECT * FROM GRAPH_TABLE (myshop
MATCH (n IS customers)
COLUMNS (n.name, LABELS(n) AS lbls)
);
name | lbls
------------+-------------
customer1 | {customers}
customer2 | {customers}
== Implementation approach ==
A naive approach would return LABELS() as a constant (e.g., ARRAY['customers']
directly). However, this prevents the optimizer from pushing down predicates
involving LABELS() through UNION ALL branches.
To enable optimizer pushdown, I wrap each element table in a subquery that
adds a virtual __labels__ column containing a constant array. This way,
LABELS(n) returns a Var referencing that column, allowing the optimizer to
evaluate it per-branch and prune accordingly:
-- Conceptually, the rewrite produces:
SELECT name, __labels__ AS lbls FROM (
SELECT *, ARRAY['customers']::text[] AS __labels__ FROM customers
) ...
This allows the optimizer to perform constant folding and prune UNION ALL
branches when filtering by label:
-- Filter in outer WHERE clause
EXPLAIN SELECT * FROM GRAPH_TABLE (myshop
MATCH (n IS lists) -- lists label shared by orders and wishlists
COLUMNS (LABELS(n) AS lbls, n.node_id)
) WHERE 'orders' = ANY(lbls);
QUERY PLAN
------------------------------------------------------
Seq Scan on orders
Output: '{orders,lists}'::text[], orders.order_id
-- Filter in MATCH WHERE clause without IS (both tables scanned)
EXPLAIN SELECT * FROM GRAPH_TABLE (myshop
MATCH (n) WHERE 'lists' = ANY(LABELS(n))
COLUMNS (LABELS(n) AS lbls, n.node_id)
);
QUERY PLAN
------------------------------------------------------
Append
-> Seq Scan on orders
Output: '{orders,lists}'::text[], orders.order_id
-> Seq Scan on wishlists
Output: '{lists,wishlists}'::text[], wishlists.wishlist_id
The first example prunes the wishlists branch since 'orders' is not in its
label set. The second example uses LABELS() without an IS clause to filter
across all element tables that have the 'lists' label.
== The problem ==
The subquery wrapping breaks column-level privilege checking.
Test case from privileges.sql:
-- regress_priv_user4 has SELECT on atest5(one, four) only
-- lttc label maps atest5.three -> lttck (no privilege)
SET ROLE regress_priv_user4;
SELECT * FROM graph_table (ptg1 MATCH (v IS lttc) COLUMNS (v.lttck));
-- Expected: ERROR: permission denied for table atest5
-- Actual: query succeeds (returns rows without error)
I haven't yet identified the exact root cause of this issue. Has anyone
encountered a similar issue? Any pointers would be appreciated.
Thanks,
Henson2025년 12월 18일 (목) PM 6:16, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>님이 작성:On Wed, Dec 17, 2025 at 2:28 PM Peter Eisentraut <peter@eisentraut.org> wrote:
>
> On 17.12.25 06:32, Ashutosh Bapat wrote:
> > On Mon, Dec 15, 2025 at 6:43 PM Ashutosh Bapat
> > <ashutosh.bapat.oss@gmail.com> wrote:
> >>
> >> Rebased patches on the latest HEAD which required me to move
> >> graph_table.sql to another parallel group.
> >
> > Huh, the movement resulted in losing that test from parallel_schedule.
> > Fixed in the attached patches.
>
> A couple of items:
>
> 1) I was running some tests that involved properties with mismatching
> typmods, and I got an error message like
>
> ERROR: property "p1" data type modifier mismatch: 14 vs. 19
>
> but the actual types were varchar(10) and varchar(15). So to improve
> that, we need to run these through the typmod formatting routines, not
> just print the raw typmod numbers. I actually just combined that with
> the check for the type itself. Also, there was no test covering this,
> so I added one. See attached patches.
+1. The error message is better.
>
> I did another investigation about whether this level of checking is
> necessary. I think according to the letter of the SQL standard, the
> typmods must indeed match. It seems Oracle does not check (the example
> mentioned above came from an Oracle source). But I think it's okay to
> keep the check. In PostgreSQL, it is much less common to write like
> varchar(1000). And we can always consider relaxing it later.
+1.
Attached patch adds a couple more test statements.
>
> 2) I had it in my notes to consider whether we should support the colon
> syntax for label expressions. I think we might have talked about that
> before.
>
> I'm now leaning toward not supporting it in the first iteration. I
> don't know that we have fully explored possible conflicts with host
> variable syntax in ecpg and psql and the like. Maybe avoid that for now.
>
I was aware of ecpg and I vaguely remember we fixed something in ECPG
to allow : in MATCH statement. Probably following changes in
psqlscan.l and pgc.l
-self [,()\[\].;\:\+\-\*\/\%\^\<\>\=]
+self [,()\[\].;\:\|\+\-\*\/\%\^\<\>\=]
Those changes add | after : (and not the : itself) so maybe they are
not about supporting : . Do you remember what those are?
However, I see that : in psql can be a problem
#create table t1 (a int, b int);
#create property graph g1 vertex tables (t1 key (a));
#select * from GRAPH_TABLE (g1 MATCH (a :t1) COLUMNS (a.a));
a
---
(0 rows)
#\set t1 blank
#select * from GRAPH_TABLE (g1 MATCH (a :t1) COLUMNS (a.a));
ERROR: syntax error at or near "blank"
LINE 1: select * from GRAPH_TABLE (g1 MATCH (a blank) COLUMNS (a.a))...
> There was also a bit of an inconsistency in the presentation: The
> documentation introduced the colon as seemingly the preferred syntax,
> but ruleutils.c dumped out the IS syntax.
>
> (It was also a bit curious that some test code put spaces around the
> colon, which is not idiomatic.)
>
That might have been just me trying to type one letter less and yet
keeping the query readable. A column between variable name and the
label is not always noticeable.
> Attached is a patch that shows how to revert the colon support. It's
> pretty simple, and it would be easy to add it back in later, I think.
I agree that it's better not to support it now. It requires more work
and it's optional. When we come to support it, we will need thorough
testing.
I spotted some examples that use : in ddl.sgml.
<programlisting>
SELECT customer_name FROM GRAPH_TABLE (myshop MATCH
(c:customer)-[:has]->(o:"order" WHERE o.ordered_when = current_date)
COLUMNS (c.name AS customer_name));
</programlisting>
The query demonstrates that one can use label names in a way that will
make the pattern look like an English sentence. Replacing : with IS
defeats that purpose.
As written in that paragraph, the labels serve the purpose of exposing
the table with a different logical view (using different label and
property names). So we need that paragraph, but I think we should
change the example to use IS instead of :. Attached is suggested
minimal change, but I am not happy with it. Another possibility is we
completely remove that paragraph; I don't think we need to discuss all
possible usages the users will come up with.
The patch changes one more instance of : by IS. But that's straight forward.
In ddl.sgml I noticed a seemingly incomplete sentence
A property graph is a way to represent database contents, instead of using
relational structures such as tables.
Represent the contents as what? I feel the complete sentence should be
one of the following
property graph is a way to represent database contents as a graph,
instead of representing those as relational structures OR
property graph is another way to represent database contents instead
of using relational structures such as tables
But I can't figure out what was originally intended.
I have squashed 0002 from my earlier patchset and your 3 patches into 0001.
0002 has extra tests mentioned above. It also removes "TODO: dubious
error message" from a comment. I don't see anything dubious in the
error message. I think this patch is safe to be merged into 0001.
0003 is changed to ddl.sgml. Those need a bit more work as described above.
--
Best Wishes,
Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Thu, Dec 18, 2025 at 2:45 PM Ashutosh Bapat wrote: > > > > > > I did another investigation about whether this level of checking is > > necessary. I think according to the letter of the SQL standard, the > > typmods must indeed match. It seems Oracle does not check (the example > > mentioned above came from an Oracle source). But I think it's okay to > > keep the check. In PostgreSQL, it is much less common to write like > > varchar(1000). And we can always consider relaxing it later. > > +1. > > Attached patch adds a couple more test statements. > Squashed this into the main patchset. > > > > 2) I had it in my notes to consider whether we should support the colon > > syntax for label expressions. I think we might have talked about that > > before. > > > > I'm now leaning toward not supporting it in the first iteration. I > > don't know that we have fully explored possible conflicts with host > > variable syntax in ecpg and psql and the like. Maybe avoid that for now. > > > > I was aware of ecpg and I vaguely remember we fixed something in ECPG > to allow : in MATCH statement. Probably following changes in > psqlscan.l and pgc.l > -self [,()\[\].;\:\+\-\*\/\%\^\<\>\=] > +self [,()\[\].;\:\|\+\-\*\/\%\^\<\>\=] > > Those changes add | after : (and not the : itself) so maybe they are > not about supporting : . Do you remember what those are? I reverted those changes from both the files and ran "meson test". I did not observe any failure. It seems those changes are not needed. But adding them as a separate commit (0004) in case CI bot reveals any failures without them. I noticed that there were no ECPG tests for SQL/PGQ. Added a basic test in patch 0003. > > I spotted some examples that use : in ddl.sgml. > > SELECT customer_name FROM GRAPH_TABLE (myshop MATCH > (c:customer)-[:has]->(o:"order" WHERE o.ordered_when = current_date) > COLUMNS (c.name AS customer_name)); > > > The query demonstrates that one can use label names in a way that will > make the pattern look like an English sentence. Replacing : with IS > defeats that purpose. > > As written in that paragraph, the labels serve the purpose of exposing > the table with a different logical view (using different label and > property names). So we need that paragraph, but I think we should > change the example to use IS instead of :. Attached is suggested > minimal change, but I am not happy with it. Another possibility is we > completely remove that paragraph; I don't think we need to discuss all > possible usages the users will come up with. > > The patch changes one more instance of : by IS. But that's straight forward. > > In ddl.sgml I noticed a seemingly incomplete sentence > A property graph is a way to represent database contents, instead of using > relational structures such as tables. > > Represent the contents as what? I feel the complete sentence should be > one of the following > property graph is a way to represent database contents as a graph, > instead of representing those as relational structures OR > property graph is another way to represent database contents instead > of using relational structures such as tables > > But I can't figure out what was originally intended. 0002 contains some edits to this part of documentation. I think the paragraph reads better than before. Let me know what you think. Please let me know which of 0002 to 0004 look good to you. I will squash those into the patchset in the next version. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Henson, Thanks a lot for your interest in SQL/PGQ patches. Your expertise will certainly help. On Fri, Dec 26, 2025 at 6:03 PM Henson Choi wrote: > > Following up on my Dec 24 email - three features completed: > > 1. LABELS() function > - Returns text[] of element labels > - Fixed privilege checking from previous version > - Enables optimizer pushdown for branch pruning > > 2. PROPERTY_NAMES() function > - Returns text[] of property names > - Similar approach to LABELS() > I could not find specification of these functions in SQL/PGQ standard. It's a large document and I might be missing something. Can you please point me to the relevant sections? > 3. Multiple path patterns > - Syntax: MATCH (a)->(b), (b)->(c) > - Implements SQL/PGQ standard feature (was TODO) > This path pattern list feature is discussed in section 10.4 of the standard. I think supporting this feature would be a good addition to SQL/PGQ compliance. The current patchset is already large. I (and AFAIK Peter as well) am focusing on getting that patchset in a committable shape. Once committed, it will facilitate adding features like path pattern list, quantified path patterns, label conjunction etc. as incremental relatively smaller commits. Since you could build one of the complex features without changing a lot of earlier implementation, it validates that the basic implementation is extensible and yet robust. Thanks for that validation. The way you have implemented it, it can lead to a path pattern with two vertex patterns next to each other without an interleaving edge pattern. That would throw an error or assertion. If you try path patterns without a common vertex, you will get that error. That is not covered by your tests. In such cases, the paths should end up being full-joined rather than concatenated. I don't see it being implemented that way. I think more work is needed here. [1] https://www.postgresql.org/message-id/CAExHW5sr+dJPCFw2OqXUfPPqPks8qmsivaAYhRiBdFANcX8RHw@mail.gmail.com -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Tue, Dec 30, 2025 at 3:14 PM Ashutosh Bapat wrote: > > On Thu, Dec 18, 2025 at 2:45 PM Ashutosh Bapat > wrote: > > > > > > > > > > I did another investigation about whether this level of checking is > > > necessary. I think according to the letter of the SQL standard, the > > > typmods must indeed match. It seems Oracle does not check (the example > > > mentioned above came from an Oracle source). But I think it's okay to > > > keep the check. In PostgreSQL, it is much less common to write like > > > varchar(1000). And we can always consider relaxing it later. > > > > +1. > > > > Attached patch adds a couple more test statements. > > > > Squashed this into the main patchset. > > > > > > > 2) I had it in my notes to consider whether we should support the colon > > > syntax for label expressions. I think we might have talked about that > > > before. > > > > > > I'm now leaning toward not supporting it in the first iteration. I > > > don't know that we have fully explored possible conflicts with host > > > variable syntax in ecpg and psql and the like. Maybe avoid that for now. > > > > > > > I was aware of ecpg and I vaguely remember we fixed something in ECPG > > to allow : in MATCH statement. Probably following changes in > > psqlscan.l and pgc.l > > -self [,()\[\].;\:\+\-\*\/\%\^\<\>\=] > > +self [,()\[\].;\:\|\+\-\*\/\%\^\<\>\=] > > > > Those changes add | after : (and not the : itself) so maybe they are > > not about supporting : . Do you remember what those are? > > I reverted those changes from both the files and ran "meson test". I > did not observe any failure. It seems those changes are not needed. > But adding them as a separate commit (0004) in case CI bot reveals any > failures without them. > > I noticed that there were no ECPG tests for SQL/PGQ. Added a basic > test in patch 0003. > > > > > I spotted some examples that use : in ddl.sgml. > > > > SELECT customer_name FROM GRAPH_TABLE (myshop MATCH > > (c:customer)-[:has]->(o:"order" WHERE o.ordered_when = current_date) > > COLUMNS (c.name AS customer_name)); > > > > > > The query demonstrates that one can use label names in a way that will > > make the pattern look like an English sentence. Replacing : with IS > > defeats that purpose. > > > > As written in that paragraph, the labels serve the purpose of exposing > > the table with a different logical view (using different label and > > property names). So we need that paragraph, but I think we should > > change the example to use IS instead of :. Attached is suggested > > minimal change, but I am not happy with it. Another possibility is we > > completely remove that paragraph; I don't think we need to discuss all > > possible usages the users will come up with. > > > > The patch changes one more instance of : by IS. But that's straight forward. > > > > In ddl.sgml I noticed a seemingly incomplete sentence > > A property graph is a way to represent database contents, instead of using > > relational structures such as tables. > > > > Represent the contents as what? I feel the complete sentence should be > > one of the following > > property graph is a way to represent database contents as a graph, > > instead of representing those as relational structures OR > > property graph is another way to represent database contents instead > > of using relational structures such as tables > > > > But I can't figure out what was originally intended. > > > 0002 contains some edits to this part of documentation. I think the > paragraph reads better than before. Let me know what you think. > > Please let me know which of 0002 to 0004 look good to you. I will > squash those into the patchset in the next version. The previous patchset had a whitespace difference in ECPG expected output files. Fixed in the attached patchset. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
============================
Patch: SQL Property Graph Queries (SQL/PGQ)
Commitfest: https://commitfest.postgresql.org/patch/4904
Review Methodology:
This review focused on quality assessment, not line-by-line code audit.
Key code paths and quality issues were examined with surrounding context
when concerns arose. Documentation files were reviewed with AI-assisted
grammar and typo checking. Code coverage was measured using gcov and
custom analysis tools.
Limitations:
- Not a security audit or formal verification
- Parser and executor internals reviewed at module level, not exhaustively
- Performance characteristics not benchmarked
TABLE OF CONTENTS
-----------------
1. Executive Summary
2. Issues Found
2.1 Critical / Major
2.2 Minor Issues
2.3 Suggestions for Discussion
3. Test Coverage
3.1 Covered Areas
3.2 Untested Items
3.3 Unimplemented Features (No Test Needed)
4. Code Coverage Analysis
4.1 Overall Coverage
4.2 Coverage by File
4.3 Uncovered Code Risk Assessment
5. Recommended Additional Tests
5.1 Black-box Tests (Functional)
5.2 White-box Tests (Coverage)
5.3 Untestable Code (Defensive)
6. Recommendations
7. Conclusion
1. EXECUTIVE SUMMARY
--------------------
Overall assessment: GOOD
The SQL/PGQ patch demonstrates solid implementation quality within its
defined scope. Code follows PostgreSQL coding standards, test coverage
is comprehensive at 90.5%, and documentation is thorough with only
minor typos.
Rating by Area:
- Code Quality: Excellent (PostgreSQL style compliant, 1 FIXME)
- Test Coverage: Good (90.5% line coverage, ~180 test cases)
- Documentation: Good (Complete, 5 minor issues)
- Build/Regress: Pass (make check-world, 56 test suites passed)
2. ISSUES FOUND
---------------
2.1 Critical / Major
(None)
2.2 Minor Issues
#1 [Code] src/backend/commands/propgraphcmds.c:1632
FIXME: Missing index for plppropid column causes sequential scan.
Decision needed: (a) add index, or (c) allow seq scan for rare path.
#2 [Doc] doc/src/sgml/ref/alter_property_graph.sgml:286
Compatibility section incorrectly states "CREATE PROPERTY GRAPH"
Should be: "ALTER PROPERTY GRAPH"
#3 [Doc] doc/src/sgml/ref/alter_property_graph.sgml:65
Synopsis shows VERTEX/NODE and EDGE/RELATIONSHIP as separate clauses,
but Description merges them as {VERTEX|NODE|EDGE|RELATIONSHIP}.
#4 [Doc] doc/src/sgml/ref/alter_property_graph.sgml:80
Grammar error: "the graph removed" should be "the graph is removed"
#5 [Doc] doc/src/sgml/queries.sgml:2929,2931
TODO comments for unimplemented features without clear limitation notes.
#6 [Doc] doc/src/sgml/ddl.sgml:5717
Typo: "infrastucture" should be "infrastructure"
2.3 Alternative Approaches for Discussion
#1 Support CREATE PROPERTY GRAPH IF NOT EXISTS
Rationale: PostgreSQL-style extension, consistent with other DDL.
#2 Return 0 rows for non-existent labels instead of error
Current: SELECT * FROM GRAPH_TABLE(g MATCH (a:NonExistent) ...) raises error
Alternative: Return empty result set instead
Rationale: Better for exploratory queries, similar to SQL WHERE on
non-existent values returning 0 rows rather than error.
#3 Return 0 rows when same variable has different labels
Current: SELECT * FROM GRAPH_TABLE(g MATCH (a:Person)-[e]-(a:Company) ...)
raises error because variable 'a' has conflicting labels.
Alternative: Return empty result set instead
Rationale: Logically, a node cannot be both Person AND Company,
so 0 rows is the correct result. Consistent with standard SQL
WHERE semantics (impossible condition = 0 rows, not error).
3. TEST COVERAGE
----------------
3.1 Covered Areas
- CREATE PROPERTY GRAPH: Empty graph, VERTEX/EDGE TABLES, KEY, LABEL, PROPERTIES
- ALTER PROPERTY GRAPH: ADD/DROP VERTEX/EDGE, ADD/DROP LABEL, ADD/DROP PROPERTIES
- DROP PROPERTY GRAPH: Basic DROP, IF EXISTS
- RENAME TO / SET SCHEMA: Tested in alter_generic.sql
- OWNER TO: Permission change tests
- GRAPH_TABLE queries: Pattern matching, WHERE, COLUMNS, LATERAL, etc.
- RLS integration: PERMISSIVE/RESTRICTIVE policies, inheritance/partition tables
- Error cases: Type/collation mismatch, non-existent objects, etc.
- psql integration: \dG, \d commands
- pg_dump: Tested in t/002_pg_dump.pl
3.2 Untested Items
- CREATE TEMP PROPERTY GRAPH (Medium priority)
- DROP ... CASCADE (Low priority)
- DROP ... RESTRICT (Low priority)
3.3 Unimplemented Features (No Test Needed)
- Multiple path patterns: Parser supports, execution not implemented
- Quantifier {n,m}: Parser supports, execution not implemented
4. CODE COVERAGE ANALYSIS
-------------------------
4.1 Overall Coverage
90.5% (2,029 / 2,243 lines)
4.2 Coverage by File
propgraphcmds.c: 94.6% (DDL command processing)
rewriteGraphTable.c: 94.6% (GRAPH_TABLE rewrite)
parse_graphtable.c: 97.6% (Graph query parser)
parse_clause.c: 98.0% (FROM clause parser)
ruleutils.c: 85.1% (pg_get_propgraphdef, etc.)
pg_dump.c: 84.0% (Dump/restore)
describe.c: 88.9% (psql \dG command)
4.3 Uncovered Code Risk Assessment
Low Risk (13 items):
- Defensive code, debug functions, unimplemented feature guards
Medium Risk (1 item):
- TEMP graph functionality untested
Conclusion: Most uncovered code consists of error handling, unimplemented
feature guards, and debug utilities. No security or functional risk.
5. RECOMMENDED ADDITIONAL TESTS
-------------------------------
5.1 Black-box Tests (Functional)
Based on feature specification, independent of code structure.
Feature Test Case Priority
-------------------------------------------------------------------------------
TEMP graph CREATE TEMP PROPERTY GRAPH Medium
TEMP graph TEMP graph with permanent table reference Medium
TEMP graph ALTER ADD permanent table to TEMP graph Medium
CASCADE DROP ... CASCADE (dependent view cascade) Low
RESTRICT DROP ... RESTRICT (dependent object error) Low
5.2 White-box Tests (Coverage)
Based on uncovered code paths identified in coverage analysis.
File:Line Test Case Target Branch
-------------------------------------------------------------------------------
propgraphcmds.c:136,179,254-262 TEMP table in graph creation Auto TEMP conversion
propgraphcmds.c:1323,1364 ALTER ADD TEMP to perm graph Error branch
propgraphcmds.c:724-734 CREATE without LABEL clause Default label else
propgraphcmds.c:1300,1303 ALTER IF EXISTS non-existent missing_ok branch
propgraphcmds.c:116 CREATE UNLOGGED attempt UNLOGGED error
execMain.c:1162-1163 DML on graph RELKIND_PROPGRAPH
rewriteGraphTable.c:120 Multiple path patterns Length check
rewriteGraphTable.c:205 Quantifier usage Quantifier error
ruleutils.c:7939-7963 Complex label VIEW deparsing T_BoolExpr branch
5.3 Untestable Code (Defensive)
File:Line Reason
-------------------------------------------------------------------------------
rewriteGraphTable.c:202 PAREN_EXPR blocked at parser level
rewriteGraphTable.c:297,304,319 Cyclic pattern edge conflict - unreachable
rewriteGraphTable.c:801-818 get_gep_kind_name - error path only
nodeFuncs.c:4585-4596,4755-4774 Walker branches - internal implementation
6. RECOMMENDATIONS
------------------
6.1 Code Review Required (Minor, Decision Needed)
Location: propgraphcmds.c:1632
Issue: FIXME - No single-column index for plppropid
Current: InvalidOid causes sequential scan
Purpose: Check property references across all labels when deleting orphaned properties
Options:
(a) Add index: Create new single-column index on plppropid
(b) Use existing: NOT POSSIBLE (cannot specify plpellabelid, need all labels)
(c) Allow: Rare path (property deletion), sequential scan acceptable
6.2 Documentation Fixes (Minor)
- alter_property_graph.sgml: 3 typos/errors to fix
- queries.sgml: Add clear limitation notes for unimplemented features
- ddl.sgml: Fix "infrastucture" typo
6.3 Test Additions (Optional)
- CREATE TEMP PROPERTY GRAPH tests
- DROP ... CASCADE/RESTRICT tests
7. CONCLUSION
-------------
Test Quality: GOOD
Core functionality is thoroughly tested with comprehensive error case and
security (RLS) integration tests.
The patch is well-implemented within its defined scope. Identified issues
are minor documentation typos and one code decision point (FIXME).
No critical or major issues found.
Recommended actions before commit:
1. Decide on FIXME at propgraphcmds.c:1632 (index vs. allow seq scan)
2. Fix 5 documentation issues
3. Consider adding TEMP graph tests (optional but recommended)
Points for discussion (optional):
4. CREATE PROPERTY GRAPH IF NOT EXISTS support
5. Error vs. 0 rows behavior for non-existent/conflicting labels
Attachment:
- coverage_report.tar.gz (HTML coverage report generated by gcov)
End of Report
On Tue, Dec 30, 2025 at 3:14 PM Ashutosh Bapat
<ashutosh.bapat.oss@gmail.com> wrote:
>
> On Thu, Dec 18, 2025 at 2:45 PM Ashutosh Bapat
> <ashutosh.bapat.oss@gmail.com> wrote:
> >
> >
> > >
> > > I did another investigation about whether this level of checking is
> > > necessary. I think according to the letter of the SQL standard, the
> > > typmods must indeed match. It seems Oracle does not check (the example
> > > mentioned above came from an Oracle source). But I think it's okay to
> > > keep the check. In PostgreSQL, it is much less common to write like
> > > varchar(1000). And we can always consider relaxing it later.
> >
> > +1.
> >
> > Attached patch adds a couple more test statements.
> >
>
> Squashed this into the main patchset.
>
> > >
> > > 2) I had it in my notes to consider whether we should support the colon
> > > syntax for label expressions. I think we might have talked about that
> > > before.
> > >
> > > I'm now leaning toward not supporting it in the first iteration. I
> > > don't know that we have fully explored possible conflicts with host
> > > variable syntax in ecpg and psql and the like. Maybe avoid that for now.
> > >
> >
> > I was aware of ecpg and I vaguely remember we fixed something in ECPG
> > to allow : in MATCH statement. Probably following changes in
> > psqlscan.l and pgc.l
> > -self [,()\[\].;\:\+\-\*\/\%\^\<\>\=]
> > +self [,()\[\].;\:\|\+\-\*\/\%\^\<\>\=]
> >
> > Those changes add | after : (and not the : itself) so maybe they are
> > not about supporting : . Do you remember what those are?
>
> I reverted those changes from both the files and ran "meson test". I
> did not observe any failure. It seems those changes are not needed.
> But adding them as a separate commit (0004) in case CI bot reveals any
> failures without them.
>
> I noticed that there were no ECPG tests for SQL/PGQ. Added a basic
> test in patch 0003.
>
> >
> > I spotted some examples that use : in ddl.sgml.
> > <programlisting>
> > SELECT customer_name FROM GRAPH_TABLE (myshop MATCH
> > (c:customer)-[:has]->(o:"order" WHERE o.ordered_when = current_date)
> > COLUMNS (c.name AS customer_name));
> > </programlisting>
> >
> > The query demonstrates that one can use label names in a way that will
> > make the pattern look like an English sentence. Replacing : with IS
> > defeats that purpose.
> >
> > As written in that paragraph, the labels serve the purpose of exposing
> > the table with a different logical view (using different label and
> > property names). So we need that paragraph, but I think we should
> > change the example to use IS instead of :. Attached is suggested
> > minimal change, but I am not happy with it. Another possibility is we
> > completely remove that paragraph; I don't think we need to discuss all
> > possible usages the users will come up with.
> >
> > The patch changes one more instance of : by IS. But that's straight forward.
> >
> > In ddl.sgml I noticed a seemingly incomplete sentence
> > A property graph is a way to represent database contents, instead of using
> > relational structures such as tables.
> >
> > Represent the contents as what? I feel the complete sentence should be
> > one of the following
> > property graph is a way to represent database contents as a graph,
> > instead of representing those as relational structures OR
> > property graph is another way to represent database contents instead
> > of using relational structures such as tables
> >
> > But I can't figure out what was originally intended.
>
>
> 0002 contains some edits to this part of documentation. I think the
> paragraph reads better than before. Let me know what you think.
>
> Please let me know which of 0002 to 0004 look good to you. I will
> squash those into the patchset in the next version.
The previous patchset had a whitespace difference in ECPG expected
output files. Fixed in the attached patchset.
--
Best Wishes,
Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
I ran Valgrind memcheck against the SQL/PGQ (Property Graph) implementation
to verify there are no memory issues introduced by the new graph features.
== Test Environment ==
- PostgreSQL: 19devel (master branch)
- Valgrind: 3.22.0
- Platform: Linux x86_64 (RHEL 9)
- Tests executed: run_pgq_tests.sql
- create_property_graph.sql
- graph_table.sql
- graph_table_rls.sql
- alter_generic.sql
- object_address.sql
== Executive Summary ==
+----------------------------------------------------------+
| SQL/PGQ Implementation: NO MEMORY LEAKS DETECTED |
+----------------------------------------------------------+
All detected leaks originate from existing PostgreSQL core components.
No graph-related functions appear in any leak stack traces.
== Backend Process 487751: Itemized Leak Analysis ==
Total: 555 bytes definitely lost in 47 blocks, 21 unique leak contexts
+================================================================================+
| # | Bytes | Blocks | Allocator | Root Cause | PGQ? | Verdict |
+================================================================================+
| 1 | 1 | 1 | text_to_cstring | SQL func cache | NO | HARMLESS |
| 2 | 3 | 1 | pstrdup | PL/pgSQL lexer | NO | HARMLESS |
| 3 | 3 | 1 | pstrdup | PL/pgSQL lexer | NO | HARMLESS |
| 4 | 12 | 2 | downcase_identifier | PL/pgSQL parser | NO | HARMLESS |
| 5 | 12 | 2 | downcase_identifier | PL/pgSQL parser | NO | HARMLESS |
| 6 | 12 | 2 | downcase_identifier | PL/pgSQL parser | NO | HARMLESS |
| 7 | 13 | 2 | downcase_identifier | PL/pgSQL parser | NO | HARMLESS |
| 8 | 21 | 3 | downcase_identifier | PL/pgSQL parser | NO | HARMLESS |
| 9 | 25 | 3 | downcase_identifier | PL/pgSQL parser | NO | HARMLESS |
| 10 | 27 | 1 | detoast_attr | SQL func cache | NO | HARMLESS |
| 11 | 27 | 1 | detoast_attr | SQL func cache | NO | HARMLESS |
| 12 | 33 | 5 | downcase_identifier | PL/pgSQL parser | NO | HARMLESS |
| 13 | 33 | 5 | downcase_identifier | PL/pgSQL parser | NO | HARMLESS |
| 14 | 33 | 5 | downcase_identifier | PL/pgSQL parser | NO | HARMLESS |
| 15 | 37 | 1 | strdup | Postmaster init | NO | HARMLESS |
| 16 | 38 | 5 | downcase_identifier | PL/pgSQL parser | NO | HARMLESS |
| 17 | 68 | 1 | deconstruct_array | SQL func cache | NO | HARMLESS |
| 18 | 84 | 1 | deconstruct_array | SQL func cache | NO | HARMLESS |
| 19 | 164 | 2 | lappend | PL/pgSQL parser | NO | HARMLESS |
| 20 | 164 | 2 | lappend | PL/pgSQL parser | NO | HARMLESS |
| 21 | 358 | 1 | plpgsql_ns_push | PL/pgSQL parser | NO | HARMLESS |
+================================================================================+
TOTAL: 555 bytes in 47 blocks
PGQ-RELATED LEAKS: 0
== SQL/PGQ Verification ==
All 21 leak stack traces were examined. Key functions NOT present:
- CreatePropertyGraph, DropPropertyGraph, AlterPropertyGraph
- transformGraphTable, ExecGraphTableScan
- Any function from src/backend/commands/propertygraphcmds.c
- Any function from src/backend/parser/parse_graph.c
- Any GRAPH_TABLE related executor nodes
The SQL/PGQ tests exercised CREATE PROPERTY GRAPH, DROP PROPERTY GRAPH,
and GRAPH_TABLE queries, yet none of these code paths appear in leaks.
== Process Summary ==
+--------+----------------+-----------------+----------+--------------------+
| PID | Type | Definitely Lost | Errors | Notes |
+--------+----------------+-----------------+----------+--------------------+
| 487724 | postmaster | 37 bytes | 1 | strdup at startup |
| 487751 | backend | 555 bytes | 30 | See above analysis |
| 487735 | checkpointer | 37 bytes | 1 | strdup at startup |
| 487736 | bgwriter | 37 bytes | 1 | strdup at startup |
| 487737 | walwriter | 37 bytes | 1 | strdup at startup |
| 487738 | autovacuum | 37 bytes | 1 | strdup at startup |
| 487739 | logical rep | 37 bytes | 1 | strdup at startup |
| 487740 | syslogger | 37 bytes | 1 | strdup at startup |
| Others | aux workers | 37 bytes each | 1 each | strdup at startup |
+--------+----------------+-----------------+----------+--------------------+
== Possibly Lost (LLVM JIT) ==
Additionally, ~15KB in ~155 blocks reported as "possibly lost" from LLVM JIT:
- llvm::MDTuple, llvm::User allocations
- Origin: llvm_compile_expr -> jit_compile_expr -> ExecReadyExpr
- These are LLVM's internal caches, not PostgreSQL leaks
== Other Memory Errors ==
+--------------------------------------------------------------------------+
| NO memory access errors detected: |
| - Invalid read/write: 0 |
| - Use of uninitialized value: 0 |
| - Conditional jump on uninitialized value: 0 |
| - Syscall param errors: 0 |
| - Overlap in memcpy/strcpy: 0 |
+--------------------------------------------------------------------------+
Suppressed errors (via valgrind.supp):
- 487751 (backend): 330 errors from 3 contexts suppressed
- 487762 (aux worker): 9 errors suppressed
- Other processes: ~9 errors each suppressed
Suppression rules in valgrind.supp (12 categories):
1. Padding - write() syscalls with uninitialized struct padding
2. CRC - CRC32 calculation on padded buffers
3. Overlap - memcpy overlap in bootstrap/relmap
4. glibc - Dynamic loader internals
5. Regex/Pattern - RE_compile_and_cache, patternsel
6. Planner - query_planner memcpy overlap
7. Cache - RelCache, CatCache, TypeCache possible leaks
8. XLogReader - WAL reader allocations
9. Parallel - ParallelWorkerMain allocations
10. AutoVacuum - AutoVacWorkerMain allocations
11. GUC/Backend - set_config_option, InitPostgres
12. PL/pgSQL - plpgsql_compile, SPI_prepare, CachedPlan
All suppressed errors are known, harmless PostgreSQL behaviors.
See attached valgrind.supp for details.
== Conclusion ==
The SQL/PGQ implementation introduces NO memory leaks. All detected issues
are pre-existing PostgreSQL behaviors related to:
1. PL/pgSQL function compilation caching
2. SQL function metadata caching
3. Postmaster startup allocations
4. LLVM JIT internal caching
These are by-design patterns that trade minimal memory for performance.
== Files Attached ==
- valgrind.supp: Suppression file used for this test
- 487724.log: Postmaster log
- 487751.log: Backend log with full leak details (126KB)
- 4877xx.log: Auxiliary process logs
--
Regards
On Tue, Dec 30, 2025 at 3:14 PM Ashutosh Bapat
<ashutosh.bapat.oss@gmail.com> wrote:
>
> On Thu, Dec 18, 2025 at 2:45 PM Ashutosh Bapat
> <ashutosh.bapat.oss@gmail.com> wrote:
> >
> >
> > >
> > > I did another investigation about whether this level of checking is
> > > necessary. I think according to the letter of the SQL standard, the
> > > typmods must indeed match. It seems Oracle does not check (the example
> > > mentioned above came from an Oracle source). But I think it's okay to
> > > keep the check. In PostgreSQL, it is much less common to write like
> > > varchar(1000). And we can always consider relaxing it later.
> >
> > +1.
> >
> > Attached patch adds a couple more test statements.
> >
>
> Squashed this into the main patchset.
>
> > >
> > > 2) I had it in my notes to consider whether we should support the colon
> > > syntax for label expressions. I think we might have talked about that
> > > before.
> > >
> > > I'm now leaning toward not supporting it in the first iteration. I
> > > don't know that we have fully explored possible conflicts with host
> > > variable syntax in ecpg and psql and the like. Maybe avoid that for now.
> > >
> >
> > I was aware of ecpg and I vaguely remember we fixed something in ECPG
> > to allow : in MATCH statement. Probably following changes in
> > psqlscan.l and pgc.l
> > -self [,()\[\].;\:\+\-\*\/\%\^\<\>\=]
> > +self [,()\[\].;\:\|\+\-\*\/\%\^\<\>\=]
> >
> > Those changes add | after : (and not the : itself) so maybe they are
> > not about supporting : . Do you remember what those are?
>
> I reverted those changes from both the files and ran "meson test". I
> did not observe any failure. It seems those changes are not needed.
> But adding them as a separate commit (0004) in case CI bot reveals any
> failures without them.
>
> I noticed that there were no ECPG tests for SQL/PGQ. Added a basic
> test in patch 0003.
>
> >
> > I spotted some examples that use : in ddl.sgml.
> > <programlisting>
> > SELECT customer_name FROM GRAPH_TABLE (myshop MATCH
> > (c:customer)-[:has]->(o:"order" WHERE o.ordered_when = current_date)
> > COLUMNS (c.name AS customer_name));
> > </programlisting>
> >
> > The query demonstrates that one can use label names in a way that will
> > make the pattern look like an English sentence. Replacing : with IS
> > defeats that purpose.
> >
> > As written in that paragraph, the labels serve the purpose of exposing
> > the table with a different logical view (using different label and
> > property names). So we need that paragraph, but I think we should
> > change the example to use IS instead of :. Attached is suggested
> > minimal change, but I am not happy with it. Another possibility is we
> > completely remove that paragraph; I don't think we need to discuss all
> > possible usages the users will come up with.
> >
> > The patch changes one more instance of : by IS. But that's straight forward.
> >
> > In ddl.sgml I noticed a seemingly incomplete sentence
> > A property graph is a way to represent database contents, instead of using
> > relational structures such as tables.
> >
> > Represent the contents as what? I feel the complete sentence should be
> > one of the following
> > property graph is a way to represent database contents as a graph,
> > instead of representing those as relational structures OR
> > property graph is another way to represent database contents instead
> > of using relational structures such as tables
> >
> > But I can't figure out what was originally intended.
>
>
> 0002 contains some edits to this part of documentation. I think the
> paragraph reads better than before. Let me know what you think.
>
> Please let me know which of 0002 to 0004 look good to you. I will
> squash those into the patchset in the next version.
The previous patchset had a whitespace difference in ECPG expected
output files. Fixed in the attached patchset.
--
Best Wishes,
Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Thank you for the detailed review and feedback.
Hi Henson,
Thanks a lot for your interest in SQL/PGQ patches. Your expertise will
certainly help.
On Fri, Dec 26, 2025 at 6:03 PM Henson Choi <assam258@gmail.com> wrote:
>
> Following up on my Dec 24 email - three features completed:
>
> 1. LABELS() function
> - Returns text[] of element labels
> - Fixed privilege checking from previous version
> - Enables optimizer pushdown for branch pruning
>
> 2. PROPERTY_NAMES() function
> - Returns text[] of property names
> - Similar approach to LABELS()
>
I could not find specification of these functions in SQL/PGQ standard.
It's a large document and I might be missing something. Can you please
point me to the relevant sections?
standard. I was inspired by similar functions in Cypher (labels(), keys())
and Oracle's PGQL (which has LABELS(), though Oracle is moving toward
SQL/PGQ compliance as well).
The attached code demonstrates that through query rewrite, these functions
can enable planner-level table pruning optimizations. This becomes
particularly valuable for client applications - GUI tools could use label
names as host variables for flexible label-based filtering, and
PROPERTY_NAMES() (similar to Cypher's keys()) would enable dynamic property
inspection for display or selective querying of elements with specific
properties.
(Cypher) query models, I don't think we need to strictly exclude
semi-structured patterns that work well within the structured framework.
Whether this should be proposed as a future SQL/PGQ standard extension or
remain a PostgreSQL-specific extension is worth discussion. Given the
practical utility demonstrated in graph query deployments, there might be
value in standardizing such introspection functions.
Similarly, I'd suggest considering Cypher's SHORTEST PATH for future
SQL/PGQ standards. If we treat SHORTEST PATH as a specialized join type
in SQL and handle it through query rewrite, PostgreSQL's existing planner
infrastructure could support it efficiently. This approach has been proven
in practice and could be a valuable addition to the next standard revision.
> 3. Multiple path patterns
> - Syntax: MATCH (a)->(b), (b)->(c)
> - Implements SQL/PGQ standard feature (was TODO)
>
This path pattern list feature is discussed in section 10.4 of the
standard. I think supporting this feature would be a good addition to
SQL/PGQ compliance. The current patchset is already large. I (and
AFAIK Peter as well) am focusing on getting that patchset in a
committable shape. Once committed, it will facilitate adding features
like path pattern list, quantified path patterns, label conjunction
etc. as incremental relatively smaller commits.
Since you could build one of the complex features without changing a
lot of earlier implementation, it validates that the basic
implementation is extensible and yet robust. Thanks for that
validation.
extensibility.
The way you have implemented it, it can lead to a path pattern with
two vertex patterns next to each other without an interleaving edge
pattern. That would throw an error or assertion. If you try path
patterns without a common vertex, you will get that error. That is not
covered by your tests. In such cases, the paths should end up being
full-joined rather than concatenated. I don't see it being implemented
that way. I think more work is needed here.
You're absolutely right, and I apologize for the hasty implementation.
I agree that merging this after the current commitfest makes more sense -
it keeps the core patchset focused and reviewable. I'll rework this
properly with correct handling for disjoint patterns and full join logic.
Having more people who can maintain and extend SQL/PGQ reduces the
risk for both the community and PostgreSQL itself. When I have a revised
version ready, would you be willing to review it again?
[1] https://www.postgresql.org/message-id/CAExHW5sr+dJPCFw2OqXUfPPqPks8qmsivaAYhRiBdFANcX8RHw@mail.gmail.com
--
Best Wishes,
Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Henson,
Thanks for your systematic review.
On Wed, Dec 31, 2025 at 11:53 AM Henson Choi wrote:
>
> Overall assessment: GOOD
Glad to know that.
> - Test Coverage: Good (90.5% line coverage, ~180 test cases)
Thanks for the coverage analysis. Looks good right now. But see below.
> 2.1 Critical / Major
> (None)
Great.
>
> 2.2 Minor Issues
>
> #1 [Code] src/backend/commands/propgraphcmds.c:1632
> FIXME: Missing index for plppropid column causes sequential scan.
> Decision needed: (a) add index, or (c) allow seq scan for rare path.
The path is rare enough that I think we can allow the seq scan. Given
that Peter has marked it as FIXME, it seems we will keep it as is for
now, but will revisit if performance becomes an issue. Peter, please
correct me if I'm wrong.
>
> #2 [Doc] doc/src/sgml/ref/alter_property_graph.sgml:286
> Compatibility section incorrectly states "CREATE PROPERTY GRAPH"
> Should be: "ALTER PROPERTY GRAPH"
>
That's right. Fixed.
> #3 [Doc] doc/src/sgml/ref/alter_property_graph.sgml:65
> Synopsis shows VERTEX/NODE and EDGE/RELATIONSHIP as separate clauses,
> but Description merges them as {VERTEX|NODE|EDGE|RELATIONSHIP}.
Their syntax is slightly different hence they are separate in
Synopsis. If we separate them in the Description, we might have to
repeat the same text twice. Having them merged in the Description
makes it more concise without losing any clarity or meaning. I think
we can keep it as is. What do you think?
>
> #4 [Doc] doc/src/sgml/ref/alter_property_graph.sgml:80
> Grammar error: "the graph removed" should be "the graph is removed"
Right. Fixed.
>
> #5 [Doc] doc/src/sgml/queries.sgml:2929,2931
> TODO comments for unimplemented features without clear limitation notes.
Those TODOs are not visible to users. I think they serve as
placeholders to add the documentation when the features are
implemented. We may want to remove them, but I see no harm in keeping
them for now. Peter, what do you think?
>
> #6 [Doc] doc/src/sgml/ddl.sgml:5717
> Typo: "infrastucture" should be "infrastructure"
>
Fixed. Thanks for catching it.
> 2.3 Alternative Approaches for Discussion
>
> #1 Support CREATE PROPERTY GRAPH IF NOT EXISTS
> Rationale: PostgreSQL-style extension, consistent with other DDL.
>
I think this will be good-to-have for consistency across DDLs.
However, I think it is better to discuss and implement it separately
since lack of it does not block the main functionality of property
graphs. Meantime users can DROP and CREATE. There are other DDLs which
do not have this support. What do you think?
> #2 Return 0 rows for non-existent labels instead of error
> Current: SELECT * FROM GRAPH_TABLE(g MATCH (a:NonExistent) ...) raises error
> Alternative: Return empty result set instead
> Rationale: Better for exploratory queries, similar to SQL WHERE on
> non-existent values returning 0 rows rather than error.
I think this makes sense in a proper graph database where the labels
are not predefined. However, in property graphs the labels, the
properties associated with them and data types of those properties are
predefined in the graph schema. If the specified label does not exist
in the graph schema, we can not determine what properties are
associated with it and their data types. In turn we can not determine
the shape of the result set, which is essential for reporting even 0
rows. Hence the error instead of 0 rows. Oracle has similar behaviour.
>
> #3 Return 0 rows when same variable has different labels
> Current: SELECT * FROM GRAPH_TABLE(g MATCH (a:Person)-[e]-(a:Company) ...)
> raises error because variable 'a' has conflicting labels.
> Alternative: Return empty result set instead
> Rationale: Logically, a node cannot be both Person AND Company,
> so 0 rows is the correct result. Consistent with standard SQL
> WHERE semantics (impossible condition = 0 rows, not error).
>
In such a case 0 rows isn't a correct result. According to the
standard, variable a is bound to all the nodes that have both the
labels. This is label conjunction, a feature we don't support right
now. Hence the "unsupported feature" error. I expect that some day we
will implement label conjunction, and then the same query will return
non-zero rows if there are nodes with both labels.
> -------------------------------------------------------------------------------
> TEMP graph CREATE TEMP PROPERTY GRAPH Medium
Done
> TEMP graph TEMP graph with permanent table reference Medium
Done
> TEMP graph ALTER ADD permanent table to TEMP graph Medium
Done
> CASCADE DROP ... CASCADE (dependent view cascade) Low
Done
> RESTRICT DROP ... RESTRICT (dependent object error) Low
Done, but without explicit RESTRICT keyword since it's default behavior.
- Tests specifying NODE/RELATIONSHIP instead of VERTEX/EDGE (Low priority)
Done
> propgraphcmds.c:136,179,254-262 TEMP table in graph creation Auto TEMP conversion
Done
> propgraphcmds.c:1323,1364 ALTER ADD TEMP to perm graph Error branch
Done
> propgraphcmds.c:724-734 CREATE without LABEL clause Default label else
This should be covered. There are several CREATE PROPERTY GRAPH
statements without LABEL clauses.
> propgraphcmds.c:1300,1303 ALTER IF EXISTS non-existent missing_ok branch
This is unreachable since the syntax is not supported. The only IF
EXISTS variant supported is ALTER PROPERTY GRAPH IF EXISTS ... SET
SCHEMA .... Added a test for the same.
> propgraphcmds.c:116 CREATE UNLOGGED attempt UNLOGGED error
Done
> execMain.c:1162-1163 DML on graph RELKIND_PROPGRAPH
This is unreachable since a property graph reference is only allowed
in GRAPH_TABLE().
> rewriteGraphTable.c:120 Multiple path patterns Length check
Done
> rewriteGraphTable.c:205 Quantifier usage Quantifier error
Done
> ruleutils.c:7939-7963 Complex label VIEW deparsing T_BoolExpr branch
>
Done
Can you please check whether the uncovered lines are now covered?
> - Tests executed: run_pgq_tests.sql
What's this test? It's not in the patchset. Also you might want to try
002_pg_upgrade.
>
> +----------------------------------------------------------+
> | SQL/PGQ Implementation: NO MEMORY LEAKS DETECTED |
> +----------------------------------------------------------+
Great. Thanks for confirming.
>>
>> On Fri, Dec 26, 2025 at 6:03 PM Henson Choi wrote:
>> >
>> > 1. LABELS() function
>> > - Returns text[] of element labels
>> > - Fixed privilege checking from previous version
>> > - Enables optimizer pushdown for branch pruning
>> >
>> > 2. PROPERTY_NAMES() function
>> > - Returns text[] of property names
>> > - Similar approach to LABELS()
>> >
>>
>> I could not find specification of these functions in SQL/PGQ standard.
>> It's a large document and I might be missing something. Can you please
>> point me to the relevant sections?
>>
>
> You're correct - LABELS() and PROPERTY_NAMES() are not in the SQL/PGQ
> standard. I was inspired by similar functions in Cypher (labels(), keys())
> and Oracle's PGQL (which has LABELS(), though Oracle is moving toward
> SQL/PGQ compliance as well).
>
> The attached code demonstrates that through query rewrite, these functions
> can enable planner-level table pruning optimizations. This becomes
> particularly valuable for client applications - GUI tools could use label
> names as host variables for flexible label-based filtering, and
> PROPERTY_NAMES() (similar to Cypher's keys()) would enable dynamic property
> inspection for display or selective querying of elements with specific
> properties.
>
> While there's a distinction between structured (SQL/PGQ) and semi-structured
> (Cypher) query models, I don't think we need to strictly exclude
> semi-structured patterns that work well within the structured framework.
> Whether this should be proposed as a future SQL/PGQ standard extension or
> remain a PostgreSQL-specific extension is worth discussion. Given the
> practical utility demonstrated in graph query deployments, there might be
> value in standardizing such introspection functions.
While these functions are useful with semistructured frameworks like
Cypher, I am not sure how useful they are in structured framework like
SQL/PGQ. In SQL/PGQ, the graph schema is predefined and known to the
users. Hence users know what labels and properties exist in the graph.
However, if they become part of the standard, their chances of getting
accepted in the PostgreSQL core will increase.
Even if we keep them out of core, I think we should be able to
implement them as stable functions in an extension and still benefit
from planner optimizations you mentioned.
>
> Similarly, I'd suggest considering Cypher's SHORTEST PATH for future
> SQL/PGQ standards. If we treat SHORTEST PATH as a specialized join type
> in SQL and handle it through query rewrite, PostgreSQL's existing planner
> infrastructure could support it efficiently. This approach has been proven
> in practice and could be a valuable addition to the next standard revision.
IIRC there is SQL/PGQ standard specification for shortest path. We
should implement that when we get to it.
>
> That was my finding as well - the architecture is well-designed for
> extensibility.
Great. Thanks for the confirmation.
>
> Having more people who can maintain and extend SQL/PGQ reduces the
> risk for both the community and PostgreSQL itself. When I have a revised
> version ready, would you be willing to review it again?
>
We will need to prioritize the features to be implemented next. This
looks like a useful pattern to support. I believe this will appear
higher in the priority list, thus worth reviewing.
The patches are thus
0001 - same as previous except a. addition of new lines in
create_property_graph.sql for consistency with other sections in that
file, b. some minor corrections suggested by Hensen.
0002 - fixes : references and improves documentation. I think we can
merge this into 0001 after a quick review from Peter
0003 - ECPG test. This might need a bit of review. The patch is large
because of the .c and .err files.
0004 - This reverts back ECPG and PSQL lexer changes introduced in
0001. Does not show any failure even in the test case added by 0003.
Those changes seem unnecessary. Peter, can you please confirm.
0005 - Additional test cases for code coverage as pointed out by
Hensen's report.
--
Best Wishes,
Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Thank you for the detailed responses and for addressing the test coverage items so quickly.
Hi Henson,
Thanks for your systematic review.
On Wed, Dec 31, 2025 at 11:53 AM Henson Choi <assam258@gmail.com> wrote:
>
> Overall assessment: GOOD
Glad to know that.
> - Test Coverage: Good (90.5% line coverage, ~180 test cases)
Thanks for the coverage analysis. Looks good right now. But see below.
> 2.1 Critical / Major
> (None)
Great.
>
> 2.2 Minor Issues
>
> #1 [Code] src/backend/commands/propgraphcmds.c:1632
> FIXME: Missing index for plppropid column causes sequential scan.
> Decision needed: (a) add index, or (c) allow seq scan for rare path.
The path is rare enough that I think we can allow the seq scan. Given
that Peter has marked it as FIXME, it seems we will keep it as is for
now, but will revisit if performance becomes an issue. Peter, please
correct me if I'm wrong.
>
> #2 [Doc] doc/src/sgml/ref/alter_property_graph.sgml:286
> Compatibility section incorrectly states "CREATE PROPERTY GRAPH"
> Should be: "ALTER PROPERTY GRAPH"
>
That's right. Fixed.
> #3 [Doc] doc/src/sgml/ref/alter_property_graph.sgml:65
> Synopsis shows VERTEX/NODE and EDGE/RELATIONSHIP as separate clauses,
> but Description merges them as {VERTEX|NODE|EDGE|RELATIONSHIP}.
Their syntax is slightly different hence they are separate in
Synopsis. If we separate them in the Description, we might have to
repeat the same text twice. Having them merged in the Description
makes it more concise without losing any clarity or meaning. I think
we can keep it as is. What do you think?
>
> #4 [Doc] doc/src/sgml/ref/alter_property_graph.sgml:80
> Grammar error: "the graph removed" should be "the graph is removed"
Right. Fixed.
>
> #5 [Doc] doc/src/sgml/queries.sgml:2929,2931
> TODO comments for unimplemented features without clear limitation notes.
Those TODOs are not visible to users. I think they serve as
placeholders to add the documentation when the features are
implemented. We may want to remove them, but I see no harm in keeping
them for now. Peter, what do you think?
>
> #6 [Doc] doc/src/sgml/ddl.sgml:5717
> Typo: "infrastucture" should be "infrastructure"
>
Fixed. Thanks for catching it.
> 2.3 Alternative Approaches for Discussion
>
> #1 Support CREATE PROPERTY GRAPH IF NOT EXISTS
> Rationale: PostgreSQL-style extension, consistent with other DDL.
>
I think this will be good-to-have for consistency across DDLs.
However, I think it is better to discuss and implement it separately
since lack of it does not block the main functionality of property
graphs. Meantime users can DROP and CREATE. There are other DDLs which
do not have this support. What do you think?
> #2 Return 0 rows for non-existent labels instead of error
> Current: SELECT * FROM GRAPH_TABLE(g MATCH (a:NonExistent) ...) raises error
> Alternative: Return empty result set instead
> Rationale: Better for exploratory queries, similar to SQL WHERE on
> non-existent values returning 0 rows rather than error.
I think this makes sense in a proper graph database where the labels
are not predefined. However, in property graphs the labels, the
properties associated with them and data types of those properties are
predefined in the graph schema. If the specified label does not exist
in the graph schema, we can not determine what properties are
associated with it and their data types. In turn we can not determine
the shape of the result set, which is essential for reporting even 0
rows. Hence the error instead of 0 rows. Oracle has similar behaviour.
However, I think it's worth extra consideration when behavior differs from Cypher -
the similar syntax might confuse users despite the fundamental architectural differences.
>
> #3 Return 0 rows when same variable has different labels
> Current: SELECT * FROM GRAPH_TABLE(g MATCH (a:Person)-[e]-(a:Company) ...)
> raises error because variable 'a' has conflicting labels.
> Alternative: Return empty result set instead
> Rationale: Logically, a node cannot be both Person AND Company,
> so 0 rows is the correct result. Consistent with standard SQL
> WHERE semantics (impossible condition = 0 rows, not error).
>
In such a case 0 rows isn't a correct result. According to the
standard, variable a is bound to all the nodes that have both the
labels. This is label conjunction, a feature we don't support right
now. Hence the "unsupported feature" error. I expect that some day we
will implement label conjunction, and then the same query will return
non-zero rows if there are nodes with both labels.
code details in my review. Please always view my tests critically, as I will your
code - that's how we build better software together. I respect your attention to detail.
> -------------------------------------------------------------------------------
> TEMP graph CREATE TEMP PROPERTY GRAPH Medium
Done
> TEMP graph TEMP graph with permanent table reference Medium
Done
> TEMP graph ALTER ADD permanent table to TEMP graph Medium
Done
> CASCADE DROP ... CASCADE (dependent view cascade) Low
Done
> RESTRICT DROP ... RESTRICT (dependent object error) Low
Done, but without explicit RESTRICT keyword since it's default behavior.
- Tests specifying NODE/RELATIONSHIP instead of VERTEX/EDGE (Low priority)
Done
> propgraphcmds.c:136,179,254-262 TEMP table in graph creation Auto TEMP conversion
Done
> propgraphcmds.c:1323,1364 ALTER ADD TEMP to perm graph Error branch
Done
> propgraphcmds.c:724-734 CREATE without LABEL clause Default label else
This should be covered. There are several CREATE PROPERTY GRAPH
statements without LABEL clauses.
> propgraphcmds.c:1300,1303 ALTER IF EXISTS non-existent missing_ok branch
This is unreachable since the syntax is not supported. The only IF
EXISTS variant supported is ALTER PROPERTY GRAPH IF EXISTS ... SET
SCHEMA .... Added a test for the same.
> propgraphcmds.c:116 CREATE UNLOGGED attempt UNLOGGED error
Done
> execMain.c:1162-1163 DML on graph RELKIND_PROPGRAPH
This is unreachable since a property graph reference is only allowed
in GRAPH_TABLE().
> rewriteGraphTable.c:120 Multiple path patterns Length check
Done
> rewriteGraphTable.c:205 Quantifier usage Quantifier error
Done
> ruleutils.c:7939-7963 Complex label VIEW deparsing T_BoolExpr branch
>
Done
Can you please check whether the uncovered lines are now covered?
> - Tests executed: run_pgq_tests.sql
What's this test? It's not in the patchset. Also you might want to try
002_pg_upgrade.
>
> +----------------------------------------------------------+
> | SQL/PGQ Implementation: NO MEMORY LEAKS DETECTED |
> +----------------------------------------------------------+
Great. Thanks for confirming.
>>
>> On Fri, Dec 26, 2025 at 6:03 PM Henson Choi <assam258@gmail.com> wrote:
>> >
>> > 1. LABELS() function
>> > - Returns text[] of element labels
>> > - Fixed privilege checking from previous version
>> > - Enables optimizer pushdown for branch pruning
>> >
>> > 2. PROPERTY_NAMES() function
>> > - Returns text[] of property names
>> > - Similar approach to LABELS()
>> >
>>
>> I could not find specification of these functions in SQL/PGQ standard.
>> It's a large document and I might be missing something. Can you please
>> point me to the relevant sections?
>>
>
> You're correct - LABELS() and PROPERTY_NAMES() are not in the SQL/PGQ
> standard. I was inspired by similar functions in Cypher (labels(), keys())
> and Oracle's PGQL (which has LABELS(), though Oracle is moving toward
> SQL/PGQ compliance as well).
>
> The attached code demonstrates that through query rewrite, these functions
> can enable planner-level table pruning optimizations. This becomes
> particularly valuable for client applications - GUI tools could use label
> names as host variables for flexible label-based filtering, and
> PROPERTY_NAMES() (similar to Cypher's keys()) would enable dynamic property
> inspection for display or selective querying of elements with specific
> properties.
>
> While there's a distinction between structured (SQL/PGQ) and semi-structured
> (Cypher) query models, I don't think we need to strictly exclude
> semi-structured patterns that work well within the structured framework.
> Whether this should be proposed as a future SQL/PGQ standard extension or
> remain a PostgreSQL-specific extension is worth discussion. Given the
> practical utility demonstrated in graph query deployments, there might be
> value in standardizing such introspection functions.
While these functions are useful with semistructured frameworks like
Cypher, I am not sure how useful they are in structured framework like
SQL/PGQ. In SQL/PGQ, the graph schema is predefined and known to the
users. Hence users know what labels and properties exist in the graph.
However, if they become part of the standard, their chances of getting
accepted in the PostgreSQL core will increase.
Even if we keep them out of core, I think we should be able to
implement them as stable functions in an extension and still benefit
from planner optimizations you mentioned.
I raised this as something worth considering - if someone can participate in the next
standard revision, I believe these functions are worth discussing there.
>
> Similarly, I'd suggest considering Cypher's SHORTEST PATH for future
> SQL/PGQ standards. If we treat SHORTEST PATH as a specialized join type
> in SQL and handle it through query rewrite, PostgreSQL's existing planner
> infrastructure could support it efficiently. This approach has been proven
> in practice and could be a valuable addition to the next standard revision.
IIRC there is SQL/PGQ standard specification for shortest path. We
should implement that when we get to it.
have access to the standard document. Could you share the relevant excerpt from the
specification?
Regarding implementation: this would require adding two non-standard Executor nodes as
a SQL JOIN type before it can be rewritten. This is a significant undertaking - likely
several times larger than the current PGQ code modifications. Fortunately, I have prior
experience implementing shortest path in PostgreSQL, so I understand the complexity
involved. Since the SQL layer work needs to be done first, I think we should start
discussing this two-track approach now, even though the actual implementation will take
considerable time.
>
> That was my finding as well - the architecture is well-designed for
> extensibility.
Great. Thanks for the confirmation.
>
> Having more people who can maintain and extend SQL/PGQ reduces the
> risk for both the community and PostgreSQL itself. When I have a revised
> version ready, would you be willing to review it again?
>
We will need to prioritize the features to be implemented next. This
looks like a useful pattern to support. I believe this will appear
higher in the priority list, thus worth reviewing.
prioritization or need my input.
The patches are thus
0001 - same as previous except a. addition of new lines in
create_property_graph.sql for consistency with other sections in that
file, b. some minor corrections suggested by Hensen.
0002 - fixes : references and improves documentation. I think we can
merge this into 0001 after a quick review from Peter
0003 - ECPG test. This might need a bit of review. The patch is large
because of the .c and .err files.
0004 - This reverts back ECPG and PSQL lexer changes introduced in
0001. Does not show any failure even in the test case added by 0003.
Those changes seem unnecessary. Peter, can you please confirm.
0005 - Additional test cases for code coverage as pointed out by
Hensen's report.
--
Best Wishes,
Ashutosh Bapat
might be overreaching, I do so for two reasons: (a) I don't have access to the
SQL/PGQ standard document, and (b) my implementation-level experience is primarily
with Cypher. However, if I feel this dissonance, users coming from Cypher will
likely experience the same confusion. I hope you'll consider this user perspective
valuable, even when the technical decisions differ.
Re: SQL Property Graph Queries (SQL/PGQ)
On Fri, Jan 2, 2026 at 6:53 PM Henson Choi wrote: > > When I raise issues about differences from Cypher, even when I sense my suggestions > might be overreaching, I do so for two reasons: (a) I don't have access to the > SQL/PGQ standard document, and (b) my implementation-level experience is primarily > with Cypher. However, if I feel this dissonance, users coming from Cypher will > likely experience the same confusion. I hope you'll consider this user perspective > valuable, even when the technical decisions differ. I think all these issues are worth raising on pgsql-hackers. Many users who are using Cypher may want to use PostgreSQL + SQL/PGQ as their graph database. All these inputs are valuable. Let me summarise my thoughts briefly over here. IMO, at a higher level, we could leverage Apache/AGE-like extensions to provide Cypher compatibility on top of SQL/PGQ. The required functionality from SQL/PGQ (directly or indirectly) can be implemented in the core. For example, the core will throw an error when a label is not defined, but Apache/AGE may detect such labels beforehand, avoid translating the query to SQL/PGQ and return 0 rows in such a case. Or Apache/AGE may add stable functions for labels() and property_names(), but use SQL/PGQ catalogs for implementation. I envision the relation between Apache/AGE and SQL/PGQ evolving similarly to how the relation between pg_partman and built-in partitioning evolved. Others may have different opinions. We may even want to weigh each feature/functionality separately. How to support Cypher queries on PostgreSQL in the context of SQL/PGQ seems to be a broader topic worth a discussion of its own. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Fri, Jan 2, 2026 at 6:53 PM Henson Choi <assam258@gmail.com> wrote:
>
> When I raise issues about differences from Cypher, even when I sense my suggestions
> might be overreaching, I do so for two reasons: (a) I don't have access to the
> SQL/PGQ standard document, and (b) my implementation-level experience is primarily
> with Cypher. However, if I feel this dissonance, users coming from Cypher will
> likely experience the same confusion. I hope you'll consider this user perspective
> valuable, even when the technical decisions differ.
I think all these issues are worth raising on pgsql-hackers. Many
users who are using Cypher may want to use PostgreSQL + SQL/PGQ as
their graph database. All these inputs are valuable. Let me summarise
my thoughts briefly over here.
perspective is considered valuable.
IMO, at a higher level, we could leverage Apache/AGE-like extensions
to provide Cypher compatibility on top of SQL/PGQ. The required
functionality from SQL/PGQ (directly or indirectly) can be implemented
in the core. For example, the core will throw an error when a label is
not defined, but Apache/AGE may detect such labels beforehand, avoid
translating the query to SQL/PGQ and return 0 rows in such a case. Or
Apache/AGE may add stable functions for labels() and property_names(),
but use SQL/PGQ catalogs for implementation.
compatibility concerns on top of SQL/PGQ core functionality seems
pragmatic.
I envision the relation between Apache/AGE and SQL/PGQ evolving
similarly to how the relation between pg_partman and built-in
partitioning evolved. Others may have different opinions. We may even
want to weigh each feature/functionality separately. How to support
Cypher queries on PostgreSQL in the context of SQL/PGQ seems to be a
broader topic worth a discussion of its own.
notice differences from Cypher, particularly from a user experience
standpoint. However, I fully respect that the community will make the
final decisions on these matters, weighing standard compliance,
implementation complexity, and PostgreSQL's design principles.
--
Best Wishes,
Ashutosh Bapat
I've been caught up with work commitments at my company, but I'll get
back to it as soon as possible.
Looking forward to contributing to this broader discussion.
Best regards,
Re: SQL Property Graph Queries (SQL/PGQ)
I think it may be a bit early for this, but I wanted to share this design
document now so we can revisit and discuss when the time is right.
===================================================================
Variable Length Edge (VLE) Implementation Strategies for PostgreSQL
===================================================================
1. Overview
-----------
This document describes two implementation strategies for Variable
Length Edge (VLE) traversal in PostgreSQL-based graph databases.
VLE Query Example:
MATCH (a)-[*1..5]->(b) RETURN a, b
MATCH p = (a)-[:knows*]->(b) RETURN p
Two implementation approaches:
1. Unoptimized: Query rewriting to WITH RECURSIVE (CTE)
2. Optimized: Custom executor node with DFS algorithm
2. Unoptimized Approach: WITH RECURSIVE Rewriting
-------------------------------------------------
2.1 Query Transformation
Cypher query:
MATCH (a:person)-[:knows*1..3]->(b) WHERE a.name = 'Alice' RETURN b
Rewritten SQL using WITH RECURSIVE:
WITH RECURSIVE vle_paths AS (
-- Base case: start vertices
SELECT v.id as start_vid,
v.id as end_vid,
ARRAY[] as edge_ids,
ARRAY[] as edges,
0 as depth
FROM person v
WHERE name = 'Alice'
UNION ALL
-- Recursive case: expand one hop
SELECT p.start_vid,
e.end_id,
p.edge_ids || e.id,
p.edges || e,
p.depth + 1
FROM vle_paths p
JOIN knows e ON p.end_vid = e.start_id
WHERE p.depth < 3
AND e.id <> ALL(p.edge_ids) -- Edge uniqueness check
)
SEARCH DEPTH FIRST BY end_vid SET ordercol
SELECT b.*, edges
FROM vle_paths
JOIN person b ON b.id = end_vid
WHERE depth BETWEEN 1 AND 3;
2.2 Execution Plan
Hash Join (b vertex lookup)
Hash Cond: (end_vid = b.id)
-> CTE Scan on vle_paths
Filter: (depth >= 1 AND depth <= 3)
Sort Key: ordercol -- SEARCH DEPTH FIRST ordering
CTE vle_paths
Recursive Union
Seq Scan on person v
Filter: (name = 'Alice')
Hash Join
Hash Cond: (p.end_vid = e.start_id)
Filter: (e.id <> ALL(p.edge_ids)) AND (p.depth < 3)
WorkTable Scan on vle_paths p
Hash
Seq Scan on knows e
-> Hash
-> Seq Scan on person b
2.3 Problems
┌─────────────────────┬──────────────────────────────────────────┐
│ Problem │ Description │
├─────────────────────┼──────────────────────────────────────────┤
│ Execution Model │ BFS execution (set-based iteration) │
│ │ SEARCH DEPTH FIRST changes output order │
│ │ only, not execution or memory model │
├─────────────────────┼──────────────────────────────────────────┤
│ No Backtracking │ CTE stores all intermediate results │
│ │ Cannot restore previous state │
├─────────────────────┼──────────────────────────────────────────┤
│ Memory Usage │ O(total_paths) - all partial paths │
│ │ Exponential growth with depth │
├─────────────────────┼──────────────────────────────────────────┤
│ Edge Uniqueness │ e.id <> ALL(p.edge_ids) │
│ │ O(path_length) comparison per row │
├─────────────────────┼──────────────────────────────────────────┤
│ No Streaming │ Must complete all iterations before │
│ │ returning results │
├─────────────────────┼──────────────────────────────────────────┤
│ Array Operations │ p.edge_ids || e.id creates new array │
│ │ O(n) copy per iteration │
└─────────────────────┴──────────────────────────────────────────┘
2.4 Memory Analysis
Graph: Tree with branching factor B=10, max depth D=5
Iteration 1: 10 rows (depth 1)
Iteration 2: 100 rows (depth 2)
Iteration 3: 1,000 rows (depth 3)
Iteration 4: 10,000 rows (depth 4)
Iteration 5: 100,000 rows (depth 5)
Total rows in WorkTable: 111,110
Each row contains: start_vid + end_vid + edge_ids array + edges array
Memory = 111,110 * (8 + 8 + avg_path_len * 8 + avg_path_len * edge_size)
3. Optimized Approach: Custom Executor Node
-------------------------------------------
3.1 Design Principle
Instead of query rewriting, implement a dedicated executor node that:
- Performs true DFS traversal with backtracking
- Maintains only current path in memory
- Uses PlanState stack for depth-wise edge scanning
- Yields results incrementally (streaming)
3.2 Plan Node Structure
┌────────────────────────────────────────────────────────┐
│ Nested Loop (b lookup) │
└────────────────────────────────────────────────────────┘
│ │
│ outer │ inner
▼ ▼
┌──────────────────────────────┐ ┌─────────────────────────┐
│ VLEPlan Node │ │ IndexScan on person │
│ - DFS with PlanState stack │ │ (b vertex lookup) │
│ - O(depth) memory │ └─────────────────────────┘
└──────────────────────────────┘
│ │
outer │ │ inner (edge subplan)
▼ ▼
┌───────────┐ ┌───────────────────────────┐
│ IndexScan │ │ IndexScan on knows │
│ (person a)│ │ (re-scanned per vertex) │
└───────────┘ └───────────────────────────┘
Execution Flow:
Outer plan returns vertex A
│
▼
VLEPlan performs DFS:
│
├──→ Push PlanState for depth 0 (edges from A)
│ │
│ ├──→ Find edge A->B, push PlanState for depth 1
│ │ │
│ │ ├──→ Find edge B->D, push PlanState for depth 2
│ │ │ │
│ │ │ └──→ No more edges, pop PlanState
│ │ │
│ │ ├──→ Continue B's PlanState, find B->E
│ │ │
│ │ └──→ Pop PlanState (B exhausted)
│ │
│ └──→ Continue A's PlanState, find A->C
│
└──→ Yield results when depth in [min, max]
3.3 Key Concept: PlanState Stack
The executor maintains a stack of inner subplan states (PlanState),
one per depth level. Each PlanState holds the scan position for
edges from that depth's vertex.
At each depth:
- Re-scan inner subplan with current vertex as parameter
- On finding an edge, push new PlanState for next depth
- On exhausting edges, pop PlanState and backtrack
Memory: Only current path + one PlanState per depth level
3.4 Execution Plan (Optimized)
EXPLAIN MATCH (a:person)-[:knows*1..3]->(b) WHERE a.name='Alice' RETURN b
Nested Loop (b vertex lookup)
-> VLEPlan (minDepth=1 maxDepth=3 direction=RIGHT)
-> Index Scan on person a (outer: start vertices)
Index Cond: (name = 'Alice')
-> Index Scan on knows e (inner: edge subplan)
Index Cond: (start_id = $current_vertex)
-> Index Scan on person b
Index Cond: (id = vle.end_vertex)
4. Comparison Summary
---------------------
┌─────────────────────┬─────────────────────────┬─────────────────────────┐
│ Aspect │ Unoptimized (CTE) │ Optimized (Executor) │
├─────────────────────┼─────────────────────────┼─────────────────────────┤
│ Implementation │ Query rewriting │ Custom executor node │
├─────────────────────┼─────────────────────────┼─────────────────────────┤
│ Traversal Order │ BFS (set-based) │ True DFS │
├─────────────────────┼─────────────────────────┼─────────────────────────┤
│ Backtracking │ Not possible │ PlanState stack pop/push│
├─────────────────────┼─────────────────────────┼─────────────────────────┤
│ Memory Usage │ O(B^D) all paths │ O(D) current path only │
├─────────────────────┼─────────────────────────┼─────────────────────────┤
│ Edge Uniqueness │ <> ALL(array) O(n) │ Array scan O(n) │
│ │ + array copy per row │ No array copy │
├─────────────────────┼─────────────────────────┼─────────────────────────┤
│ Result Streaming │ After all iterations │ Yield as found │
├─────────────────────┼─────────────────────────┼─────────────────────────┤
│ Code Complexity │ Low (rewriting only) │ High (new executor) │
├─────────────────────┼─────────────────────────┼─────────────────────────┤
│ PostgreSQL Changes │ None │ New plan/executor node │
└─────────────────────┴─────────────────────────┴─────────────────────────┘
5. Memory Usage Example
-----------------------
Graph: Social network, avg 100 friends per person
Query: MATCH (a)-[:friend*1..4]->(b) RETURN b
Unoptimized (CTE):
Depth 1: 100 rows
Depth 2: 10,000 rows
Depth 3: 1,000,000 rows
Depth 4: 100,000,000 rows (!)
Total: ~101 million partial paths in memory
Each path: vertex IDs + edge arrays (growing)
Optimized (DFS Executor):
PlanState stack: max 4 PlanState (~1KB each)
Path arrays: max 4 edges
Total: ~10KB regardless of graph size
6. Key Techniques Summary
-------------------------
┌────┬───────────────────────────┬────────────────────────────────────────┐
│ # │ Technique │ Benefit │
├────┼───────────────────────────┼────────────────────────────────────────┤
│ 1 │ Non-Directional Handling │ Support -- (bidirectional) edges │
│ 2 │ Multi-Label Scan │ Handle label inheritance │
│ 3 │ PlanState Stack Backtrack │ True DFS with O(depth) memory │
│ 4 │ Edge Uniqueness Check │ Prevent cycles efficiently │
│ 5 │ Property Filtering │ Early pruning during scan │
│ 6 │ Direction-Aware Traversal │ Support ->, <-, -- correctly │
│ 7 │ Result Streaming │ Return results without full compute │
│ 8 │ Depth Expansion │ Continue traversal to max depth │
└────┴───────────────────────────┴────────────────────────────────────────┘
7. Conclusion
-------------
The unoptimized CTE-based approach is simple to implement (query
rewriting only) but suffers from:
- Exponential memory growth with depth
- No true DFS traversal capability
- No result streaming
- Expensive array operations per row
The optimized executor-based approach requires more implementation
effort but provides:
- O(depth) memory usage regardless of graph size
- True DFS with backtracking capability
- Streaming results as they are discovered
- Efficient PlanState-based edge scanning
- Clean integration with PostgreSQL executor framework
For production graph database systems, the optimized approach is
essential for handling real-world graph sizes and traversal depths.
This document focuses on the conceptual design. Implementation details
such as PlanState cloning vs. scan position saving, memory allocation
strategies, and index structures are left for follow-up discussion.
Re: SQL Property Graph Queries (SQL/PGQ)
I think it may be a bit early for this, but I wanted to share this design
document now so we can revisit and discuss when the time is right.
=====================================================
Shortestpath Implementation Strategies for PostgreSQL
=====================================================
1. Overview
-----------
This document describes two implementation strategies for shortest path
queries in PostgreSQL-based graph databases.
Shortestpath Query Example:
MATCH p = shortestpath((a)-[*]->(b)) RETURN p
MATCH p = allshortestpaths((a)-[:knows*]->(b)) RETURN p
Two implementation approaches:
1. Unoptimized: Query rewriting to WITH RECURSIVE (CTE)
2. Optimized: Custom executor node with bidirectional BFS
2. Unoptimized Approach: WITH RECURSIVE Rewriting
-------------------------------------------------
2.1 Query Transformation
Cypher query:
MATCH p = shortestpath((a:person)-[:knows*]->(b:person))
WHERE a.name = 'Alice' AND b.name = 'Bob'
RETURN p
Rewritten SQL using WITH RECURSIVE:
WITH RECURSIVE sp_paths AS (
-- Base case: start vertex
SELECT v.id as start_vid,
v.id as end_vid,
ARRAY[v.id] as vertex_ids,
ARRAY[]::bigint[] as edge_ids,
0 as depth
FROM person v
WHERE name = 'Alice'
UNION ALL
-- Recursive case: expand one hop
SELECT p.start_vid,
e.end_id,
p.vertex_ids || e.end_id,
p.edge_ids || e.id,
p.depth + 1
FROM sp_paths p
JOIN knows e ON p.end_vid = e.start_id
WHERE e.end_id <> ALL(p.vertex_ids) -- Cycle prevention
)
SELECT vertex_ids, edge_ids, depth
FROM sp_paths
WHERE end_vid = (SELECT id FROM person WHERE name = 'Bob')
ORDER BY depth
LIMIT 1;
2.2 Execution Plan
Limit
-> Sort
Sort Key: depth
-> CTE Scan on sp_paths
Filter: (end_vid = $bob_id)
CTE sp_paths
Recursive Union
Seq Scan on person v
Filter: (name = 'Alice')
Hash Join
Hash Cond: (p.end_vid = e.start_id)
Filter: (e.end_id <> ALL(p.vertex_ids))
WorkTable Scan on sp_paths p
Hash
Seq Scan on knows e
2.3 Problems
┌─────────────────────┬──────────────────────────────────────────┐
│ Problem │ Description │
├─────────────────────┼──────────────────────────────────────────┤
│ Unidirectional │ Search expands only from start vertex │
│ │ Misses optimization from end vertex │
├─────────────────────┼──────────────────────────────────────────┤
│ Full Exploration │ Must explore all paths up to min depth │
│ │ before finding shortest │
├─────────────────────┼──────────────────────────────────────────┤
│ No Early Termination│ Cannot stop when shortest found │
│ │ CTE runs to completion │
├─────────────────────┼──────────────────────────────────────────┤
│ Memory Usage │ O(V) visited vertices per iteration │
│ │ All partial paths stored │
├─────────────────────┼──────────────────────────────────────────┤
│ Cycle Prevention │ <> ALL(array) grows with path length │
│ │ O(path_length) per edge check │
└─────────────────────┴──────────────────────────────────────────┘
2.4 Search Space Comparison
Unidirectional BFS (CTE):
Start ──────────────────────────────────────> End
╲ ╱
╲ Explores entire cone ╱
╲ from start ╱
╲ ╱
╲ Search space: O(B^D) ╱
╲ ╱
────────────────────────
Bidirectional BFS (Optimized):
Start ────────> <──────── End
╲ ╱╲ ╱
╲ ╱ ╲ ╱
╲ ╱ ╲ ╱
╲ ╱ Meet ╲ ╱
╲╱ Point ╲
Search space: O(2 * B^(D/2))
3. Optimized Approach: Custom Executor Node
-------------------------------------------
3.1 Design Principle
Instead of query rewriting, implement a dedicated executor node that:
- Performs bidirectional BFS from both start and end vertices
- Uses hash tables to track visited vertices from each direction
- Detects meeting point where both searches intersect
- Terminates early when shortest path is found
3.2 Plan Node Structure
┌────────────────────────────────────────────────────────────┐
│ ShortestpathPlan │
│ - Bidirectional BFS with dual hash tables │
│ - Early termination on path found │
└────────────────────────────────────────────────────────────┘
│ │
left │ │ right
▼ ▼
┌───────────────────────────┐ ┌───────────────────────────┐
│ Hash2Side (Left) │ │ Hash2Side (Right) │
│ - KeyTable + HashTable │ │ - KeyTable + HashTable │
│ - Forward direction │ │ - Reverse direction │
└───────────────────────────┘ └───────────────────────────┘
│ │
▼ ▼
┌───────────────────────────┐ ┌───────────────────────────┐
│ SubPlan (Forward) │ │ SubPlan (Reverse) │
│ Index Cond: │ │ Index Cond: │
│ start_id = $current │ │ end_id = $current │
└───────────────────────────┘ └───────────────────────────┘
Execution Flow:
Initialize:
Left HashTable = {start_vertex}
Right HashTable = {end_vertex}
│
▼
Expansion loop (smaller side first):
│
├──→ Compare |Left frontier| vs |Right frontier|
│ │
│ └──→ Expand smaller side
│ │
│ └──→ Check intersection with other side
│
├──→ Repeat until intersection found
│
└──→ Return shortest path(s)
3.3 Key Concept: Dual Hash Tables
The executor maintains two hash tables for bidirectional search:
┌─────────────────────────────────────────────────────────────┐
│ Left Direction (Start → End) │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ KeyTable: Previous hop vertices (expansion base) │ │
│ │ HashTable: Current hop results (newly discovered) │ │
│ └─────────────────────────────────────────────────────┘ │
├─────────────────────────────────────────────────────────────┤
│ Right Direction (End → Start) │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ KeyTable: Previous hop vertices (expansion base) │ │
│ │ HashTable: Current hop results (newly discovered) │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
After each hop:
- Swap KeyTable and HashTable (new base for next hop)
- Check for intersection between Left and Right HashTables
- If intersection found, reconstruct path through meeting point
3.4 Key Concept: Smaller Side Expansion
At each hop, expand from the direction with fewer frontier vertices.
This minimizes the total number of edges scanned.
Example (highly unbalanced tree):
Graph structure:
- Forward (Left->Right): branching factor = 100
- Backward (Right->Left): branching factor = 2
- Path distance: 6 hops
Simple alternating:
Hop 1: expand Left (1) -> Left=100, Right=1
Hop 2: expand Right (1) -> Left=100, Right=2
Hop 3: expand Left (100) -> Left=10,000, Right=2
Hop 4: expand Right (2) -> Left=10,000, Right=4
Hop 5: expand Left (10,000) -> Left=1,000,000, Right=4
Hop 6: expand Right (4) -> meet!
Total vertices expanded: 1 + 1 + 100 + 2 + 10,000 + 4 = 10,108
With smaller side expansion:
Hop 1: Left=1, Right=1 -> expand Left -> Left=100, Right=1
Hop 2: 1 < 100 -> expand Right -> Left=100, Right=2
Hop 3: 2 < 100 -> expand Right -> Left=100, Right=4
Hop 4: 4 < 100 -> expand Right -> Left=100, Right=8
Hop 5: 8 < 100 -> expand Right -> Left=100, Right=16
Hop 6: 16 < 100 -> expand Right -> meet!
Total vertices expanded: 1 + 1 + 2 + 4 + 8 + 16 = 32
Speedup: 10,108 / 32 = ~300x fewer vertices explored
3.5 Key Concept: Cycle Detection via Hash Lookup
Hash table insertion automatically prevents revisiting vertices.
Two tuple types in HashTable:
┌─────────────────────────────────────────────────────────────┐
│ Long Tuple (path data) │
│ ┌─────────┬─────────┬─────────────────────────────────┐ │
│ │ Header │ Graphid │ Edge Rowids (path to vertex) │ │
│ └─────────┴─────────┴─────────────────────────────────┘ │
├─────────────────────────────────────────────────────────────┤
│ Short Tuple (visited marker) │
│ ┌─────────┬─────────┐ │
│ │ Header │ Graphid │ <- No path data, just marker │
│ └─────────┴─────────┘ │
└─────────────────────────────────────────────────────────────┘
Insertion logic:
1. Inserting long tuple (with path):
- Check if short tuple (marker) exists for same Graphid
- If marker exists: reject insertion (already visited)
2. Inserting short tuple (marker):
- Insert marker first
- Remove all existing long tuples with same Graphid
- Vertex is now "locked" - no more paths to this vertex
Example:
Left Hop 1: Expand from A
HashTable = {B(long), C(long)} <- paths A->B, A->C
Left and Right meet at C -> shortest path found
Insert C(short) marker:
HashTable = {B(long), C(short)} <- C's long tuple removed
Later, another path tries to reach C (e.g., D->C):
-> C(short) marker exists -> insertion rejected
-> Already processed at shortest hop
Benefits:
- O(1) duplicate detection via hash lookup
- No separate "visited" set needed
- Automatic cleanup of superseded paths
- Memory efficient (markers are minimal size)
3.6 Key Concept: Batch Synchronization
When hash table exceeds memory, it splits into multiple batches.
Left and Right hash tables must have matching batch structure:
Problem without synchronization:
Left: nbatch=1 [all data in batch 0]
Right: nbatch=4 [batch0] [batch1] [batch2] [batch3]
-> Cannot find intersection (different batch structures)
Solution:
When Right splits into 4 batches, clone structure to Left:
Left: nbatch=4 [batch0] [batch1] [batch2] [batch3]
Right: nbatch=4 [batch0] [batch1] [batch2] [batch3]
| | | |
Join only matching batches
This ensures correct intersection detection across batch boundaries.
3.7 Execution Plan (Optimized)
EXPLAIN MATCH p = shortestpath((a:person)-[:knows*]->(b:person))
WHERE a.name='Alice' AND b.name='Bob' RETURN p
Shortestpath (limit=1)
-> Hash2Side (left direction=FORWARD)
-> Index Scan on knows e
Index Cond: (start_id = $current_vertex)
-> Hash2Side (right direction=REVERSE)
-> Index Scan on knows e
Index Cond: (end_id = $current_vertex)
4. Comparison Summary
---------------------
┌─────────────────────┬─────────────────────────┬─────────────────────────┐
│ Aspect │ Unoptimized (CTE) │ Optimized (Executor) │
├─────────────────────┼─────────────────────────┼─────────────────────────┤
│ Implementation │ Query rewriting │ Custom executor node │
├─────────────────────┼─────────────────────────┼─────────────────────────┤
│ Search Direction │ Unidirectional │ Bidirectional │
├─────────────────────┼─────────────────────────┼─────────────────────────┤
│ Search Space │ O(B^D) │ O(2 * B^(D/2)) │
├─────────────────────┼─────────────────────────┼─────────────────────────┤
│ Early Termination │ Not possible │ Stop when path found │
├─────────────────────┼─────────────────────────┼─────────────────────────┤
│ Data Structure │ WorkTable (tuplestore) │ Dual hash tables │
├─────────────────────┼─────────────────────────┼─────────────────────────┤
│ Cycle Prevention │ Array membership check │ Hash table lookup O(1) │
├─────────────────────┼─────────────────────────┼─────────────────────────┤
│ Code Complexity │ Low (rewriting only) │ High (new executor) │
├─────────────────────┼─────────────────────────┼─────────────────────────┤
│ PostgreSQL Changes │ None │ New plan/executor node │
└─────────────────────┴─────────────────────────┴─────────────────────────┘
5. Search Space Example
-----------------------
Graph: Social network, avg 100 connections per person
Query: shortestpath((Alice)-[*]->(Bob)), actual distance = 6 hops
Unidirectional BFS (CTE):
Hop 1: 100 vertices
Hop 2: 10,000 vertices
Hop 3: 1,000,000 vertices
Hop 4: 100,000,000 vertices
Hop 5: 10,000,000,000 vertices
Hop 6: Find Bob
Total vertices explored: ~10 billion
Bidirectional BFS with smaller side expansion:
Hop 1: Left=1, Right=1 -> expand Left -> Left=100
Hop 2: 1 < 100 -> expand Right -> Right=100
Hop 3: 100 = 100 -> expand Left -> Left=10,000
Hop 4: 100 < 10,000 -> expand Right -> Right=10,000
Hop 5: 10,000 = 10,000 -> expand Left -> Left=1,000,000
Hop 6: 10,000 < 1,000,000-> expand Right -> Meet!
Total vertices explored: ~1 million (each side explores ~500K)
Speedup: ~10,000x fewer vertices explored
6. Key Techniques Summary
-------------------------
┌────┬───────────────────────────┬────────────────────────────────────────┐
│ # │ Technique │ Benefit │
├────┼───────────────────────────┼────────────────────────────────────────┤
│ 1 │ Bidirectional BFS │ Exponential reduction in search space │
│ 2 │ Dual Hash Tables │ O(1) visited check, O(1) intersection │
│ 3 │ Smaller Side Expansion │ Expand from side with fewer vertices │
│ 4 │ Early Termination │ Stop immediately when path found │
│ 5 │ Cycle Detection │ Hash lookup prevents revisiting vertex │
│ 6 │ Batch Synchronization │ Match nbatch between Left/Right hashes │
│ 7 │ Path Reconstruction │ Merge left and right paths at meeting │
│ 8 │ Parameterized Subplan │ Reuse edge scan plan per vertex │
│ 9 │ Batch Processing │ Handle memory overflow with batching │
│ 10 │ Limit Control │ shortestpath (1) vs allshortestpaths │
└────┴───────────────────────────┴────────────────────────────────────────┘
7. Conclusion
-------------
The unoptimized CTE-based approach is simpler to implement but suffers from:
- Unidirectional search with O(B^D) complexity
- No early termination capability
- Inefficient cycle prevention with arrays
- Must explore all paths before finding shortest
The optimized executor-based approach requires more implementation
effort but provides:
- Bidirectional BFS with O(B^(D/2)) complexity
- Early termination when shortest path found
- Efficient hash-based visited tracking
- Support for both shortestpath and allshortestpaths
For production graph database systems, the bidirectional BFS approach
is essential for practical shortest path queries on large graphs.
This document focuses on the conceptual design. Implementation details
such as hash table sizing, batch overflow handling, and path reconstruction
algorithms are left for follow-up discussion.
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Ashutosh,
=====================================
I've re-run the coverage analysis with the latest patches (0001-0005).
Here are the results:
1. COVERAGE COMPARISON
----------------------
Previous Current Change
---------------------------------------------------------
Overall Coverage 90.5% 91.4% +0.9%
Covered Lines 2,029 2,049 +20
Untested Lines 214 194 -20
2. KEY FILE IMPROVEMENTS
------------------------
File Previous Current Change
---------------------------------------------------------
propgraphcmds.c 94.6% 95.3% +0.7%
rewriteGraphTable.c 94.6% 95.0% +0.4%
ruleutils.c 85.1% 89.2% +4.1%
3. WHITE-BOX TEST VERIFICATION (Section 5.2)
--------------------------------------------
File:Line Test Case Status
-------------------------------------------------------------------------------
propgraphcmds.c:116 CREATE UNLOGGED attempt COVERED
propgraphcmds.c:136 TEMP table in graph creation COVERED
propgraphcmds.c:179 (same group) UNCOVERED [1]
propgraphcmds.c:254-262 (same group) COVERED
propgraphcmds.c:1323 ALTER ADD TEMP to perm graph COVERED
propgraphcmds.c:1364 (same group) UNCOVERED [1]
propgraphcmds.c:726-733 CREATE without LABEL clause UNREACHABLE [2]
propgraphcmds.c:1300,1303 ALTER IF EXISTS non-existent UNREACHABLE [3]
execMain.c:1162-1163 DML on graph UNREACHABLE [4]
rewriteGraphTable.c:120 Multiple path patterns COVERED
rewriteGraphTable.c:205 Quantifier usage COVERED
ruleutils.c:7939-7961 Complex label VIEW deparsing COVERED
ruleutils.c:7962-7963 (same group) DEFENSIVE [5]
Summary: 7 covered, 3 unreachable, 2 uncovered, 1 defensive
Notes:
[1] TEMP edge table tests missing. Line 136/1323 cover vertex tables,
but 179/1364 are the corresponding edge table branches.
[2] Parser always creates default label entry (gram.y:9591-9601).
The else-block at 726-733 is dead code; einfo->labels is never NIL.
[3] Syntax not supported; only SET SCHEMA has IF EXISTS variant.
[4] Graph reference only allowed in GRAPH_TABLE(), parser blocks DML.
[5] Default case for unrecognized node type (elog ERROR).
4. UNTESTABLE CODE VERIFICATION (Section 5.3)
---------------------------------------------
File:Line Reason Status
-------------------------------------------------------------------------------
rewriteGraphTable.c:202 PAREN_EXPR blocked at parser AGREED
rewriteGraphTable.c:297,304,319 Cyclic pattern edge conflict AGREED
rewriteGraphTable.c:801-818 get_gep_kind_name error only AGREED
nodeFuncs.c:4585-4596,4755-4774 Walker branches internal AGREED
Summary: 4 items confirmed unreachable as expected
5. REMAINING UNCOVERED LINES
----------------------------
5.1 Unreachable Code (by design):
- propgraphcmds.c:726-733 - Parser creates default label (gram.y:9591)
- propgraphcmds.c:1300,1303 - IF EXISTS syntax not supported
- execMain.c:1162-1163 - Graph reference only in GRAPH_TABLE()
5.2 Defensive/Error-only Code:
- get_gep_kind_name() - Error message function only
- nodeFuncs.c walker - Internal implementation details
- ruleutils.c:7962-7963 - Default case (elog ERROR)
5.3 Test Gaps (remaining):
- propgraphcmds.c:179 - TEMP edge table in CREATE
- propgraphcmds.c:1364 - TEMP edge table in ALTER ADD
6. RECOMMENDATIONS
------------------
6.1 Proposed Test Cases (Optional)
To cover the 2 remaining uncovered lines:
-- TEMP edge table in CREATE (covers line 179)
CREATE TEMP TABLE te_src (id int PRIMARY KEY);
CREATE TEMP TABLE te_dst (id int PRIMARY KEY);
CREATE TEMP TABLE te (id int PRIMARY KEY, src int, dst int);
CREATE PROPERTY GRAPH pg_temp_edge
VERTEX TABLES (te_src, te_dst)
EDGE TABLES (te KEY (id)
SOURCE KEY (src) REFERENCES te_src (id)
DESTINATION KEY (dst) REFERENCES te_dst (id));
-- TEMP edge table in ALTER ADD (covers line 1364)
CREATE TABLE pv1 (id int PRIMARY KEY);
CREATE TABLE pv2 (id int PRIMARY KEY);
CREATE TEMP TABLE pe (id int PRIMARY KEY, src int, dst int);
CREATE PROPERTY GRAPH pg_perm VERTEX TABLES (pv1, pv2);
ALTER PROPERTY GRAPH pg_perm ADD EDGE TABLES (pe KEY (id)
SOURCE KEY (src) REFERENCES pv1 (id)
DESTINATION KEY (dst) REFERENCES pv2 (id));
-- Expected: ERROR (cannot add temp edge to permanent graph)
6.2 Dead Code Cleanup (Optional)
propgraphcmds.c:726-733 is unreachable dead code. Consider replacing
the else-block with defensive error handling:
if (einfo->labels)
{
...
}
else
{
/* Parser guarantees labels list is never empty */
elog(ERROR, "unexpected empty labels list");
}
6.3 Minor Issue
Patch 0003 (ECPG test) is missing .gitignore entries.
src/interfaces/ecpg/test/sql/.gitignore should include:
/sqlpgq
/sqlpgq.c
7. CONCLUSION
-------------
The coverage has improved from 90.5% to 91.4%. The additional tests in
patch 0005 have addressed most coverage concerns raised in my initial report:
- Section 5.2: 7 of 13 items now covered
- Section 5.3: 4 items confirmed unreachable as expected
- Remaining: 3 unreachable, 1 defensive, 2 uncovered
Note on 726-733: Analysis of gram.y (lines 9591-9601) confirms the parser
always creates a default label entry when no LABEL clause is specified.
The else-block is dead code. Recommend replacing with elog(ERROR).
The 2 remaining uncovered lines (179, 1364) are TEMP edge table branches.
Adding edge-specific tests would complete the coverage.
---
End of Report
Best regards,
Henson
Hi Henson,
Thanks for your systematic review.
On Wed, Dec 31, 2025 at 11:53 AM Henson Choi <assam258@gmail.com> wrote:
>
> Overall assessment: GOOD
Glad to know that.
> - Test Coverage: Good (90.5% line coverage, ~180 test cases)
Thanks for the coverage analysis. Looks good right now. But see below.
> 2.1 Critical / Major
> (None)
Great.
>
> 2.2 Minor Issues
>
> #1 [Code] src/backend/commands/propgraphcmds.c:1632
> FIXME: Missing index for plppropid column causes sequential scan.
> Decision needed: (a) add index, or (c) allow seq scan for rare path.
The path is rare enough that I think we can allow the seq scan. Given
that Peter has marked it as FIXME, it seems we will keep it as is for
now, but will revisit if performance becomes an issue. Peter, please
correct me if I'm wrong.
>
> #2 [Doc] doc/src/sgml/ref/alter_property_graph.sgml:286
> Compatibility section incorrectly states "CREATE PROPERTY GRAPH"
> Should be: "ALTER PROPERTY GRAPH"
>
That's right. Fixed.
> #3 [Doc] doc/src/sgml/ref/alter_property_graph.sgml:65
> Synopsis shows VERTEX/NODE and EDGE/RELATIONSHIP as separate clauses,
> but Description merges them as {VERTEX|NODE|EDGE|RELATIONSHIP}.
Their syntax is slightly different hence they are separate in
Synopsis. If we separate them in the Description, we might have to
repeat the same text twice. Having them merged in the Description
makes it more concise without losing any clarity or meaning. I think
we can keep it as is. What do you think?
>
> #4 [Doc] doc/src/sgml/ref/alter_property_graph.sgml:80
> Grammar error: "the graph removed" should be "the graph is removed"
Right. Fixed.
>
> #5 [Doc] doc/src/sgml/queries.sgml:2929,2931
> TODO comments for unimplemented features without clear limitation notes.
Those TODOs are not visible to users. I think they serve as
placeholders to add the documentation when the features are
implemented. We may want to remove them, but I see no harm in keeping
them for now. Peter, what do you think?
>
> #6 [Doc] doc/src/sgml/ddl.sgml:5717
> Typo: "infrastucture" should be "infrastructure"
>
Fixed. Thanks for catching it.
> 2.3 Alternative Approaches for Discussion
>
> #1 Support CREATE PROPERTY GRAPH IF NOT EXISTS
> Rationale: PostgreSQL-style extension, consistent with other DDL.
>
I think this will be good-to-have for consistency across DDLs.
However, I think it is better to discuss and implement it separately
since lack of it does not block the main functionality of property
graphs. Meantime users can DROP and CREATE. There are other DDLs which
do not have this support. What do you think?
> #2 Return 0 rows for non-existent labels instead of error
> Current: SELECT * FROM GRAPH_TABLE(g MATCH (a:NonExistent) ...) raises error
> Alternative: Return empty result set instead
> Rationale: Better for exploratory queries, similar to SQL WHERE on
> non-existent values returning 0 rows rather than error.
I think this makes sense in a proper graph database where the labels
are not predefined. However, in property graphs the labels, the
properties associated with them and data types of those properties are
predefined in the graph schema. If the specified label does not exist
in the graph schema, we can not determine what properties are
associated with it and their data types. In turn we can not determine
the shape of the result set, which is essential for reporting even 0
rows. Hence the error instead of 0 rows. Oracle has similar behaviour.
>
> #3 Return 0 rows when same variable has different labels
> Current: SELECT * FROM GRAPH_TABLE(g MATCH (a:Person)-[e]-(a:Company) ...)
> raises error because variable 'a' has conflicting labels.
> Alternative: Return empty result set instead
> Rationale: Logically, a node cannot be both Person AND Company,
> so 0 rows is the correct result. Consistent with standard SQL
> WHERE semantics (impossible condition = 0 rows, not error).
>
In such a case 0 rows isn't a correct result. According to the
standard, variable a is bound to all the nodes that have both the
labels. This is label conjunction, a feature we don't support right
now. Hence the "unsupported feature" error. I expect that some day we
will implement label conjunction, and then the same query will return
non-zero rows if there are nodes with both labels.
> -------------------------------------------------------------------------------
> TEMP graph CREATE TEMP PROPERTY GRAPH Medium
Done
> TEMP graph TEMP graph with permanent table reference Medium
Done
> TEMP graph ALTER ADD permanent table to TEMP graph Medium
Done
> CASCADE DROP ... CASCADE (dependent view cascade) Low
Done
> RESTRICT DROP ... RESTRICT (dependent object error) Low
Done, but without explicit RESTRICT keyword since it's default behavior.
- Tests specifying NODE/RELATIONSHIP instead of VERTEX/EDGE (Low priority)
Done
> propgraphcmds.c:136,179,254-262 TEMP table in graph creation Auto TEMP conversion
Done
> propgraphcmds.c:1323,1364 ALTER ADD TEMP to perm graph Error branch
Done
> propgraphcmds.c:724-734 CREATE without LABEL clause Default label else
This should be covered. There are several CREATE PROPERTY GRAPH
statements without LABEL clauses.
> propgraphcmds.c:1300,1303 ALTER IF EXISTS non-existent missing_ok branch
This is unreachable since the syntax is not supported. The only IF
EXISTS variant supported is ALTER PROPERTY GRAPH IF EXISTS ... SET
SCHEMA .... Added a test for the same.
> propgraphcmds.c:116 CREATE UNLOGGED attempt UNLOGGED error
Done
> execMain.c:1162-1163 DML on graph RELKIND_PROPGRAPH
This is unreachable since a property graph reference is only allowed
in GRAPH_TABLE().
> rewriteGraphTable.c:120 Multiple path patterns Length check
Done
> rewriteGraphTable.c:205 Quantifier usage Quantifier error
Done
> ruleutils.c:7939-7963 Complex label VIEW deparsing T_BoolExpr branch
>
Done
Can you please check whether the uncovered lines are now covered?
> - Tests executed: run_pgq_tests.sql
What's this test? It's not in the patchset. Also you might want to try
002_pg_upgrade.
>
> +----------------------------------------------------------+
> | SQL/PGQ Implementation: NO MEMORY LEAKS DETECTED |
> +----------------------------------------------------------+
Great. Thanks for confirming.
>>
>> On Fri, Dec 26, 2025 at 6:03 PM Henson Choi <assam258@gmail.com> wrote:
>> >
>> > 1. LABELS() function
>> > - Returns text[] of element labels
>> > - Fixed privilege checking from previous version
>> > - Enables optimizer pushdown for branch pruning
>> >
>> > 2. PROPERTY_NAMES() function
>> > - Returns text[] of property names
>> > - Similar approach to LABELS()
>> >
>>
>> I could not find specification of these functions in SQL/PGQ standard.
>> It's a large document and I might be missing something. Can you please
>> point me to the relevant sections?
>>
>
> You're correct - LABELS() and PROPERTY_NAMES() are not in the SQL/PGQ
> standard. I was inspired by similar functions in Cypher (labels(), keys())
> and Oracle's PGQL (which has LABELS(), though Oracle is moving toward
> SQL/PGQ compliance as well).
>
> The attached code demonstrates that through query rewrite, these functions
> can enable planner-level table pruning optimizations. This becomes
> particularly valuable for client applications - GUI tools could use label
> names as host variables for flexible label-based filtering, and
> PROPERTY_NAMES() (similar to Cypher's keys()) would enable dynamic property
> inspection for display or selective querying of elements with specific
> properties.
>
> While there's a distinction between structured (SQL/PGQ) and semi-structured
> (Cypher) query models, I don't think we need to strictly exclude
> semi-structured patterns that work well within the structured framework.
> Whether this should be proposed as a future SQL/PGQ standard extension or
> remain a PostgreSQL-specific extension is worth discussion. Given the
> practical utility demonstrated in graph query deployments, there might be
> value in standardizing such introspection functions.
While these functions are useful with semistructured frameworks like
Cypher, I am not sure how useful they are in structured framework like
SQL/PGQ. In SQL/PGQ, the graph schema is predefined and known to the
users. Hence users know what labels and properties exist in the graph.
However, if they become part of the standard, their chances of getting
accepted in the PostgreSQL core will increase.
Even if we keep them out of core, I think we should be able to
implement them as stable functions in an extension and still benefit
from planner optimizations you mentioned.
>
> Similarly, I'd suggest considering Cypher's SHORTEST PATH for future
> SQL/PGQ standards. If we treat SHORTEST PATH as a specialized join type
> in SQL and handle it through query rewrite, PostgreSQL's existing planner
> infrastructure could support it efficiently. This approach has been proven
> in practice and could be a valuable addition to the next standard revision.
IIRC there is SQL/PGQ standard specification for shortest path. We
should implement that when we get to it.
>
> That was my finding as well - the architecture is well-designed for
> extensibility.
Great. Thanks for the confirmation.
>
> Having more people who can maintain and extend SQL/PGQ reduces the
> risk for both the community and PostgreSQL itself. When I have a revised
> version ready, would you be willing to review it again?
>
We will need to prioritize the features to be implemented next. This
looks like a useful pattern to support. I believe this will appear
higher in the priority list, thus worth reviewing.
The patches are thus
0001 - same as previous except a. addition of new lines in
create_property_graph.sql for consistency with other sections in that
file, b. some minor corrections suggested by Hensen.
0002 - fixes : references and improves documentation. I think we can
merge this into 0001 after a quick review from Peter
0003 - ECPG test. This might need a bit of review. The patch is large
because of the .c and .err files.
0004 - This reverts back ECPG and PSQL lexer changes introduced in
0001. Does not show any failure even in the test case added by 0003.
Those changes seem unnecessary. Peter, can you please confirm.
0005 - Additional test cases for code coverage as pointed out by
Hensen's report.
--
Best Wishes,
Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
I analyzed the pg_upgrade coverage for property graph functions in
ruleutils.c. Here are the findings:
What's this test? It's not in the patchset. Also you might want to try
002_pg_upgrade.
1. UNCOVERED CODE ANALYSIS
--------------------------
The uncovered lines in ruleutils.c property graph functions fall into
four categories:
1.1 Defensive Code (5 lines)
Error handling that cannot be reached in normal operation.
Line Code Reason
-------------------------------------------------------------------------
1628 PG_RETURN_NULL() Invalid OID check
1710 elog(ERROR, "null pgekey") Parser prevents
1733 elog(ERROR, "cache lookup failed") System catalog guard
1750 elog(ERROR, "cache lookup failed") System catalog guard
7962-7963 elog(ERROR, "unrecognized node type") Default switch case
1.2 Dead Code (2 lines)
Unreachable due to design - implicit SOURCE/DEST is expanded during
DDL processing. FK lookup always populates pgesrckey/pgedestkey in
the catalog, so pg_get_propgraphdef() never sees NULL keys.
Line Code Reason
-------------------------------------------------------------------------
1744 appendStringInfo(... pgealias) Implicit SOURCE path
1761 appendStringInfo(... pgealias) Implicit DEST path
1.3 Unimplemented Features (~13 lines)
Parser accepts but rewriter rejects these patterns. Cannot be stored
as VIEW/RULE, so deparse code is unreachable.
This code will be used when these features are implemented.
Feature Lines Rewriter Rejection
-------------------------------------------------------------------------
Quantifier {m,n} 8046-8049 rewriteGraphTable.c:204-207
PAREN_EXPR 7994-7996, 8039-8041 rewriteGraphTable.c:201-202
Multiple Paths 8069 rewriteGraphTable.c:119-120
Subexpr 8013-8017 Part of PAREN_EXPR
1.4 Testable Code - Needs Coverage (4 features)
Supported features but not covered by current pg_upgrade tests.
Feature Lines Test Method
-------------------------------------------------------------------------
Left-pointing Edge 7987-7989, 8032-8035 VIEW + pg_get_viewdef()
Element WHERE 8020-8024 VIEW + pg_get_viewdef()
Graph Pattern WHERE 8078-8079 VIEW + pg_get_viewdef()
AS Alias (DDL) 1698-1700 pg_get_propgraphdef()
2. PROPOSED TEST CASES
----------------------
To cover the testable code paths:
-- Left-pointing edge (covers 7987-7989, 8032-8035)
CREATE VIEW v AS SELECT * FROM GRAPH_TABLE (g
MATCH (a)<-[e]-(b) COLUMNS (a.x, b.y));
-- Element WHERE on vertex (covers 8020-8024)
CREATE VIEW v AS SELECT * FROM GRAPH_TABLE (g
MATCH (a WHERE a.age > 25)-[e]->(b) COLUMNS (a.name));
-- Element WHERE on edge (covers 8020-8024)
CREATE VIEW v AS SELECT * FROM GRAPH_TABLE (g
MATCH (a)-[e WHERE e.since > 2020]->(b) COLUMNS (a.name));
-- Graph Pattern WHERE (covers 8078-8079)
CREATE VIEW v AS SELECT * FROM GRAPH_TABLE (g
MATCH (a)-[e]->(b) WHERE a.x > 10 COLUMNS (a.name));
-- AS Alias in DDL (covers 1698-1700)
CREATE PROPERTY GRAPH g VERTEX TABLES (t AS alias KEY (id));
3. VERIFICATION
---------------
I verified these patterns are testable by creating VIEWs and checking
pg_get_viewdef() output locally. All proposed test cases execute the
target code paths successfully.
4. SUMMARY
----------
Category Lines Status
---------------------------------------------------------
Defensive Code 5 Unreachable - error handling
Dead Code 2 Unreachable - design limitation
Unimplemented ~13 Unreachable - rewriter blocks
Testable 4 Recommend adding tests
---
End of Report
Best regards,
Henson
Hi Ashutosh,> Can you please check whether the uncovered lines are now covered?SQL/PGQ Coverage Verification Report
=====================================
I've re-run the coverage analysis with the latest patches (0001-0005).
Here are the results:
1. COVERAGE COMPARISON
----------------------
Previous Current Change
---------------------------------------------------------
Overall Coverage 90.5% 91.4% +0.9%
Covered Lines 2,029 2,049 +20
Untested Lines 214 194 -20
2. KEY FILE IMPROVEMENTS
------------------------
File Previous Current Change
---------------------------------------------------------
propgraphcmds.c 94.6% 95.3% +0.7%
rewriteGraphTable.c 94.6% 95.0% +0.4%
ruleutils.c 85.1% 89.2% +4.1%
3. WHITE-BOX TEST VERIFICATION (Section 5.2)
--------------------------------------------
File:Line Test Case Status
-------------------------------------------------------------------------------
propgraphcmds.c:116 CREATE UNLOGGED attempt COVERED
propgraphcmds.c:136 TEMP table in graph creation COVERED
propgraphcmds.c:179 (same group) UNCOVERED [1]
propgraphcmds.c:254-262 (same group) COVERED
propgraphcmds.c:1323 ALTER ADD TEMP to perm graph COVERED
propgraphcmds.c:1364 (same group) UNCOVERED [1]
propgraphcmds.c:726-733 CREATE without LABEL clause UNREACHABLE [2]
propgraphcmds.c:1300,1303 ALTER IF EXISTS non-existent UNREACHABLE [3]
execMain.c:1162-1163 DML on graph UNREACHABLE [4]
rewriteGraphTable.c:120 Multiple path patterns COVERED
rewriteGraphTable.c:205 Quantifier usage COVERED
ruleutils.c:7939-7961 Complex label VIEW deparsing COVERED
ruleutils.c:7962-7963 (same group) DEFENSIVE [5]
Summary: 7 covered, 3 unreachable, 2 uncovered, 1 defensive
Notes:
[1] TEMP edge table tests missing. Line 136/1323 cover vertex tables,
but 179/1364 are the corresponding edge table branches.
[2] Parser always creates default label entry (gram.y:9591-9601).
The else-block at 726-733 is dead code; einfo->labels is never NIL.
[3] Syntax not supported; only SET SCHEMA has IF EXISTS variant.
[4] Graph reference only allowed in GRAPH_TABLE(), parser blocks DML.
[5] Default case for unrecognized node type (elog ERROR).
4. UNTESTABLE CODE VERIFICATION (Section 5.3)
---------------------------------------------
File:Line Reason Status
-------------------------------------------------------------------------------
rewriteGraphTable.c:202 PAREN_EXPR blocked at parser AGREED
rewriteGraphTable.c:297,304,319 Cyclic pattern edge conflict AGREED
rewriteGraphTable.c:801-818 get_gep_kind_name error only AGREED
nodeFuncs.c:4585-4596,4755-4774 Walker branches internal AGREED
Summary: 4 items confirmed unreachable as expected
5. REMAINING UNCOVERED LINES
----------------------------
5.1 Unreachable Code (by design):
- propgraphcmds.c:726-733 - Parser creates default label (gram.y:9591)
- propgraphcmds.c:1300,1303 - IF EXISTS syntax not supported
- execMain.c:1162-1163 - Graph reference only in GRAPH_TABLE()
5.2 Defensive/Error-only Code:
- get_gep_kind_name() - Error message function only
- nodeFuncs.c walker - Internal implementation details
- ruleutils.c:7962-7963 - Default case (elog ERROR)
5.3 Test Gaps (remaining):
- propgraphcmds.c:179 - TEMP edge table in CREATE
- propgraphcmds.c:1364 - TEMP edge table in ALTER ADD
6. RECOMMENDATIONS
------------------
6.1 Proposed Test Cases (Optional)
To cover the 2 remaining uncovered lines:
-- TEMP edge table in CREATE (covers line 179)
CREATE TEMP TABLE te_src (id int PRIMARY KEY);
CREATE TEMP TABLE te_dst (id int PRIMARY KEY);
CREATE TEMP TABLE te (id int PRIMARY KEY, src int, dst int);
CREATE PROPERTY GRAPH pg_temp_edge
VERTEX TABLES (te_src, te_dst)
EDGE TABLES (te KEY (id)
SOURCE KEY (src) REFERENCES te_src (id)
DESTINATION KEY (dst) REFERENCES te_dst (id));
-- TEMP edge table in ALTER ADD (covers line 1364)
CREATE TABLE pv1 (id int PRIMARY KEY);
CREATE TABLE pv2 (id int PRIMARY KEY);
CREATE TEMP TABLE pe (id int PRIMARY KEY, src int, dst int);
CREATE PROPERTY GRAPH pg_perm VERTEX TABLES (pv1, pv2);
ALTER PROPERTY GRAPH pg_perm ADD EDGE TABLES (pe KEY (id)
SOURCE KEY (src) REFERENCES pv1 (id)
DESTINATION KEY (dst) REFERENCES pv2 (id));
-- Expected: ERROR (cannot add temp edge to permanent graph)
6.2 Dead Code Cleanup (Optional)
propgraphcmds.c:726-733 is unreachable dead code. Consider replacing
the else-block with defensive error handling:
if (einfo->labels)
{
...
}
else
{
/* Parser guarantees labels list is never empty */
elog(ERROR, "unexpected empty labels list");
}
6.3 Minor Issue
Patch 0003 (ECPG test) is missing .gitignore entries.
src/interfaces/ecpg/test/sql/.gitignore should include:
/sqlpgq
/sqlpgq.c
7. CONCLUSION
-------------
The coverage has improved from 90.5% to 91.4%. The additional tests in
patch 0005 have addressed most coverage concerns raised in my initial report:
- Section 5.2: 7 of 13 items now covered
- Section 5.3: 4 items confirmed unreachable as expected
- Remaining: 3 unreachable, 1 defensive, 2 uncovered
Note on 726-733: Analysis of gram.y (lines 9591-9601) confirms the parser
always creates a default label entry when no LABEL clause is specified.
The else-block is dead code. Recommend replacing with elog(ERROR).
The 2 remaining uncovered lines (179, 1364) are TEMP edge table branches.
Adding edge-specific tests would complete the coverage.
---
End of Report
Best regards,
Henson2026년 1월 2일 (금) PM 5:48, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>님이 작성:Hi Henson,
Thanks for your systematic review.
On Wed, Dec 31, 2025 at 11:53 AM Henson Choi <assam258@gmail.com> wrote:
>
> Overall assessment: GOOD
Glad to know that.
> - Test Coverage: Good (90.5% line coverage, ~180 test cases)
Thanks for the coverage analysis. Looks good right now. But see below.
> 2.1 Critical / Major
> (None)
Great.
>
> 2.2 Minor Issues
>
> #1 [Code] src/backend/commands/propgraphcmds.c:1632
> FIXME: Missing index for plppropid column causes sequential scan.
> Decision needed: (a) add index, or (c) allow seq scan for rare path.
The path is rare enough that I think we can allow the seq scan. Given
that Peter has marked it as FIXME, it seems we will keep it as is for
now, but will revisit if performance becomes an issue. Peter, please
correct me if I'm wrong.
>
> #2 [Doc] doc/src/sgml/ref/alter_property_graph.sgml:286
> Compatibility section incorrectly states "CREATE PROPERTY GRAPH"
> Should be: "ALTER PROPERTY GRAPH"
>
That's right. Fixed.
> #3 [Doc] doc/src/sgml/ref/alter_property_graph.sgml:65
> Synopsis shows VERTEX/NODE and EDGE/RELATIONSHIP as separate clauses,
> but Description merges them as {VERTEX|NODE|EDGE|RELATIONSHIP}.
Their syntax is slightly different hence they are separate in
Synopsis. If we separate them in the Description, we might have to
repeat the same text twice. Having them merged in the Description
makes it more concise without losing any clarity or meaning. I think
we can keep it as is. What do you think?
>
> #4 [Doc] doc/src/sgml/ref/alter_property_graph.sgml:80
> Grammar error: "the graph removed" should be "the graph is removed"
Right. Fixed.
>
> #5 [Doc] doc/src/sgml/queries.sgml:2929,2931
> TODO comments for unimplemented features without clear limitation notes.
Those TODOs are not visible to users. I think they serve as
placeholders to add the documentation when the features are
implemented. We may want to remove them, but I see no harm in keeping
them for now. Peter, what do you think?
>
> #6 [Doc] doc/src/sgml/ddl.sgml:5717
> Typo: "infrastucture" should be "infrastructure"
>
Fixed. Thanks for catching it.
> 2.3 Alternative Approaches for Discussion
>
> #1 Support CREATE PROPERTY GRAPH IF NOT EXISTS
> Rationale: PostgreSQL-style extension, consistent with other DDL.
>
I think this will be good-to-have for consistency across DDLs.
However, I think it is better to discuss and implement it separately
since lack of it does not block the main functionality of property
graphs. Meantime users can DROP and CREATE. There are other DDLs which
do not have this support. What do you think?
> #2 Return 0 rows for non-existent labels instead of error
> Current: SELECT * FROM GRAPH_TABLE(g MATCH (a:NonExistent) ...) raises error
> Alternative: Return empty result set instead
> Rationale: Better for exploratory queries, similar to SQL WHERE on
> non-existent values returning 0 rows rather than error.
I think this makes sense in a proper graph database where the labels
are not predefined. However, in property graphs the labels, the
properties associated with them and data types of those properties are
predefined in the graph schema. If the specified label does not exist
in the graph schema, we can not determine what properties are
associated with it and their data types. In turn we can not determine
the shape of the result set, which is essential for reporting even 0
rows. Hence the error instead of 0 rows. Oracle has similar behaviour.
>
> #3 Return 0 rows when same variable has different labels
> Current: SELECT * FROM GRAPH_TABLE(g MATCH (a:Person)-[e]-(a:Company) ...)
> raises error because variable 'a' has conflicting labels.
> Alternative: Return empty result set instead
> Rationale: Logically, a node cannot be both Person AND Company,
> so 0 rows is the correct result. Consistent with standard SQL
> WHERE semantics (impossible condition = 0 rows, not error).
>
In such a case 0 rows isn't a correct result. According to the
standard, variable a is bound to all the nodes that have both the
labels. This is label conjunction, a feature we don't support right
now. Hence the "unsupported feature" error. I expect that some day we
will implement label conjunction, and then the same query will return
non-zero rows if there are nodes with both labels.
> -------------------------------------------------------------------------------
> TEMP graph CREATE TEMP PROPERTY GRAPH Medium
Done
> TEMP graph TEMP graph with permanent table reference Medium
Done
> TEMP graph ALTER ADD permanent table to TEMP graph Medium
Done
> CASCADE DROP ... CASCADE (dependent view cascade) Low
Done
> RESTRICT DROP ... RESTRICT (dependent object error) Low
Done, but without explicit RESTRICT keyword since it's default behavior.
- Tests specifying NODE/RELATIONSHIP instead of VERTEX/EDGE (Low priority)
Done
> propgraphcmds.c:136,179,254-262 TEMP table in graph creation Auto TEMP conversion
Done
> propgraphcmds.c:1323,1364 ALTER ADD TEMP to perm graph Error branch
Done
> propgraphcmds.c:724-734 CREATE without LABEL clause Default label else
This should be covered. There are several CREATE PROPERTY GRAPH
statements without LABEL clauses.
> propgraphcmds.c:1300,1303 ALTER IF EXISTS non-existent missing_ok branch
This is unreachable since the syntax is not supported. The only IF
EXISTS variant supported is ALTER PROPERTY GRAPH IF EXISTS ... SET
SCHEMA .... Added a test for the same.
> propgraphcmds.c:116 CREATE UNLOGGED attempt UNLOGGED error
Done
> execMain.c:1162-1163 DML on graph RELKIND_PROPGRAPH
This is unreachable since a property graph reference is only allowed
in GRAPH_TABLE().
> rewriteGraphTable.c:120 Multiple path patterns Length check
Done
> rewriteGraphTable.c:205 Quantifier usage Quantifier error
Done
> ruleutils.c:7939-7963 Complex label VIEW deparsing T_BoolExpr branch
>
Done
Can you please check whether the uncovered lines are now covered?
> - Tests executed: run_pgq_tests.sql
What's this test? It's not in the patchset. Also you might want to try
002_pg_upgrade.
>
> +----------------------------------------------------------+
> | SQL/PGQ Implementation: NO MEMORY LEAKS DETECTED |
> +----------------------------------------------------------+
Great. Thanks for confirming.
>>
>> On Fri, Dec 26, 2025 at 6:03 PM Henson Choi <assam258@gmail.com> wrote:
>> >
>> > 1. LABELS() function
>> > - Returns text[] of element labels
>> > - Fixed privilege checking from previous version
>> > - Enables optimizer pushdown for branch pruning
>> >
>> > 2. PROPERTY_NAMES() function
>> > - Returns text[] of property names
>> > - Similar approach to LABELS()
>> >
>>
>> I could not find specification of these functions in SQL/PGQ standard.
>> It's a large document and I might be missing something. Can you please
>> point me to the relevant sections?
>>
>
> You're correct - LABELS() and PROPERTY_NAMES() are not in the SQL/PGQ
> standard. I was inspired by similar functions in Cypher (labels(), keys())
> and Oracle's PGQL (which has LABELS(), though Oracle is moving toward
> SQL/PGQ compliance as well).
>
> The attached code demonstrates that through query rewrite, these functions
> can enable planner-level table pruning optimizations. This becomes
> particularly valuable for client applications - GUI tools could use label
> names as host variables for flexible label-based filtering, and
> PROPERTY_NAMES() (similar to Cypher's keys()) would enable dynamic property
> inspection for display or selective querying of elements with specific
> properties.
>
> While there's a distinction between structured (SQL/PGQ) and semi-structured
> (Cypher) query models, I don't think we need to strictly exclude
> semi-structured patterns that work well within the structured framework.
> Whether this should be proposed as a future SQL/PGQ standard extension or
> remain a PostgreSQL-specific extension is worth discussion. Given the
> practical utility demonstrated in graph query deployments, there might be
> value in standardizing such introspection functions.
While these functions are useful with semistructured frameworks like
Cypher, I am not sure how useful they are in structured framework like
SQL/PGQ. In SQL/PGQ, the graph schema is predefined and known to the
users. Hence users know what labels and properties exist in the graph.
However, if they become part of the standard, their chances of getting
accepted in the PostgreSQL core will increase.
Even if we keep them out of core, I think we should be able to
implement them as stable functions in an extension and still benefit
from planner optimizations you mentioned.
>
> Similarly, I'd suggest considering Cypher's SHORTEST PATH for future
> SQL/PGQ standards. If we treat SHORTEST PATH as a specialized join type
> in SQL and handle it through query rewrite, PostgreSQL's existing planner
> infrastructure could support it efficiently. This approach has been proven
> in practice and could be a valuable addition to the next standard revision.
IIRC there is SQL/PGQ standard specification for shortest path. We
should implement that when we get to it.
>
> That was my finding as well - the architecture is well-designed for
> extensibility.
Great. Thanks for the confirmation.
>
> Having more people who can maintain and extend SQL/PGQ reduces the
> risk for both the community and PostgreSQL itself. When I have a revised
> version ready, would you be willing to review it again?
>
We will need to prioritize the features to be implemented next. This
looks like a useful pattern to support. I believe this will appear
higher in the priority list, thus worth reviewing.
The patches are thus
0001 - same as previous except a. addition of new lines in
create_property_graph.sql for consistency with other sections in that
file, b. some minor corrections suggested by Hensen.
0002 - fixes : references and improves documentation. I think we can
merge this into 0001 after a quick review from Peter
0003 - ECPG test. This might need a bit of review. The patch is large
because of the .c and .err files.
0004 - This reverts back ECPG and PSQL lexer changes introduced in
0001. Does not show any failure even in the test case added by 0003.
Those changes seem unnecessary. Peter, can you please confirm.
0005 - Additional test cases for code coverage as pointed out by
Hensen's report.
--
Best Wishes,
Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Ashutosh, Here is a brief review of v20260102-0001-WIP-SQL-Property-Graph-Queries-SQL-PGQ.patch + + <literal>pg_element_table_key_columns</literal> + + + The view pg_element_key_columns identifies which columns + are part of the keys of the element tables of property graphs defined in + the current database. Only those property graphs are shown that the + current user has access to (by way of being the owner or having some + privilege). + pg_element_key_columns should be pg_element_table_key_columns + + <literal>pg_element_table_properties</literal> + + + The view pg_element_table_labels shows the definitions + of the properties for the element tables of property graphs defined in the + current database. Only those property graphs are shown that the current + user has access to (by way of being the owner or having some privilege). + pg_element_table_labels here should be pg_element_table_properties, I guess this was due to copy-paste. + + <literal>pg_property_graph_privileges</literal> + + + The view property_graph_privileges identifies all + privileges granted on property graphs to a currently enabled role or by a + currently enabled role. There is one row for each combination of property + graph, grantor, and grantee. + + +
Re: SQL Property Graph Queries (SQL/PGQ)
I've added comprehensive tests to address your concerns below.
Hi Henson,
> 3. Multiple path patterns
> - Syntax: MATCH (a)->(b), (b)->(c)
> - Implements SQL/PGQ standard feature (was TODO)
>
This path pattern list feature is discussed in section 10.4 of the
standard. I think supporting this feature would be a good addition to
SQL/PGQ compliance. The current patchset is already large. I (and
AFAIK Peter as well) am focusing on getting that patchset in a
committable shape. Once committed, it will facilitate adding features
like path pattern list, quantified path patterns, label conjunction
etc. as incremental relatively smaller commits.
should be stabilized first.
Since you could build one of the complex features without changing a
lot of earlier implementation, it validates that the basic
implementation is extensible and yet robust. Thanks for that
validation.
The way you have implemented it, it can lead to a path pattern with
two vertex patterns next to each other without an interleaving edge
pattern. That would throw an error or assertion.
Cartesian product correctly (vl1 has 3 rows, vl3 has 6 rows = 18 rows):
SELECT a_name, b_name FROM GRAPH_TABLE (g1
MATCH (a IS vl1), (b IS vl3)
COLUMNS (a.vname AS a_name, b.vname AS b_name)
) ORDER BY 1, 2;
a_name | b_name
--------+--------
v11 | v21
v11 | v22
...
(18 rows) -- 3 x 6 = 18, confirming cross join
If you try path
patterns without a common vertex, you will get that error.
a Cartesian product (vl1->vl2 has 3 paths, vl1->vl3 has 5 paths = 15 rows):
SELECT a_name, b_name, c_name, d_name FROM GRAPH_TABLE (g1
MATCH (a IS vl1)-[]->(b IS vl2),
(c IS vl1)-[]->(d IS vl3)
COLUMNS (a.vname AS a_name, b.vname AS b_name,
c.vname AS c_name, d.vname AS d_name)
) ORDER BY 1, 2, 3, 4;
a_name | b_name | c_name | d_name
--------+--------+--------+--------
v11 | v22 | v11 | v22
v11 | v22 | v11 | v31
v11 | v22 | v11 | v33
...
(15 rows) -- 3 x 5 = 15, confirming cross join
That is not
covered by your tests.
Disconnected patterns (cross product):
1. Two independent paths - 3 x 5 = 15 rows
2. EXPLAIN verification - confirms Nested Loop (cross join)
3. Single vertex patterns - 3 x 6 = 18 rows
4. Three-way cross product - 3 x 3 x 6 = 54 rows
5. Mixed connected + disconnected - 1 path x 3 vertices = 3 rows
6. Filtered cross product - 1 x 6 = 6 rows
Connected patterns (join via shared variable):
7. Star pattern: A->B, A->C, D->A with shared hub 'a' - 2 rows (NOT cross product)
MATCH (a IS vl1)-[]->(b IS vl2),
(a)-[]->(c IS vl3),
(d IS vl2)-[]->(a)
a_name | b_name | c_name | d_name
--------+--------+--------+--------
v12 | v21 | v21 | v21
v13 | v23 | v23 | v23
(2 rows) -- all joined via 'a', NOT cross product
All row counts match expected behavior.
In such cases, the paths should end up being
full-joined rather than concatenated. I don't see it being implemented
that way.
The implementation DOES produce cross joins for disconnected patterns.
The EXPLAIN output confirms this:
EXPLAIN (COSTS OFF) SELECT ... FROM GRAPH_TABLE (g1
MATCH (a IS vl1)-[]->(b IS vl2),
(c IS vl1)-[]->(d IS vl3)
...
);
QUERY PLAN
-----------------------------------------------
Append
-> Merge Join
...
-> Nested Loop <-- Cross join here
-> Index Scan ...
-> Materialize
-> Nested Loop
...
The Nested Loop without join condition IS the cross join (Cartesian product).
I think more work is needed here.
of the current design, not to push for immediate inclusion at this stage.
[1] https://www.postgresql.org/message-id/CAExHW5sr+dJPCFw2OqXUfPPqPks8qmsivaAYhRiBdFANcX8RHw@mail.gmail.com
--
Best Wishes,
Ashutosh Bapat
Henson
Re: SQL Property Graph Queries (SQL/PGQ)
On Mon, Jan 5, 2026 at 9:56 PM Henson Choi wrote: > > Hi hackers, > > I think it may be a bit early for this, but I wanted to share this design > document now so we can revisit and discuss when the time is right. > > =================================================================== > Variable Length Edge (VLE) Implementation Strategies for PostgreSQL > =================================================================== > > 1. Overview > ----------- > > This document describes two implementation strategies for Variable > Length Edge (VLE) traversal in PostgreSQL-based graph databases. > > VLE Query Example: > > MATCH (a)-[*1..5]->(b) RETURN a, b > MATCH p = (a)-[:knows*]->(b) RETURN p > > Two implementation approaches: > > 1. Unoptimized: Query rewriting to WITH RECURSIVE (CTE) > 2. Optimized: Custom executor node with DFS algorithm > Interesting ideas. I was thinking about expanding the edge pattern using the lower and upper but it seems it can not handle the * case. ISTM these two approaches can both work when we need runtime pruning, for example if we are going to support path mode. The first option can be costly, since you have to pre calculate the recursive CTE, it can not utilize the predicate from previous hops. Can it work with quantifier * case? The second option seems more promising, but it needs to touch the planner and executor. I guess you need a special node to represent the VLE in the rewrite phase. > > 2. Unoptimized Approach: WITH RECURSIVE Rewriting > ------------------------------------------------- > > 2.1 Query Transformation > > Cypher query: > > MATCH (a:person)-[:knows*1..3]->(b) WHERE a.name = 'Alice' RETURN b > > Rewritten SQL using WITH RECURSIVE: > > WITH RECURSIVE vle_paths AS ( > -- Base case: start vertices > SELECT v.id as start_vid, > v.id as end_vid, > ARRAY[] as edge_ids, > ARRAY[] as edges, > 0 as depth > FROM person v > WHERE name = 'Alice' > > UNION ALL > > -- Recursive case: expand one hop > SELECT p.start_vid, > e.end_id, > p.edge_ids || e.id, > p.edges || e, > p.depth + 1 > FROM vle_paths p > JOIN knows e ON p.end_vid = e.start_id > WHERE p.depth < 3 > AND e.id <> ALL(p.edge_ids) -- Edge uniqueness check > ) > SEARCH DEPTH FIRST BY end_vid SET ordercol > SELECT b.*, edges > FROM vle_paths > JOIN person b ON b.id = end_vid > WHERE depth BETWEEN 1 AND 3; > > 2.2 Execution Plan > > Hash Join (b vertex lookup) > Hash Cond: (end_vid = b.id) > -> CTE Scan on vle_paths > Filter: (depth >= 1 AND depth <= 3) > Sort Key: ordercol -- SEARCH DEPTH FIRST ordering > CTE vle_paths > Recursive Union > Seq Scan on person v > Filter: (name = 'Alice') > Hash Join > Hash Cond: (p.end_vid = e.start_id) > Filter: (e.id <> ALL(p.edge_ids)) AND (p.depth < 3) > WorkTable Scan on vle_paths p > Hash > Seq Scan on knows e > -> Hash > -> Seq Scan on person b > > 2.3 Problems > > ┌─────────────────────┬──────────────────────────────────────────┐ > │ Problem │ Description │ > ├─────────────────────┼──────────────────────────────────────────┤ > │ Execution Model │ BFS execution (set-based iteration) │ > │ │ SEARCH DEPTH FIRST changes output order │ > │ │ only, not execution or memory model │ > ├─────────────────────┼──────────────────────────────────────────┤ > │ No Backtracking │ CTE stores all intermediate results │ > │ │ Cannot restore previous state │ > ├─────────────────────┼──────────────────────────────────────────┤ > │ Memory Usage │ O(total_paths) - all partial paths │ > │ │ Exponential growth with depth │ > ├─────────────────────┼──────────────────────────────────────────┤ > │ Edge Uniqueness │ e.id <> ALL(p.edge_ids) │ > │ │ O(path_length) comparison per row │ > ├─────────────────────┼──────────────────────────────────────────┤ > │ No Streaming │ Must complete all iterations before │ > │ │ returning results │ > ├─────────────────────┼──────────────────────────────────────────┤ > │ Array Operations │ p.edge_ids || e.id creates new array │ > │ │ O(n) copy per iteration │ > └─────────────────────┴──────────────────────────────────────────┘ > > 2.4 Memory Analysis > > Graph: Tree with branching factor B=10, max depth D=5 > > Iteration 1: 10 rows (depth 1) > Iteration 2: 100 rows (depth 2) > Iteration 3: 1,000 rows (depth 3) > Iteration 4: 10,000 rows (depth 4) > Iteration 5: 100,000 rows (depth 5) > > Total rows in WorkTable: 111,110 > Each row contains: start_vid + end_vid + edge_ids array + edges array > > Memory = 111,110 * (8 + 8 + avg_path_len * 8 + avg_path_len * edge_size) > > > 3. Optimized Approach: Custom Executor Node > ------------------------------------------- > > 3.1 Design Principle > > Instead of query rewriting, implement a dedicated executor node that: > > - Performs true DFS traversal with backtracking > - Maintains only current path in memory > - Uses PlanState stack for depth-wise edge scanning > - Yields results incrementally (streaming) > > 3.2 Plan Node Structure > > ┌────────────────────────────────────────────────────────┐ > │ Nested Loop (b lookup) │ > └────────────────────────────────────────────────────────┘ > │ │ > │ outer │ inner > ▼ ▼ > ┌──────────────────────────────┐ ┌─────────────────────────┐ > │ VLEPlan Node │ │ IndexScan on person │ > │ - DFS with PlanState stack │ │ (b vertex lookup) │ > │ - O(depth) memory │ └─────────────────────────┘ > └──────────────────────────────┘ > │ │ > outer │ │ inner (edge subplan) > ▼ ▼ > ┌───────────┐ ┌───────────────────────────┐ > │ IndexScan │ │ IndexScan on knows │ > │ (person a)│ │ (re-scanned per vertex) │ > └───────────┘ └───────────────────────────┘ > > Execution Flow: > > Outer plan returns vertex A > │ > ▼ > VLEPlan performs DFS: > │ > ├──→ Push PlanState for depth 0 (edges from A) > │ │ > │ ├──→ Find edge A->B, push PlanState for depth 1 > │ │ │ > │ │ ├──→ Find edge B->D, push PlanState for depth 2 > │ │ │ │ > │ │ │ └──→ No more edges, pop PlanState > │ │ │ > │ │ ├──→ Continue B's PlanState, find B->E > │ │ │ > │ │ └──→ Pop PlanState (B exhausted) > │ │ > │ └──→ Continue A's PlanState, find A->C > │ > └──→ Yield results when depth in [min, max] > > > 3.3 Key Concept: PlanState Stack > > The executor maintains a stack of inner subplan states (PlanState), > one per depth level. Each PlanState holds the scan position for > edges from that depth's vertex. > > At each depth: > - Re-scan inner subplan with current vertex as parameter > - On finding an edge, push new PlanState for next depth > - On exhausting edges, pop PlanState and backtrack > > Memory: Only current path + one PlanState per depth level > > > 3.4 Execution Plan (Optimized) > > EXPLAIN MATCH (a:person)-[:knows*1..3]->(b) WHERE a.name='Alice' RETURN b > > Nested Loop (b vertex lookup) > -> VLEPlan (minDepth=1 maxDepth=3 direction=RIGHT) > -> Index Scan on person a (outer: start vertices) > Index Cond: (name = 'Alice') > -> Index Scan on knows e (inner: edge subplan) > Index Cond: (start_id = $current_vertex) > -> Index Scan on person b > Index Cond: (id = vle.end_vertex) > > > 4. Comparison Summary > --------------------- > > ┌─────────────────────┬─────────────────────────┬─────────────────────────┐ > │ Aspect │ Unoptimized (CTE) │ Optimized (Executor) │ > ├─────────────────────┼─────────────────────────┼─────────────────────────┤ > │ Implementation │ Query rewriting │ Custom executor node │ > ├─────────────────────┼─────────────────────────┼─────────────────────────┤ > │ Traversal Order │ BFS (set-based) │ True DFS │ > ├─────────────────────┼─────────────────────────┼─────────────────────────┤ > │ Backtracking │ Not possible │ PlanState stack pop/push│ > ├─────────────────────┼─────────────────────────┼─────────────────────────┤ > │ Memory Usage │ O(B^D) all paths │ O(D) current path only │ > ├─────────────────────┼─────────────────────────┼─────────────────────────┤ > │ Edge Uniqueness │ <> ALL(array) O(n) │ Array scan O(n) │ > │ │ + array copy per row │ No array copy │ > ├─────────────────────┼─────────────────────────┼─────────────────────────┤ > │ Result Streaming │ After all iterations │ Yield as found │ > ├─────────────────────┼─────────────────────────┼─────────────────────────┤ > │ Code Complexity │ Low (rewriting only) │ High (new executor) │ > ├─────────────────────┼─────────────────────────┼─────────────────────────┤ > │ PostgreSQL Changes │ None │ New plan/executor node │ > └─────────────────────┴─────────────────────────┴─────────────────────────┘ > > > 5. Memory Usage Example > ----------------------- > > Graph: Social network, avg 100 friends per person > Query: MATCH (a)-[:friend*1..4]->(b) RETURN b > > Unoptimized (CTE): > Depth 1: 100 rows > Depth 2: 10,000 rows > Depth 3: 1,000,000 rows > Depth 4: 100,000,000 rows (!) > > Total: ~101 million partial paths in memory > Each path: vertex IDs + edge arrays (growing) > > Optimized (DFS Executor): > PlanState stack: max 4 PlanState (~1KB each) > Path arrays: max 4 edges > Total: ~10KB regardless of graph size > > > 6. Key Techniques Summary > ------------------------- > > ┌────┬───────────────────────────┬────────────────────────────────────────┐ > │ # │ Technique │ Benefit │ > ├────┼───────────────────────────┼────────────────────────────────────────┤ > │ 1 │ Non-Directional Handling │ Support -- (bidirectional) edges │ > │ 2 │ Multi-Label Scan │ Handle label inheritance │ > │ 3 │ PlanState Stack Backtrack │ True DFS with O(depth) memory │ > │ 4 │ Edge Uniqueness Check │ Prevent cycles efficiently │ > │ 5 │ Property Filtering │ Early pruning during scan │ > │ 6 │ Direction-Aware Traversal │ Support ->, <-, -- correctly │ > │ 7 │ Result Streaming │ Return results without full compute │ > │ 8 │ Depth Expansion │ Continue traversal to max depth │ > └────┴───────────────────────────┴────────────────────────────────────────┘ > > > 7. Conclusion > ------------- > > The unoptimized CTE-based approach is simple to implement (query > rewriting only) but suffers from: > > - Exponential memory growth with depth > - No true DFS traversal capability > - No result streaming > - Expensive array operations per row > > The optimized executor-based approach requires more implementation > effort but provides: > > - O(depth) memory usage regardless of graph size > - True DFS with backtracking capability > - Streaming results as they are discovered > - Efficient PlanState-based edge scanning > - Clean integration with PostgreSQL executor framework > > For production graph database systems, the optimized approach is > essential for handling real-world graph sizes and traversal depths. > > This document focuses on the conceptual design. Implementation details > such as PlanState cloning vs. scan position saving, memory allocation > strategies, and index structures are left for follow-up discussion. -- Regards Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
Thanks for the feedback!
On Mon, Jan 5, 2026 at 9:56 PM Henson Choi <assam258@gmail.com> wrote:
>
> Hi hackers,
>
> I think it may be a bit early for this, but I wanted to share this design
> document now so we can revisit and discuss when the time is right.
>
> ===================================================================
> Variable Length Edge (VLE) Implementation Strategies for PostgreSQL
> ===================================================================
>
> 1. Overview
> -----------
>
> This document describes two implementation strategies for Variable
> Length Edge (VLE) traversal in PostgreSQL-based graph databases.
>
> VLE Query Example:
>
> MATCH (a)-[*1..5]->(b) RETURN a, b
> MATCH p = (a)-[:knows*]->(b) RETURN p
>
> Two implementation approaches:
>
> 1. Unoptimized: Query rewriting to WITH RECURSIVE (CTE)
> 2. Optimized: Custom executor node with DFS algorithm
>
Interesting ideas. I was thinking about expanding the edge pattern using the
lower and upper but it seems it can not handle the * case.
a fixed number of JOINs at compile time. But -[*]-> has no upper bound
known at compile time, so unrolling isn't possible.
That said, the traversal is still finite due to the edge uniqueness
constraint (e.id <> ALL(p.edge_ids)) which enforces TRAIL semantics.
This prevents traversing the same edge twice, not revisiting vertices.
In a graph with E edges, the maximum path length is E. The challenge
isn't infinity - it's that we need runtime iteration with dynamic
termination.
ISTM these two approaches can both work when we need runtime
pruning, for example if we are going to support path mode.
Edge predicates ([e* WHERE ...]) are applied at each hop, while path-level
predicates (length, aggregates) require completion. The real difference is
the execution model: CTE uses BFS storing all intermediate paths, whereas
a custom executor enables DFS with backtracking and O(depth) memory.
The first option can be costly, since you have to pre calculate the recursive
CTE, it can not utilize the predicate from previous hops. Can it work with
quantifier * case?
ensures termination.
As mentioned above, edge predicates ([e* WHERE ...]) go into the recursion,
while path-level predicates (length, aggregates) stay outside. Since e* is
a collection, scalar access like "WHERE e.weight > 50" outside the pattern
would be invalid - edge filtering belongs inside [e* WHERE ...].
The second option seems more promising, but it needs to touch the planner
and executor. I guess you need a special node to represent the VLE in
the rewrite phase.
(like SEARCH DEPTH FIRST) needs deeper thought.
This won't be easy, but it's an unavoidable challenge. Adding a new plan
node is one thing, but PlanState stack with push/pop could affect all
executor nodes. I expect this will spark lively discussion among planner
hackers.
Best regards,
Henson
Re: SQL Property Graph Queries (SQL/PGQ)
On Fri, Jan 9, 2026 at 10:22 AM Junwang Zhao wrote: > > Hi Ashutosh, > > Here is a brief review of > v20260102-0001-WIP-SQL-Property-Graph-Queries-SQL-PGQ.patch > > + > + <literal>pg_element_table_key_columns</literal> > + > + > + The view pg_element_key_columns identifies which columns > + are part of the keys of the element tables of property graphs defined in > + the current database. Only those property graphs are shown that the > + current user has access to (by way of being the owner or having some > + privilege). > + > > pg_element_key_columns should be pg_element_table_key_columns > Done. > + > + <literal>pg_element_table_properties</literal> > + > + > + The view pg_element_table_labels shows the definitions > + of the properties for the element tables of property graphs defined in the > + current database. Only those property graphs are shown that the current > + user has access to (by way of being the owner or having some privilege). > + > > pg_element_table_labels here should be pg_element_table_properties, I > guess this was due to copy-paste. Done. > > + > + <literal>pg_property_graph_privileges</literal> > + > + > + The view property_graph_privileges identifies all > + privileges granted on property graphs to a currently enabled role or by a > + currently enabled role. There is one row for each combination of property > + graph, grantor, and grantee. > + > + > +
Re: SQL Property Graph Queries (SQL/PGQ)
On Fri, Jan 9, 2026 at 6:38 PM Henson Choi wrote: > > Hi Junwang, > > Thanks for the feedback! > > 2026년 1월 9일 (금) PM 7:51, Junwang Zhao 님이 작성: >> >> On Mon, Jan 5, 2026 at 9:56 PM Henson Choi wrote: >> > >> > Hi hackers, >> > >> > I think it may be a bit early for this, but I wanted to share this design >> > document now so we can revisit and discuss when the time is right. >> > Let's keep this thread for the discussion of the original patchset. If we discuss new proposals here readers will get confused and we may lose focus. Let's create separate threads for those discussions. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Fri, Jan 9, 2026 at 6:38 PM Henson Choi <assam258@gmail.com> wrote:
>
> Hi Junwang,
>
> Thanks for the feedback!
>
> 2026년 1월 9일 (금) PM 7:51, Junwang Zhao <zhjwpku@gmail.com>님이 작성:
>>
>> On Mon, Jan 5, 2026 at 9:56 PM Henson Choi <assam258@gmail.com> wrote:
>> >
>> > Hi hackers,
>> >
>> > I think it may be a bit early for this, but I wanted to share this design
>> > document now so we can revisit and discuss when the time is right.
>> >
Let's keep this thread for the discussion of the original patchset. If
we discuss new proposals here readers will get confused and we may
lose focus. Let's create separate threads for those discussions.
I agree the current patch should be completed first,
and I look forward to Ashutosh leading the discussion
--
Best Wishes,
Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Hi hackers, Thank you for sharing this insightful discussion. I'm a new developer interested in this topic. The design of VLE is particularly fascinating to me because of the potential performance impact it could bring. Regarding the challenges of the custom executor approach (Option 2) that you both highlighted, especially the integration with the PlanState stack and the need for push/pop semantics, I have been trying to understand it better. From my reading of the executor code, ExprContext and the TupleTableSlot lifecycle are managed per tuple. For a DFS backtracking model, would we need to introduce a new concept like a “TraversalState” that persists across the recursive hops, perhaps housed within the VlePathScan's PlanState? Or is there an existing mechanism (like the SubPlan state for parameterized subqueries) that we could adapt to manage the stack of visited edges and vertices? Looking forward to learning more from the community discussion. Best regards, Huanbing 在 2026/1/9 21:08, Henson Choi 写道: > Hi Junwang, > > Thanks for the feedback! > > 2026년 1월 9일 (금) PM 7:51, Junwang Zhao 님이 작성: > >> On Mon, Jan 5, 2026 at 9:56 PM Henson Choi wrote: >>> Hi hackers, >>> >>> I think it may be a bit early for this, but I wanted to share this design >>> document now so we can revisit and discuss when the time is right. >>> >>> =================================================================== >>> Variable Length Edge (VLE) Implementation Strategies for PostgreSQL >>> =================================================================== >>> >>> 1. Overview >>> ----------- >>> >>> This document describes two implementation strategies for Variable >>> Length Edge (VLE) traversal in PostgreSQL-based graph databases. >>> >>> VLE Query Example: >>> >>> MATCH (a)-[*1..5]->(b) RETURN a, b >>> MATCH p = (a)-[:knows*]->(b) RETURN p >>> >>> Two implementation approaches: >>> >>> 1. Unoptimized: Query rewriting to WITH RECURSIVE (CTE) >>> 2. Optimized: Custom executor node with DFS algorithm >>> >> Interesting ideas. I was thinking about expanding the edge pattern using >> the >> lower and upper but it seems it can not handle the * case. >> > Right. With a bounded quantifier like -[*1..3]->, we can unroll it into > a fixed number of JOINs at compile time. But -[*]-> has no upper bound > known at compile time, so unrolling isn't possible. > > That said, the traversal is still finite due to the edge uniqueness > constraint (e.id <> ALL(p.edge_ids)) which enforces TRAIL semantics. > This prevents traversing the same edge twice, not revisiting vertices. > In a graph with E edges, the maximum path length is E. The challenge > isn't infinity - it's that we need runtime iteration with dynamic > termination. > > >> ISTM these two approaches can both work when we need runtime >> pruning, for example if we are going to support path mode. >> > Agreed. Both approaches can support path modes (WALK/TRAIL/ACYCLIC/SIMPLE). > Edge predicates ([e* WHERE ...]) are applied at each hop, while path-level > predicates (length, aggregates) require completion. The real difference is > the execution model: CTE uses BFS storing all intermediate paths, whereas > a custom executor enables DFS with backtracking and O(depth) memory. > > >> The first option can be costly, since you have to pre calculate the >> recursive >> CTE, it can not utilize the predicate from previous hops. Can it work with >> quantifier * case? >> > Yes, CTE can handle * - the edge uniqueness constraint (e.id <> ALL(...)) > ensures termination. > > As mentioned above, edge predicates ([e* WHERE ...]) go into the recursion, > while path-level predicates (length, aggregates) stay outside. Since e* is > a collection, scalar access like "WHERE e.weight > 50" outside the pattern > would be invalid - edge filtering belongs inside [e* WHERE ...]. > > >> The second option seems more promising, but it needs to touch the planner >> and executor. I guess you need a special node to represent the VLE in >> the rewrite phase. >> > Right. Whether to introduce new syntax or hijack existing constructs > (like SEARCH DEPTH FIRST) needs deeper thought. > > This won't be easy, but it's an unavoidable challenge. Adding a new plan > node is one thing, but PlanState stack with push/pop could affect all > executor nodes. I expect this will spark lively discussion among planner > hackers. > > Best regards, > Henson >
Re: SQL Property Graph Queries (SQL/PGQ)
Thank you for your interest and insightful question about the TraversalState
concept. You've identified exactly the right challenge with the custom
executor approach.
However, as Ashutosh suggested, let's keep this thread focused on the
current PGQ patch. Your question about DFS backtracking and PlanState
management deserves a thorough discussion, which we can have once the
current work is committed.
I'm looking forward to discussing VLE implementation details with you
and the community then.
Best regards,
Henson
Re: SQL Property Graph Queries (SQL/PGQ)
On 18.12.25 10:15, Ashutosh Bapat wrote: > I was aware of ecpg and I vaguely remember we fixed something in ECPG > to allow : in MATCH statement. Probably following changes in > psqlscan.l and pgc.l > -self [,()\[\].;\:\+\-\*\/\%\^\<\>\=] > +self [,()\[\].;\:\|\+\-\*\/\%\^\<\>\=] > > Those changes add | after : (and not the : itself) so maybe they are > not about supporting : . Do you remember what those are? These are required to support label disjunctions. If you add one of those to the ecpg sqlpgq tests you added, like (c IS customer|customer), then it will fail to compile without this change. The psql change has perhaps no such impact, but in general, these are supposed to be kept in sync with the main scan.l. > In ddl.sgml I noticed a seemingly incomplete sentence > A property graph is a way to represent database contents, instead of using > relational structures such as tables. Maybe it's clearer like this: "A property graph is a way to represent database contents, as an alternative to the usual (in SQL) approach of representing database contents using relational structures such as tables." > 0002 has extra tests mentioned above. It also removes "TODO: dubious > error message" from a comment. I don't see anything dubious in the > error message. I think this patch is safe to be merged into 0001. Hmm, yeah, this might have been a leftover from a different catalog structure that resulted in different detail messages from the dependency infrastructure. I can't see anything wrong with the current output either.
Re: SQL Property Graph Queries (SQL/PGQ)
On 02.01.26 09:48, Ashutosh Bapat wrote: >> #1 [Code] src/backend/commands/propgraphcmds.c:1632 >> FIXME: Missing index for plppropid column causes sequential scan. >> Decision needed: (a) add index, or (c) allow seq scan for rare path. > > The path is rare enough that I think we can allow the seq scan. Given > that Peter has marked it as FIXME, it seems we will keep it as is for > now, but will revisit if performance becomes an issue. Peter, please > correct me if I'm wrong. Yeah, doesn't seem critical. Maybe "downgrade" to "XXX". >> #5 [Doc] doc/src/sgml/queries.sgml:2929,2931 >> TODO comments for unimplemented features without clear limitation notes. > > Those TODOs are not visible to users. I think they serve as > placeholders to add the documentation when the features are > implemented. We may want to remove them, but I see no harm in keeping > them for now. Peter, what do you think? We should keep them and fill them in. :)
Re: SQL Property Graph Queries (SQL/PGQ)
I have a small fixup patch for your 20260102 patches, attached. - needs additional #include because of recent changes elsewhere - copyright year updates - various typos - some style changes related to palloc APIs
Re: SQL Property Graph Queries (SQL/PGQ)
On Tue, Jan 13, 2026 at 3:42 PM Peter Eisentraut wrote: > > On 18.12.25 10:15, Ashutosh Bapat wrote: > > I was aware of ecpg and I vaguely remember we fixed something in ECPG > > to allow : in MATCH statement. Probably following changes in > > psqlscan.l and pgc.l > > -self [,()\[\].;\:\+\-\*\/\%\^\<\>\=] > > +self [,()\[\].;\:\|\+\-\*\/\%\^\<\>\=] > > > > Those changes add | after : (and not the : itself) so maybe they are > > not about supporting : . Do you remember what those are? > > These are required to support label disjunctions. If you add one of > those to the ecpg sqlpgq tests you added, like (c IS customer|customer), > then it will fail to compile without this change. > Ah! I see. Added a test for the same using (c IS customer | customer) > > > In ddl.sgml I noticed a seemingly incomplete sentence > > A property graph is a way to represent database contents, instead of using > > relational structures such as tables. > > Maybe it's clearer like this: > > "A property graph is a way to represent database contents, as an > alternative to the usual (in SQL) approach of representing database > contents using relational structures such as tables." WFM. Applied. > > > 0002 has extra tests mentioned above. It also removes "TODO: dubious > > error message" from a comment. I don't see anything dubious in the > > error message. I think this patch is safe to be merged into 0001. > > Hmm, yeah, this might have been a leftover from a different catalog > structure that resulted in different detail messages from the dependency > infrastructure. I can't see anything wrong with the current output either. > Ok. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Tue, Jan 13, 2026 at 3:47 PM Peter Eisentraut wrote: > > On 02.01.26 09:48, Ashutosh Bapat wrote: > >> #1 [Code] src/backend/commands/propgraphcmds.c:1632 > >> FIXME: Missing index for plppropid column causes sequential scan. > >> Decision needed: (a) add index, or (c) allow seq scan for rare path. > > > > The path is rare enough that I think we can allow the seq scan. Given > > that Peter has marked it as FIXME, it seems we will keep it as is for > > now, but will revisit if performance becomes an issue. Peter, please > > correct me if I'm wrong. > > Yeah, doesn't seem critical. Maybe "downgrade" to "XXX". I see you have done in the patch attached to your next response. > > >> #5 [Doc] doc/src/sgml/queries.sgml:2929,2931 > >> TODO comments for unimplemented features without clear limitation notes. > > > > Those TODOs are not visible to users. I think they serve as > > placeholders to add the documentation when the features are > > implemented. We may want to remove them, but I see no harm in keeping > > them for now. Peter, what do you think? > > We should keep them and fill them in. :) > Works for me. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Tue, Jan 13, 2026 at 3:53 PM Peter Eisentraut wrote: > > I have a small fixup patch for your 20260102 patches, attached. > > - needs additional #include because of recent changes elsewhere > - copyright year updates > - various typos > - some style changes related to palloc APIs All changes look good. Looks like you have reviewed patches 0002-onwards. I removed 0004 which was erroneously removing the | handling from ecpg lexer as you pointed out earlier. Squashed all other patches along with your small fixup patch. Attached is the resultant single patch. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Observation on patch v20260113-0001: GRAPH_TABLE queries are bypassing
Row-Level Security checks. A low_priv_user is able to access sensitive
data across the entire table, even though the RLS policy should
restrict the result set to one non-sensitive row.
reproducible case:-
CREATE TABLE parent_node (id int PRIMARY KEY, secret text);
CREATE TABLE child_node () INHERITS (parent_node);
INSERT INTO child_node VALUES (1, 'Sensitive');
INSERT INTO child_node VALUES (2, 'not Sensitive');
CREATE ROLE low_priv_user;
GRANT SELECT ON parent_node TO low_priv_user;
GRANT SELECT ON child_node TO low_priv_user;
ALTER TABLE child_node ENABLE ROW LEVEL SECURITY;
-- Policy: user cannot see rows where secret contains 'Sensitive'
CREATE POLICY p_hide_sensitive ON child_node TO low_priv_user USING
(secret !~ 'Sensitive');
CREATE PROPERTY GRAPH security_graph VERTEX TABLES (parent_node);
GRANT SELECT ON PROPERTY GRAPH security_graph TO low_priv_user;
-- TEST: As low_priv_user, this query should return 0 rows.
SET ROLE low_priv_user;
postgres=> SELECT * FROM GRAPH_TABLE (security_graph MATCH (n) COLUMNS
(n.secret));
secret
---------------
Sensitive
not Sensitive
(2 rows)
Thanks
Ajay
On Tue, Jan 13, 2026 at 9:44 PM Ashutosh Bapat
wrote:
>
> On Tue, Jan 13, 2026 at 3:53 PM Peter Eisentraut wrote:
> >
> > I have a small fixup patch for your 20260102 patches, attached.
> >
> > - needs additional #include because of recent changes elsewhere
> > - copyright year updates
> > - various typos
> > - some style changes related to palloc APIs
>
> All changes look good.
>
> Looks like you have reviewed patches 0002-onwards. I removed 0004
> which was erroneously removing the | handling from ecpg lexer as you
> pointed out earlier. Squashed all other patches along with your small
> fixup patch. Attached is the resultant single patch.
>
> --
> Best Wishes,
> Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
I looked into this and it appears to be expected PostgreSQL behavior rather than a GRAPH_TABLE-specific issue.
Observation on patch v20260113-0001: GRAPH_TABLE queries are bypassing
Row-Level Security checks. A low_priv_user is able to access sensitive
data across the entire table, even though the RLS policy should
restrict the result set to one non-sensitive row.
reproducible case:-
CREATE TABLE parent_node (id int PRIMARY KEY, secret text);
CREATE TABLE child_node () INHERITS (parent_node);
INSERT INTO child_node VALUES (1, 'Sensitive');
INSERT INTO child_node VALUES (2, 'not Sensitive');
CREATE ROLE low_priv_user;
GRANT SELECT ON parent_node TO low_priv_user;
GRANT SELECT ON child_node TO low_priv_user;
ALTER TABLE child_node ENABLE ROW LEVEL SECURITY;
-- Policy: user cannot see rows where secret contains 'Sensitive'
CREATE POLICY p_hide_sensitive ON child_node TO low_priv_user USING
(secret !~ 'Sensitive');
CREATE PROPERTY GRAPH security_graph VERTEX TABLES (parent_node);
GRANT SELECT ON PROPERTY GRAPH security_graph TO low_priv_user;
-- TEST: As low_priv_user, this query should return 0 rows.
SET ROLE low_priv_user;
postgres=> SELECT * FROM GRAPH_TABLE (security_graph MATCH (n) COLUMNS
(n.secret));
secret
---------------
Sensitive
not Sensitive
(2 rows)
SELECT secret FROM parent_node;
secret
---------------
Sensitive
not Sensitive
(2 rows)
This behavior is tested in src/test/regress/sql/rowsecurity.sql (lines 374-414).
The fix would be to enable RLS on parent_node instead of child_node.
Thanks
Ajay
On Tue, Jan 13, 2026 at 9:44 PM Ashutosh Bapat
<ashutosh.bapat.oss@gmail.com> wrote:
>
> On Tue, Jan 13, 2026 at 3:53 PM Peter Eisentraut <peter@eisentraut.org> wrote:
> >
> > I have a small fixup patch for your 20260102 patches, attached.
> >
> > - needs additional #include because of recent changes elsewhere
> > - copyright year updates
> > - various typos
> > - some style changes related to palloc APIs
>
> All changes look good.
>
> Looks like you have reviewed patches 0002-onwards. I removed 0004
> which was erroneously removing the | handling from ecpg lexer as you
> pointed out earlier. Squashed all other patches along with your small
> fixup patch. Attached is the resultant single patch.
>
> --
> Best Wishes,
> Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Thu, Jan 22, 2026 at 5:26 PM Henson Choi wrote: > > Hi Ajay, > > I looked into this and it appears to be expected PostgreSQL behavior rather than a GRAPH_TABLE-specific issue. +1. This behaviour is documented in [1] " Inherited queries perform access permission checks on the parent table only. Thus, for example, granting UPDATE permission on the cities table implies permission to update rows in the capitals table as well, when they are accessed through cities. This preserves the appearance that the data is (also) in the parent table. But the capitals table could not be updated directly without an additional grant. In a similar way, the parent table's row security policies (see Section 5.9) are applied to rows coming from child tables during an inherited query. A child table's policies, if any, are applied only when it is the table explicitly named in the query; and in that case, any policies attached to its parent(s) are ignored. " [1] https://www.postgresql.org/docs/current/ddl-inherit.html#:~:text=In%20a%20similar%20way%2C%20the%20parent%20table's,policies%20attached%20to%20its%20parent(s)%20are%20ignored. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Thank you Ashutosh and Henson for clarification. On Thu, Jan 22, 2026 at 8:20 PM Ashutosh Bapat wrote: > > On Thu, Jan 22, 2026 at 5:26 PM Henson Choi wrote: > > > > Hi Ajay, > > > > I looked into this and it appears to be expected PostgreSQL behavior rather than a GRAPH_TABLE-specific issue. > > +1. This behaviour is documented in [1] > > " > Inherited queries perform access permission checks on the parent table > only. Thus, for example, granting UPDATE permission on the cities > table implies permission to update rows in the capitals table as well, > when they are accessed through cities. This preserves the appearance > that the data is (also) in the parent table. But the capitals table > could not be updated directly without an additional grant. In a > similar way, the parent table's row security policies (see Section > 5.9) are applied to rows coming from child tables during an inherited > query. A child table's policies, if any, are applied only when it is > the table explicitly named in the query; and in that case, any > policies attached to its parent(s) are ignored. > " > > [1] https://www.postgresql.org/docs/current/ddl-inherit.html#:~:text=In%20a%20similar%20way%2C%20the%20parent%20table's,policies%20attached%20to%20its%20parent(s)%20are%20ignored. > > -- > Best Wishes, > Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On 13.01.26 17:14, Ashutosh Bapat wrote: > On Tue, Jan 13, 2026 at 3:53 PM Peter Eisentraut wrote: >> >> I have a small fixup patch for your 20260102 patches, attached. >> >> - needs additional #include because of recent changes elsewhere >> - copyright year updates >> - various typos >> - some style changes related to palloc APIs > > All changes look good. > > Looks like you have reviewed patches 0002-onwards. I removed 0004 > which was erroneously removing the | handling from ecpg lexer as you > pointed out earlier. Squashed all other patches along with your small > fixup patch. Attached is the resultant single patch. I have studied a bit the changes in parse_relation.c with the additional relkind checks. That didn't look clean to me. I have attached here a patch that does it differently, by *not* accepting RELKIND_PROPGRAPH in table_open(). Instead, we write our own alternative to parserOpenTable() to use in the parser. This ends up even giving some better error messages. The only other change is that in AcquireRewriteLocks() we need to use relation_open() instead of table_open(), but that seems harmless and even intellectually better, because at that point we don't care about giving anyone a user-facing error message about wrong relkinds, we just want to lock the ones we have. (Alternatively, we could make a separate switch case for RTE_GRAPH_TABLE.) What do you think? Also, see this patch: https://www.postgresql.org/message-id/6d3fef19-a420-4e11-8235-8ea534bf2080%40eisentraut.org If this is accepted, it would make the change in the patch here even smaller. And then there is this patch: https://www.postgresql.org/message-id/4bcd65fb-2497-484c-bb41-83cb435eb64d%40eisentraut.org which also grew out of this analysis.
Re: SQL Property Graph Queries (SQL/PGQ)
On Wed, Feb 18, 2026 at 8:58 PM Peter Eisentraut wrote: > > On 13.01.26 17:14, Ashutosh Bapat wrote: > > On Tue, Jan 13, 2026 at 3:53 PM Peter Eisentraut wrote: > >> > >> I have a small fixup patch for your 20260102 patches, attached. > >> > >> - needs additional #include because of recent changes elsewhere > >> - copyright year updates > >> - various typos > >> - some style changes related to palloc APIs > > > > All changes look good. > > > > Looks like you have reviewed patches 0002-onwards. I removed 0004 > > which was erroneously removing the | handling from ecpg lexer as you > > pointed out earlier. Squashed all other patches along with your small > > fixup patch. Attached is the resultant single patch. > > I have studied a bit the changes in parse_relation.c with the additional > relkind checks. That didn't look clean to me. I have attached here a > patch that does it differently, by *not* accepting RELKIND_PROPGRAPH in > table_open(). Instead, we write our own alternative to > parserOpenTable() to use in the parser. This ends up even giving some > better error messages. This looks good to me. I wondered whether to create propgraph_open() and validate_relation_kind() for propgraph in a separate file propgraph.c on the lines of sequence.c. But we will still need something like parserOpenPropGraph() to handle callback. So doesn't seem to have an advantage of sequence_open which is not called from parser. Also parserOpenPropGraph()'s placement seems to be ok since there is only one caller in parse_clause.c. This looks better than the earlier changes in parse_relation.c > The only other change is that in > AcquireRewriteLocks() we need to use relation_open() instead of > table_open(), but that seems harmless and even intellectually better, > because at that point we don't care about giving anyone a user-facing > error message about wrong relkinds, we just want to lock the ones we > have. +1. > (Alternatively, we could make a separate switch case for > RTE_GRAPH_TABLE.) > > What do you think? LGTM. I am actually wondering whether the comment in parserOpenPropGraph() is required. In case we want to keep it, the attached patch has a typo fix. It also has some more improvements. > > Also, see this patch: > > https://www.postgresql.org/message-id/6d3fef19-a420-4e11-8235-8ea534bf2080%40eisentraut.org > > If this is accepted, it would make the change in the patch here even > smaller. +1. I think we should commit this, rebase SQL/PGQ patches and then apply this change. > > And then there is this patch: > > https://www.postgresql.org/message-id/4bcd65fb-2497-484c-bb41-83cb435eb64d%40eisentraut.org > > which also grew out of this analysis. Reviewed both the patches. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Has there been any progress on this?
Shortest path queries seem to be something that would greatly benefit
from having UNION DISTINCT ON ()
---
Hannu
On Mon, Jan 5, 2026 at 2:58 PM Henson Choi wrote:
>
> Hi hackers,
>
> I think it may be a bit early for this, but I wanted to share this design
> document now so we can revisit and discuss when the time is right.
>
> =====================================================
> Shortestpath Implementation Strategies for PostgreSQL
> =====================================================
>
> 1. Overview
> -----------
>
> This document describes two implementation strategies for shortest path
> queries in PostgreSQL-based graph databases.
>
> Shortestpath Query Example:
>
> MATCH p = shortestpath((a)-[*]->(b)) RETURN p
> MATCH p = allshortestpaths((a)-[:knows*]->(b)) RETURN p
>
> Two implementation approaches:
>
> 1. Unoptimized: Query rewriting to WITH RECURSIVE (CTE)
> 2. Optimized: Custom executor node with bidirectional BFS
>
>
> 2. Unoptimized Approach: WITH RECURSIVE Rewriting
> -------------------------------------------------
>
> 2.1 Query Transformation
>
> Cypher query:
>
> MATCH p = shortestpath((a:person)-[:knows*]->(b:person))
> WHERE a.name = 'Alice' AND b.name = 'Bob'
> RETURN p
>
> Rewritten SQL using WITH RECURSIVE:
>
> WITH RECURSIVE sp_paths AS (
> -- Base case: start vertex
> SELECT v.id as start_vid,
> v.id as end_vid,
> ARRAY[v.id] as vertex_ids,
> ARRAY[]::bigint[] as edge_ids,
> 0 as depth
> FROM person v
> WHERE name = 'Alice'
>
> UNION ALL
>
> -- Recursive case: expand one hop
> SELECT p.start_vid,
> e.end_id,
> p.vertex_ids || e.end_id,
> p.edge_ids || e.id,
> p.depth + 1
> FROM sp_paths p
> JOIN knows e ON p.end_vid = e.start_id
> WHERE e.end_id <> ALL(p.vertex_ids) -- Cycle prevention
> )
> SELECT vertex_ids, edge_ids, depth
> FROM sp_paths
> WHERE end_vid = (SELECT id FROM person WHERE name = 'Bob')
> ORDER BY depth
> LIMIT 1;
>
> 2.2 Execution Plan
>
> Limit
> -> Sort
> Sort Key: depth
> -> CTE Scan on sp_paths
> Filter: (end_vid = $bob_id)
> CTE sp_paths
> Recursive Union
> Seq Scan on person v
> Filter: (name = 'Alice')
> Hash Join
> Hash Cond: (p.end_vid = e.start_id)
> Filter: (e.end_id <> ALL(p.vertex_ids))
> WorkTable Scan on sp_paths p
> Hash
> Seq Scan on knows e
>
> 2.3 Problems
>
> ┌─────────────────────┬──────────────────────────────────────────┐
> │ Problem │ Description │
> ├─────────────────────┼──────────────────────────────────────────┤
> │ Unidirectional │ Search expands only from start vertex │
> │ │ Misses optimization from end vertex │
> ├─────────────────────┼──────────────────────────────────────────┤
> │ Full Exploration │ Must explore all paths up to min depth │
> │ │ before finding shortest │
> ├─────────────────────┼──────────────────────────────────────────┤
> │ No Early Termination│ Cannot stop when shortest found │
> │ │ CTE runs to completion │
> ├─────────────────────┼──────────────────────────────────────────┤
> │ Memory Usage │ O(V) visited vertices per iteration │
> │ │ All partial paths stored │
> ├─────────────────────┼──────────────────────────────────────────┤
> │ Cycle Prevention │ <> ALL(array) grows with path length │
> │ │ O(path_length) per edge check │
> └─────────────────────┴──────────────────────────────────────────┘
>
> 2.4 Search Space Comparison
>
> Unidirectional BFS (CTE):
>
> Start ──────────────────────────────────────> End
> ╲ ╱
> ╲ Explores entire cone ╱
> ╲ from start ╱
> ╲ ╱
> ╲ Search space: O(B^D) ╱
> ╲ ╱
> ────────────────────────
>
> Bidirectional BFS (Optimized):
>
> Start ────────> <──────── End
> ╲ ╱╲ ╱
> ╲ ╱ ╲ ╱
> ╲ ╱ ╲ ╱
> ╲ ╱ Meet ╲ ╱
> ╲╱ Point ╲
> Search space: O(2 * B^(D/2))
>
>
> 3. Optimized Approach: Custom Executor Node
> -------------------------------------------
>
> 3.1 Design Principle
>
> Instead of query rewriting, implement a dedicated executor node that:
>
> - Performs bidirectional BFS from both start and end vertices
> - Uses hash tables to track visited vertices from each direction
> - Detects meeting point where both searches intersect
> - Terminates early when shortest path is found
>
> 3.2 Plan Node Structure
>
> ┌────────────────────────────────────────────────────────────┐
> │ ShortestpathPlan │
> │ - Bidirectional BFS with dual hash tables │
> │ - Early termination on path found │
> └────────────────────────────────────────────────────────────┘
> │ │
> left │ │ right
> ▼ ▼
> ┌───────────────────────────┐ ┌───────────────────────────┐
> │ Hash2Side (Left) │ │ Hash2Side (Right) │
> │ - KeyTable + HashTable │ │ - KeyTable + HashTable │
> │ - Forward direction │ │ - Reverse direction │
> └───────────────────────────┘ └───────────────────────────┘
> │ │
> ▼ ▼
> ┌───────────────────────────┐ ┌───────────────────────────┐
> │ SubPlan (Forward) │ │ SubPlan (Reverse) │
> │ Index Cond: │ │ Index Cond: │
> │ start_id = $current │ │ end_id = $current │
> └───────────────────────────┘ └───────────────────────────┘
>
> Execution Flow:
>
> Initialize:
> Left HashTable = {start_vertex}
> Right HashTable = {end_vertex}
> │
> ▼
> Expansion loop (smaller side first):
> │
> ├──→ Compare |Left frontier| vs |Right frontier|
> │ │
> │ └──→ Expand smaller side
> │ │
> │ └──→ Check intersection with other side
> │
> ├──→ Repeat until intersection found
> │
> └──→ Return shortest path(s)
>
>
> 3.3 Key Concept: Dual Hash Tables
>
> The executor maintains two hash tables for bidirectional search:
>
> ┌─────────────────────────────────────────────────────────────┐
> │ Left Direction (Start → End) │
> │ ┌─────────────────────────────────────────────────────┐ │
> │ │ KeyTable: Previous hop vertices (expansion base) │ │
> │ │ HashTable: Current hop results (newly discovered) │ │
> │ └─────────────────────────────────────────────────────┘ │
> ├─────────────────────────────────────────────────────────────┤
> │ Right Direction (End → Start) │
> │ ┌─────────────────────────────────────────────────────┐ │
> │ │ KeyTable: Previous hop vertices (expansion base) │ │
> │ │ HashTable: Current hop results (newly discovered) │ │
> │ └─────────────────────────────────────────────────────┘ │
> └─────────────────────────────────────────────────────────────┘
>
> After each hop:
> - Swap KeyTable and HashTable (new base for next hop)
> - Check for intersection between Left and Right HashTables
> - If intersection found, reconstruct path through meeting point
>
> 3.4 Key Concept: Smaller Side Expansion
>
> At each hop, expand from the direction with fewer frontier vertices.
> This minimizes the total number of edges scanned.
>
> Example (highly unbalanced tree):
>
> Graph structure:
> - Forward (Left->Right): branching factor = 100
> - Backward (Right->Left): branching factor = 2
> - Path distance: 6 hops
>
> Simple alternating:
>
> Hop 1: expand Left (1) -> Left=100, Right=1
> Hop 2: expand Right (1) -> Left=100, Right=2
> Hop 3: expand Left (100) -> Left=10,000, Right=2
> Hop 4: expand Right (2) -> Left=10,000, Right=4
> Hop 5: expand Left (10,000) -> Left=1,000,000, Right=4
> Hop 6: expand Right (4) -> meet!
>
> Total vertices expanded: 1 + 1 + 100 + 2 + 10,000 + 4 = 10,108
>
> With smaller side expansion:
>
> Hop 1: Left=1, Right=1 -> expand Left -> Left=100, Right=1
> Hop 2: 1 < 100 -> expand Right -> Left=100, Right=2
> Hop 3: 2 < 100 -> expand Right -> Left=100, Right=4
> Hop 4: 4 < 100 -> expand Right -> Left=100, Right=8
> Hop 5: 8 < 100 -> expand Right -> Left=100, Right=16
> Hop 6: 16 < 100 -> expand Right -> meet!
>
> Total vertices expanded: 1 + 1 + 2 + 4 + 8 + 16 = 32
>
> Speedup: 10,108 / 32 = ~300x fewer vertices explored
>
>
> 3.5 Key Concept: Cycle Detection via Hash Lookup
>
> Hash table insertion automatically prevents revisiting vertices.
>
> Two tuple types in HashTable:
>
> ┌─────────────────────────────────────────────────────────────┐
> │ Long Tuple (path data) │
> │ ┌─────────┬─────────┬─────────────────────────────────┐ │
> │ │ Header │ Graphid │ Edge Rowids (path to vertex) │ │
> │ └─────────┴─────────┴─────────────────────────────────┘ │
> ├─────────────────────────────────────────────────────────────┤
> │ Short Tuple (visited marker) │
> │ ┌─────────┬─────────┐ │
> │ │ Header │ Graphid │ <- No path data, just marker │
> │ └─────────┴─────────┘ │
> └─────────────────────────────────────────────────────────────┘
>
> Insertion logic:
>
> 1. Inserting long tuple (with path):
> - Check if short tuple (marker) exists for same Graphid
> - If marker exists: reject insertion (already visited)
>
> 2. Inserting short tuple (marker):
> - Insert marker first
> - Remove all existing long tuples with same Graphid
> - Vertex is now "locked" - no more paths to this vertex
>
> Example:
>
> Left Hop 1: Expand from A
> HashTable = {B(long), C(long)} <- paths A->B, A->C
>
> Left and Right meet at C -> shortest path found
>
> Insert C(short) marker:
> HashTable = {B(long), C(short)} <- C's long tuple removed
>
> Later, another path tries to reach C (e.g., D->C):
> -> C(short) marker exists -> insertion rejected
> -> Already processed at shortest hop
>
> Benefits:
> - O(1) duplicate detection via hash lookup
> - No separate "visited" set needed
> - Automatic cleanup of superseded paths
> - Memory efficient (markers are minimal size)
>
>
> 3.6 Key Concept: Batch Synchronization
>
> When hash table exceeds memory, it splits into multiple batches.
> Left and Right hash tables must have matching batch structure:
>
> Problem without synchronization:
>
> Left: nbatch=1 [all data in batch 0]
> Right: nbatch=4 [batch0] [batch1] [batch2] [batch3]
>
> -> Cannot find intersection (different batch structures)
>
> Solution:
>
> When Right splits into 4 batches, clone structure to Left:
>
> Left: nbatch=4 [batch0] [batch1] [batch2] [batch3]
> Right: nbatch=4 [batch0] [batch1] [batch2] [batch3]
> | | | |
> Join only matching batches
>
> This ensures correct intersection detection across batch boundaries.
>
>
> 3.7 Execution Plan (Optimized)
>
> EXPLAIN MATCH p = shortestpath((a:person)-[:knows*]->(b:person))
> WHERE a.name='Alice' AND b.name='Bob' RETURN p
>
> Shortestpath (limit=1)
> -> Hash2Side (left direction=FORWARD)
> -> Index Scan on knows e
> Index Cond: (start_id = $current_vertex)
> -> Hash2Side (right direction=REVERSE)
> -> Index Scan on knows e
> Index Cond: (end_id = $current_vertex)
>
>
> 4. Comparison Summary
> ---------------------
>
> ┌─────────────────────┬─────────────────────────┬─────────────────────────┐
> │ Aspect │ Unoptimized (CTE) │ Optimized (Executor) │
> ├─────────────────────┼─────────────────────────┼─────────────────────────┤
> │ Implementation │ Query rewriting │ Custom executor node │
> ├─────────────────────┼─────────────────────────┼─────────────────────────┤
> │ Search Direction │ Unidirectional │ Bidirectional │
> ├─────────────────────┼─────────────────────────┼─────────────────────────┤
> │ Search Space │ O(B^D) │ O(2 * B^(D/2)) │
> ├─────────────────────┼─────────────────────────┼─────────────────────────┤
> │ Early Termination │ Not possible │ Stop when path found │
> ├─────────────────────┼─────────────────────────┼─────────────────────────┤
> │ Data Structure │ WorkTable (tuplestore) │ Dual hash tables │
> ├─────────────────────┼─────────────────────────┼─────────────────────────┤
> │ Cycle Prevention │ Array membership check │ Hash table lookup O(1) │
> ├─────────────────────┼─────────────────────────┼─────────────────────────┤
> │ Code Complexity │ Low (rewriting only) │ High (new executor) │
> ├─────────────────────┼─────────────────────────┼─────────────────────────┤
> │ PostgreSQL Changes │ None │ New plan/executor node │
> └─────────────────────┴─────────────────────────┴─────────────────────────┘
>
>
> 5. Search Space Example
> -----------------------
>
> Graph: Social network, avg 100 connections per person
> Query: shortestpath((Alice)-[*]->(Bob)), actual distance = 6 hops
>
> Unidirectional BFS (CTE):
> Hop 1: 100 vertices
> Hop 2: 10,000 vertices
> Hop 3: 1,000,000 vertices
> Hop 4: 100,000,000 vertices
> Hop 5: 10,000,000,000 vertices
> Hop 6: Find Bob
>
> Total vertices explored: ~10 billion
>
> Bidirectional BFS with smaller side expansion:
> Hop 1: Left=1, Right=1 -> expand Left -> Left=100
> Hop 2: 1 < 100 -> expand Right -> Right=100
> Hop 3: 100 = 100 -> expand Left -> Left=10,000
> Hop 4: 100 < 10,000 -> expand Right -> Right=10,000
> Hop 5: 10,000 = 10,000 -> expand Left -> Left=1,000,000
> Hop 6: 10,000 < 1,000,000-> expand Right -> Meet!
>
> Total vertices explored: ~1 million (each side explores ~500K)
>
> Speedup: ~10,000x fewer vertices explored
>
>
> 6. Key Techniques Summary
> -------------------------
>
> ┌────┬───────────────────────────┬────────────────────────────────────────┐
> │ # │ Technique │ Benefit │
> ├────┼───────────────────────────┼────────────────────────────────────────┤
> │ 1 │ Bidirectional BFS │ Exponential reduction in search space │
> │ 2 │ Dual Hash Tables │ O(1) visited check, O(1) intersection │
> │ 3 │ Smaller Side Expansion │ Expand from side with fewer vertices │
> │ 4 │ Early Termination │ Stop immediately when path found │
> │ 5 │ Cycle Detection │ Hash lookup prevents revisiting vertex │
> │ 6 │ Batch Synchronization │ Match nbatch between Left/Right hashes │
> │ 7 │ Path Reconstruction │ Merge left and right paths at meeting │
> │ 8 │ Parameterized Subplan │ Reuse edge scan plan per vertex │
> │ 9 │ Batch Processing │ Handle memory overflow with batching │
> │ 10 │ Limit Control │ shortestpath (1) vs allshortestpaths │
> └────┴───────────────────────────┴────────────────────────────────────────┘
>
>
> 7. Conclusion
> -------------
>
> The unoptimized CTE-based approach is simpler to implement but suffers from:
>
> - Unidirectional search with O(B^D) complexity
> - No early termination capability
> - Inefficient cycle prevention with arrays
> - Must explore all paths before finding shortest
>
> The optimized executor-based approach requires more implementation
> effort but provides:
>
> - Bidirectional BFS with O(B^(D/2)) complexity
> - Early termination when shortest path found
> - Efficient hash-based visited tracking
> - Support for both shortestpath and allshortestpaths
>
> For production graph database systems, the bidirectional BFS approach
> is essential for practical shortest path queries on large graphs.
>
> This document focuses on the conceptual design. Implementation details
> such as hash table sizing, batch overflow handling, and path reconstruction
> algorithms are left for follow-up discussion.
>
Re: SQL Property Graph Queries (SQL/PGQ)
> Has there been any progress on this?
The base SQL/PGQ patch is currently in final review. We are
refraining from expanding the discussion at this stage. Once
the patch is committed, it would be best to continue as a
separate discussion thread.
> Shortest path queries seem to be something that would greatly benefit
> from having UNION DISTINCT ON ()
Good idea. It still has the performance limitation of unidirectional
BFS, but the advantage of rapid development makes it a viable
improvement. I'll definitely keep this in mind for the future
discussion.
Best regards,
Henson
Re: SQL Property Graph Queries (SQL/PGQ)
On Thu, Feb 19, 2026 at 3:01 PM Ashutosh Bapat wrote: > > > I am actually wondering whether the comment in parserOpenPropGraph() > is required. In case we want to keep it, the attached patch has a typo > fix. It also has some more improvements. > > > > > Also, see this patch: > > > > https://www.postgresql.org/message-id/6d3fef19-a420-4e11-8235-8ea534bf2080%40eisentraut.org > > > > If this is accepted, it would make the change in the patch here even > > smaller. > > +1. I think we should commit this, rebase SQL/PGQ patches and then > apply this change. Thanks for committing those patches. Here's a patchset rebased on top of these commits. 0001 is the same as earlier 0001, but with a conflict in pg_overexplain.sql/.out resolved. It needs 0002 so that a property graph can be used in the GRAPH_TABLE clause. 0002 is your patch to add parserOpenPropGraph() with the typo and comment fixed as mentioned above. It should be squashed into 0001 in the next patchset. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Wed, Feb 25, 2026 at 12:10 PM Ashutosh Bapat wrote: > > On Thu, Feb 19, 2026 at 3:01 PM Ashutosh Bapat > wrote: > > > > > > I am actually wondering whether the comment in parserOpenPropGraph() > > is required. In case we want to keep it, the attached patch has a typo > > fix. It also has some more improvements. > > > > > > > > Also, see this patch: > > > > > > https://www.postgresql.org/message-id/6d3fef19-a420-4e11-8235-8ea534bf2080%40eisentraut.org > > > > > > If this is accepted, it would make the change in the patch here even > > > smaller. > > > > +1. I think we should commit this, rebase SQL/PGQ patches and then > > apply this change. > > Thanks for committing those patches. Here's a patchset rebased on top > of these commits. > > 0001 is the same as earlier 0001, but with a conflict in > pg_overexplain.sql/.out resolved. It needs 0002 so that a property > graph can be used in the GRAPH_TABLE clause. > 0002 is your patch to add parserOpenPropGraph() with the typo and > comment fixed as mentioned above. It should be squashed into 0001 in > the next patchset. pg_overexplain failed on CI because of new overexplain fields. Here's a patchset fixing the failure by adding those fields to the graph table query in pg_overexplain. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On 25.02.26 09:28, Ashutosh Bapat wrote: >> Thanks for committing those patches. Here's a patchset rebased on top >> of these commits. >> >> 0001 is the same as earlier 0001, but with a conflict in >> pg_overexplain.sql/.out resolved. It needs 0002 so that a property >> graph can be used in the GRAPH_TABLE clause. >> 0002 is your patch to add parserOpenPropGraph() with the typo and >> comment fixed as mentioned above. It should be squashed into 0001 in >> the next patchset. > pg_overexplain failed on CI because of new overexplain fields. Here's > a patchset fixing the failure by adding those fields to the graph > table query in pg_overexplain. Here are some additional patches for fixups and some bug fixes to apply on top. Some additional comments: - In parse_graphtable.c, maybe some of the functions could have more verbose comments, like what is the input structure, what is the output structure, what does it check for. Consider for example transformLabelExpr(). - The structure GraphTableParseState is completely undocumented. Also, I don't think it belongs into nodes/parsenodes.h. Maybe better in parser/parse_node.h, where ParseState is also? - Let's remove the debug elog(INFO) in rewriteGraphTable(). - In some cases in rewriteGraphTable.c(), it's not clear to me whether the elog should be a user-facing ereport, for example in generate_queries_for_path_pattern(). Although if there is an invalid path pattern structure, this should be handled in the parser already? - Also, check the error message style: no initial capital letter, no period, "can not" -> "cannot". - The difference between get_gep_kind_name() and get_graph_elem_kind_name() is unclear and confusing. Should they be the same? Also, for this kind of internal error: elog(ERROR, "unsupported element pattern kind: \"%s\"", get_gep_kind_name(gep->kind)) we should just print the raw gep->kind. (If it's unsupported, chances are that it's not even something that get_gep_kind_name() can translate.)
Re: SQL Property Graph Queries (SQL/PGQ)
On Wed, Feb 25, 2026 at 5:04 PM Peter Eisentraut wrote: > > On 25.02.26 09:28, Ashutosh Bapat wrote: > >> Thanks for committing those patches. Here's a patchset rebased on top > >> of these commits. > >> > >> 0001 is the same as earlier 0001, but with a conflict in > >> pg_overexplain.sql/.out resolved. It needs 0002 so that a property > >> graph can be used in the GRAPH_TABLE clause. > >> 0002 is your patch to add parserOpenPropGraph() with the typo and > >> comment fixed as mentioned above. It should be squashed into 0001 in > >> the next patchset. > > pg_overexplain failed on CI because of new overexplain fields. Here's > > a patchset fixing the failure by adding those fields to the graph > > table query in pg_overexplain. > > Here are some additional patches for fixups and some bug fixes to apply > on top. > They all LGTM. Squashed into attached 0001 along with 0002 in the earlier patchset. > Some additional comments: > > - In parse_graphtable.c, maybe some of the functions could have more > verbose comments, like what is the input structure, what is the output > structure, what does it check for. Consider for example > transformLabelExpr(). Done. I don't think we need prologue for transformPathTerm, transformPathPatternList, which just walk through the lists. But let me know if you feel otherwise. The changes are included as 0002 in the attached patchset. > > - The structure GraphTableParseState is completely undocumented. Also, > I don't think it belongs into nodes/parsenodes.h. Maybe better in > parser/parse_node.h, where ParseState is also? Done. in 0003. > > - Let's remove the debug elog(INFO) in rewriteGraphTable(). Done. Yay! > > - In some cases in rewriteGraphTable.c(), it's not clear to me whether > the elog should be a user-facing ereport, for example in > generate_queries_for_path_pattern(). Although if there is an invalid > path pattern structure, this should be handled in the parser already? Converted user facing elogs to erepots. Some of the elogs and ereports can be moved to the corresponding transform* functions in parse_graphtable.c. rewriteGraphTable.c now has Asserts in those places to document the conditions assumed to be true by that code. There are still some elogs left for failed catalog lookups and also for invalid conditions which better be documented as elogs rather than Asserts. > > - Also, check the error message style: no initial capital letter, no > period, "can not" -> "cannot". Fixed. > > - The difference between get_gep_kind_name() and > get_graph_elem_kind_name() is unclear and confusing. Should they be the > same? > They are different - get_gep_kind_name() deals with the graph element pattern kinds like vertex, and left/right/any edges, nested path patterns etc. get_graph_elem_kind_name() deals with types of property graph elements i.e. vertex and edge. I have replaced the second function with a ternary operator. > Also, for this kind of internal error: > > elog(ERROR, "unsupported element pattern kind: \"%s\"", > get_gep_kind_name(gep->kind)) > > we should just print the raw gep->kind. (If it's unsupported, chances > are that it's not even something that get_gep_kind_name() can translate.) gram.y sets gep->kind to GraphElementPatternKind enum values. Reporting these internal values won't make sense to a user. They will need the name of the kind. Right now it is used to report "nested path pattern" which accepted in gram.y but is not supported. In future we may grow the names of kinds supported in grammar but not implemented or use grow places where certain kinds are accepted but not others. In case a catalog corruption puts an invalid value for gep->kind in a cataloged expression/query, I think reporting "unknown" would be sufficient as done in the patch. All changes to rewriteGraphTable.c are in 0004. Will squash 0002-0004 into 0001 once you have reviewed those patches. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On 26.02.26 12:06, Ashutosh Bapat wrote: > All changes to rewriteGraphTable.c are in 0004. > > Will squash 0002-0004 into 0001 once you have reviewed those patches. Ok, these all look good to me. Except, this error message change -ERROR: property "ename" of element variable "src" not found +ERROR: none of the property graph elements associated with variable "src" have property with name "ename" defined I don't know, that seems quite a complicated message for such a simple mistake. Also, properties are associated with labels, not with graph elements, so this seems misleading.
Re: SQL Property Graph Queries (SQL/PGQ)
On Fri, Feb 27, 2026 at 1:14 PM Peter Eisentraut wrote: > > On 26.02.26 12:06, Ashutosh Bapat wrote: > > All changes to rewriteGraphTable.c are in 0004. > > > > Will squash 0002-0004 into 0001 once you have reviewed those patches. > > Ok, these all look good to me. > > Except, this error message change > > -ERROR: property "ename" of element variable "src" not found > +ERROR: none of the property graph elements associated with variable > "src" have property with name "ename" defined > > I don't know, that seems quite a complicated message for such a simple > mistake. Also, properties are associated with labels, not with graph > elements, so this seems misleading. > Hmm, mentioning labels was getting even more complicated, so I had to drop it. How about the earlier version with "of" replaced with "for"? "property "ename" for element variable "src" not found. The users can lookup the labels associated with variable src and figure out what went wrong themselves? I want to avoid simplistic error that other products give like "property "ename" not found" since it does not clarify whether the property is absent in the property graph or is not associated with labels in the pattern. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Fri, Feb 27, 2026 at 2:14 PM Ashutosh Bapat wrote: > > > > Except, this error message change > > > > -ERROR: property "ename" of element variable "src" not found > > +ERROR: none of the property graph elements associated with variable > > "src" have property with name "ename" defined > > > > I don't know, that seems quite a complicated message for such a simple > > mistake. Also, properties are associated with labels, not with graph > > elements, so this seems misleading. > > > > Hmm, mentioning labels was getting even more complicated, so I had to drop it. > > How about the earlier version with "of" replaced with "for"? "property > "ename" for element variable "src" not found. The users can lookup the > labels associated with variable src and figure out what went wrong > themselves? I want to avoid simplistic error that other products give > like "property "ename" not found" since it does not clarify whether > the property is absent in the property graph or is not associated with > labels in the pattern. Here's a patchset with all the earlier patches squashed into 0001. 0002 is changing this specific error message as described in the para above. Please let me know if you have any other suggestions. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Minor issue: src/interfaces/ecpg/test/sql/.gitignore is missing entries
for the sqlpgq test. After running the ECPG tests, the build artifacts
(sqlpgq binary and sqlpgq.c) show up as untracked files in git status.
The fix is to add these two lines (alphabetically between sqljson_jsontable
and twophase):
/sqlpgq
/sqlpgq.c
Best Regards,
Henson
Re: SQL Property Graph Queries (SQL/PGQ)
On Fri, Mar 6, 2026 at 1:31 PM Henson Choi wrote: > > Hi, Ashutosh > > Minor issue: src/interfaces/ecpg/test/sql/.gitignore is missing entries > for the sqlpgq test. After running the ECPG tests, the build artifacts > (sqlpgq binary and sqlpgq.c) show up as untracked files in git status. > > The fix is to add these two lines (alphabetically between sqljson_jsontable > and twophase): > > /sqlpgq > /sqlpgq.c Thanks. Good catch. Added as 0003 in the previous patchset. Can you please check if it works for you. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
I adapted the PGQ regression test cases to run on Oracle and
cross-verified the results to assess behavioral compatibility. Below
is a summary of the methodology, key differences found, and overall
assessment.
1. KEY DIFFERENCES
------------------
1.1 Supported by PG, not Oracle
ALTER PROPERTY GRAPH
Oracle rejects ALTER PROPERTY GRAPH syntax entirely (ORA-03048).
Modifying a graph requires DROP and recreate. PG supports ADD/DROP
VERTEX/EDGE TABLES, ALTER, RENAME TO, and SET SCHEMA in-place.
NODE TABLES / RELATIONSHIP TABLES synonyms
SQL/PGQ standard defines NODE/RELATIONSHIP as synonyms for
VERTEX/EDGE. Oracle accepts only VERTEX/EDGE (ORA-02000). PG
supports both.
TEMPORARY PROPERTY GRAPH
Oracle does not support temporary property graphs (ORA-00901).
PG supports them; the graph is dropped automatically at session end.
LATERAL + GRAPH_TABLE
Oracle disallows referencing outer variables inside a GRAPH_TABLE
WHERE clause (ORA-40996). PG supports LATERAL + GRAPH_TABLE directly.
1.2 Syntax difference -- Oracle workaround available
GRAPH_TABLE inside UDFs
Oracle's PL/SQL compiler cannot statically parse GRAPH_TABLE
(ORA-49028). EXECUTE IMMEDIATE (dynamic SQL) works as a workaround
and supports SYS_REFCURSOR and pipelined functions. PG supports both
static and dynamic usage. Note: the Oracle workaround carries a
performance cost -- no compile-time optimization, and per-row FETCH
overhead with pipelined functions.
1.3 Supported by Oracle, not PG
a.* star reference in COLUMNS
Oracle allows COLUMNS (a.*) to return all properties of an element
variable across all its labels. PG rejects this ("*" not allowed
here). A workaround exists: list properties explicitly. This is the
only SQL/PGQ query execution capability where Oracle is ahead of the
current PG implementation.
ALTER PROPERTY GRAPH COMPILE (item 1.18)
Oracle provides a COMPILE clause to recover from false invalidation
caused by its coarse-grained dependency tracking. PG does not have
this -- nor does it need it. PG uses strict dependency management,
so false invalidation does not occur.
1.4 Semantic difference
Label sharing policy
Oracle rejects defining the same label on more than one vertex/edge
table (ORA-42409 "label already defined"). Labels are bound to
exactly one table. PG allows label sharing across tables as long as
the property definitions (name, type, count) are consistent. PG's
approach is more flexible.
1.5 Design philosophy difference
Dependency management
Oracle allows DROP TABLE on a table referenced by a graph, and DROP
PROPERTY GRAPH on a graph that views depend on. Dependents are left
invalid and fail at next access (lazy validation). PG rejects the
DROP if dependents exist; CASCADE must be explicit. This is not
PGQ-specific -- PG follows the SQL standard (DROP ... CASCADE |
RESTRICT), while Oracle uses lazy invalidation.
3. ASSESSMENT
-------------
Within the tested scope, results matched Oracle except where noted
above. The only Oracle capabilities not present in PG are a.* in
COLUMNS (workaround: explicit property listing) and ALTER PROPERTY
GRAPH COMPILE (unnecessary in PG due to strict dependency management).
On the DDL side, PG is actually more complete than Oracle: ALTER
PROPERTY GRAPH, DROP PROPERTY GRAPH CASCADE, standard synonyms
(NODE/RELATIONSHIP), and TEMPORARY PROPERTY GRAPH are all supported
in PG but not in Oracle.
On the query side, all tested GRAPH_TABLE queries -- pattern matching,
WHERE clauses, SQL integration -- produced identical results. However,
the full SQL/PGQ specification goes well beyond the tested scope:
quantified path patterns, shortest path, graph types, ACYCLIC/SIMPLE
path constraints are not yet implemented. Oracle has broader query
coverage overall.
Regards,
Henson
Re: SQL Property Graph Queries (SQL/PGQ)
On Sun, Mar 8, 2026 at 12:52 AM Henson Choi wrote:
>
> Hi Ashutosh,
>
> I adapted the PGQ regression test cases to run on Oracle and
> cross-verified the results to assess behavioral compatibility. Below
> is a summary of the methodology, key differences found, and overall
> assessment.
>
>
> 1. KEY DIFFERENCES
> ------------------
>
> 1.1 Supported by PG, not Oracle
>
> ALTER PROPERTY GRAPH
> Oracle rejects ALTER PROPERTY GRAPH syntax entirely (ORA-03048).
> Modifying a graph requires DROP and recreate. PG supports ADD/DROP
> VERTEX/EDGE TABLES, ALTER, RENAME TO, and SET SCHEMA in-place.
>
> NODE TABLES / RELATIONSHIP TABLES synonyms
> SQL/PGQ standard defines NODE/RELATIONSHIP as synonyms for
> VERTEX/EDGE. Oracle accepts only VERTEX/EDGE (ORA-02000). PG
> supports both.
>
> TEMPORARY PROPERTY GRAPH
> Oracle does not support temporary property graphs (ORA-00901).
> PG supports them; the graph is dropped automatically at session end.
>
> LATERAL + GRAPH_TABLE
> Oracle disallows referencing outer variables inside a GRAPH_TABLE
> WHERE clause (ORA-40996). PG supports LATERAL + GRAPH_TABLE directly.
>
>
> 1.2 Syntax difference -- Oracle workaround available
>
> GRAPH_TABLE inside UDFs
> Oracle's PL/SQL compiler cannot statically parse GRAPH_TABLE
> (ORA-49028). EXECUTE IMMEDIATE (dynamic SQL) works as a workaround
> and supports SYS_REFCURSOR and pipelined functions. PG supports both
> static and dynamic usage. Note: the Oracle workaround carries a
> performance cost -- no compile-time optimization, and per-row FETCH
> overhead with pipelined functions.
>
>
> 1.3 Supported by Oracle, not PG
>
> a.* star reference in COLUMNS
> Oracle allows COLUMNS (a.*) to return all properties of an element
> variable across all its labels. PG rejects this ("*" not allowed
> here). A workaround exists: list properties explicitly. This is the
> only SQL/PGQ query execution capability where Oracle is ahead of the
> current PG implementation.
PGQ doesn’t seem to reject a.*. I think PostgreSQL is still at an early stage
of supporting SQL/PGQ, so missing features like this are acceptable for
now, and we can add support for more syntax in the future.
Here is a snippet from SQL/PGQ standard:
::=
COLUMNS
[ { }... ]
::=
[ AS ]
|
::=
>
> ALTER PROPERTY GRAPH COMPILE (item 1.18)
> Oracle provides a COMPILE clause to recover from false invalidation
> caused by its coarse-grained dependency tracking. PG does not have
> this -- nor does it need it. PG uses strict dependency management,
> so false invalidation does not occur.
>
>
> 1.4 Semantic difference
>
> Label sharing policy
> Oracle rejects defining the same label on more than one vertex/edge
> table (ORA-42409 "label already defined"). Labels are bound to
> exactly one table. PG allows label sharing across tables as long as
> the property definitions (name, type, count) are consistent. PG's
> approach is more flexible.
>
>
> 1.5 Design philosophy difference
>
> Dependency management
> Oracle allows DROP TABLE on a table referenced by a graph, and DROP
> PROPERTY GRAPH on a graph that views depend on. Dependents are left
> invalid and fail at next access (lazy validation). PG rejects the
> DROP if dependents exist; CASCADE must be explicit. This is not
> PGQ-specific -- PG follows the SQL standard (DROP ... CASCADE |
> RESTRICT), while Oracle uses lazy invalidation.
>
>
> 3. ASSESSMENT
> -------------
>
> Within the tested scope, results matched Oracle except where noted
> above. The only Oracle capabilities not present in PG are a.* in
> COLUMNS (workaround: explicit property listing) and ALTER PROPERTY
> GRAPH COMPILE (unnecessary in PG due to strict dependency management).
>
> On the DDL side, PG is actually more complete than Oracle: ALTER
> PROPERTY GRAPH, DROP PROPERTY GRAPH CASCADE, standard synonyms
> (NODE/RELATIONSHIP), and TEMPORARY PROPERTY GRAPH are all supported
> in PG but not in Oracle.
>
> On the query side, all tested GRAPH_TABLE queries -- pattern matching,
> WHERE clauses, SQL integration -- produced identical results. However,
> the full SQL/PGQ specification goes well beyond the tested scope:
> quantified path patterns, shortest path, graph types, ACYCLIC/SIMPLE
> path constraints are not yet implemented. Oracle has broader query
> coverage overall.
>
> Regards,
> Henson
--
Regards
Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
> 1.3 Supported by Oracle, not PG
>
> a.* star reference in COLUMNS
> Oracle allows COLUMNS (a.*) to return all properties of an element
> variable across all its labels. PG rejects this ("*" not allowed
> here). A workaround exists: list properties explicitly. This is the
> only SQL/PGQ query execution capability where Oracle is ahead of the
> current PG implementation.
PGQ doesn’t seem to reject a.*. I think PostgreSQL is still at an early stage
of supporting SQL/PGQ, so missing features like this are acceptable for
now, and we can add support for more syntax in the future.
Re: SQL Property Graph Queries (SQL/PGQ)
My previous message was held for moderation because of the total size
of the patches. Resending again with a zipped file.
On Sat, Mar 7, 2026 at 10:22 PM Henson Choi wrote:
>
> Hi Ashutosh,
>
> I adapted the PGQ regression test cases to run on Oracle and
> cross-verified the results to assess behavioral compatibility. Below
> is a summary of the methodology, key differences found, and overall
> assessment.
>
Thanks for doing this exercise.
>
> 1. KEY DIFFERENCES
> ------------------
>
> 1.1 Supported by PG, not Oracle
>
> ALTER PROPERTY GRAPH
> Oracle rejects ALTER PROPERTY GRAPH syntax entirely (ORA-03048).
> Modifying a graph requires DROP and recreate. PG supports ADD/DROP
> VERTEX/EDGE TABLES, ALTER, RENAME TO, and SET SCHEMA in-place.
Right. Thanks to pg_dump, we have that advantage.
>
> NODE TABLES / RELATIONSHIP TABLES synonyms
> SQL/PGQ standard defines NODE/RELATIONSHIP as synonyms for
> VERTEX/EDGE. Oracle accepts only VERTEX/EDGE (ORA-02000). PG
> supports both.
>
+1.
> TEMPORARY PROPERTY GRAPH
> Oracle does not support temporary property graphs (ORA-00901).
> PG supports them; the graph is dropped automatically at session end.
>
check. I think this will have its use cases. At least something
related to temporary object mgmt (vs GTT for example) that they don't
have. :)
> LATERAL + GRAPH_TABLE
> Oracle disallows referencing outer variables inside a GRAPH_TABLE
> WHERE clause (ORA-40996). PG supports LATERAL + GRAPH_TABLE directly.
>
check.
>
> 1.2 Syntax difference -- Oracle workaround available
>
> GRAPH_TABLE inside UDFs
> Oracle's PL/SQL compiler cannot statically parse GRAPH_TABLE
> (ORA-49028). EXECUTE IMMEDIATE (dynamic SQL) works as a workaround
> and supports SYS_REFCURSOR and pipelined functions. PG supports both
> static and dynamic usage. Note: the Oracle workaround carries a
> performance cost -- no compile-time optimization, and per-row FETCH
> overhead with pipelined functions.
>
check.
>
> 1.3 Supported by Oracle, not PG
>
> a.* star reference in COLUMNS
> Oracle allows COLUMNS (a.*) to return all properties of an element
> variable across all its labels. PG rejects this ("*" not allowed
> here). A workaround exists: list properties explicitly. This is the
> only SQL/PGQ query execution capability where Oracle is ahead of the
> current PG implementation.
Thanks for bringing this to my notice. I spent some time on it, and I
have a patch which supports this. Please read more at the end of this
email.
>
> ALTER PROPERTY GRAPH COMPILE (item 1.18)
> Oracle provides a COMPILE clause to recover from false invalidation
> caused by its coarse-grained dependency tracking. PG does not have
> this -- nor does it need it. PG uses strict dependency management,
> so false invalidation does not occur.
>
check
>
> 1.4 Semantic difference
>
> Label sharing policy
> Oracle rejects defining the same label on more than one vertex/edge
> table (ORA-42409 "label already defined"). Labels are bound to
> exactly one table. PG allows label sharing across tables as long as
> the property definitions (name, type, count) are consistent. PG's
> approach is more flexible.
>
It's as per the standard. Standard allows sharing labels across tables.
>
> 1.5 Design philosophy difference
>
> Dependency management
> Oracle allows DROP TABLE on a table referenced by a graph, and DROP
> PROPERTY GRAPH on a graph that views depend on. Dependents are left
> invalid and fail at next access (lazy validation). PG rejects the
> DROP if dependents exist; CASCADE must be explicit. This is not
> PGQ-specific -- PG follows the SQL standard (DROP ... CASCADE |
> RESTRICT), while Oracle uses lazy invalidation.
>
Right. That's the architectural difference between the two.
>
> 3. ASSESSMENT
> -------------
>
> Within the tested scope, results matched Oracle except where noted
> above. The only Oracle capabilities not present in PG are a.* in
> COLUMNS (workaround: explicit property listing) and ALTER PROPERTY
> GRAPH COMPILE (unnecessary in PG due to strict dependency management).
>
> On the DDL side, PG is actually more complete than Oracle: ALTER
> PROPERTY GRAPH, DROP PROPERTY GRAPH CASCADE, standard synonyms
> (NODE/RELATIONSHIP), and TEMPORARY PROPERTY GRAPH are all supported
> in PG but not in Oracle.
>
> On the query side, all tested GRAPH_TABLE queries -- pattern matching,
> WHERE clauses, SQL integration -- produced identical results. However,
> the full SQL/PGQ specification goes well beyond the tested scope:
> quantified path patterns, shortest path, graph types, ACYCLIC/SIMPLE
> path constraints are not yet implemented. Oracle has broader query
> coverage overall.
Thanks for the summary.
There are two new patches 0004 and 0005 in the attached patchset.
Below is a description of those.
All property reference and refactoring
--------------------------------------------------
According to the SQL/PGQ standard, all properties reference
.* is allowed in COLUMNs, but it's not allowed anywhere else
e.g. in WHERE clause or buried inside a value expression. The current
error message is misleading in saying ""*" not allowed here". Instead
it should say "not supported" in COLUMNs and "not allowed" in other
places. Patch 0004 is the patch fixing the error message. It is not
accurate since it only checks whether .* appears in COLUMNs
clause or not. It doesn't differentiate between it appearing directly
in COLUMNs vs buried in another value expression. But I think it
serves the purpose for now. It's a limitation that we will eventually
remove. So it may be ok.
I attempted to support it and turned out to be relatively simple. So
we can support it in the first version itself. However, the patch is
much larger. In order to expand all properties reference, we need to
find all the properties associated with the set of labels which
results from evaluating label expression. The properties are not
directly associated with a label, but through an element. Hence we
need to find at least one element associated with each label in the set.
Further the set of labels that an empty label expression results into
is all the labels which have at least one element of a given element
kind in the property graph. That's another reason why we want to find
at least one element associated with each of the labels. If we are
looking up element label catalog, why not to fetch all the elements
during transformation itself rather than waiting all the way till
the rewriting phase. So I changed the code to do that. And I think the
resultant code is much simpler, moves the error handling to
appropriate places and simplifies a lot of the rewriteGraphTable.c
code. Flip side is transform* functions are heavier, however in the
end it's code simplification. Since we are expanding the empty label
expression during transformation phase itself, we replace empty label
expression with a disjunction. But we need to know whether the
original label expression was empty or not in the ruleutils and when
consolidating path elements (generate_queries_for_path_pattern()). The
later usage will vanish once we support label disjunction. So I
introduced a flag to retain that status. All that refactoring is patch
0005.
Peter, if you think 0005 is larger to be acceptable at this stage, we
could revisit it later as well.
In order to apply 0005, 0004 is needed even though 0005 nullifies that
change. I have separated 0004, so that those changes can be committed
even if we decide to postpone 0005.
--
Best Wishes,
Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Thank you for the detailed response and the two new patches. I'm
glad the cross-verification exercise was useful.
My previous message was held for moderation because of the total size
of the patches. Resending again with a zipped file.
patches have been hitting the size filter since late February --
it's a sign that you're working on one of the biggest features
for PostgreSQL.
Wear it as a badge of honor. :)
By the way, the email itself is delivered to subscribers regardless
of moderation -- only the mailing list archive and cfbot processing
are delayed. So I don't think you need to resend.
Best regards,
Henson
Re: SQL Property Graph Queries (SQL/PGQ)
On Wed, Mar 11, 2026 at 1:04 PM Ashutosh Bapat wrote: > > There are two new patches 0004 and 0005 in the attached patchset. > Below is a description of those. > > All property reference and refactoring > -------------------------------------------------- > According to the SQL/PGQ standard, all properties reference > .* is allowed in COLUMNs, but it's not allowed anywhere else > e.g. in WHERE clause or buried inside a value expression. The current > error message is misleading in saying ""*" not allowed here". Instead > it should say "not supported" in COLUMNs and "not allowed" in other > places. Patch 0004 is the patch fixing the error message. It is not > accurate since it only checks whether .* appears in COLUMNs > clause or not. It doesn't differentiate between it appearing directly > in COLUMNs vs buried in another value expression. But I think it > serves the purpose for now. It's a limitation that we will eventually > remove. So it may be ok. > > I attempted to support it and turned out to be relatively simple. So > we can support it in the first version itself. However, the patch is > much larger. In order to expand all properties reference, we need to > find all the properties associated with the set of labels which > results from evaluating label expression. The properties are not > directly associated with a label, but through an element. Hence we > need to find at least one element associated with each label in the set. > Further the set of labels that an empty label expression results into > is all the labels which have at least one element of a given element > kind in the property graph. That's another reason why we want to find > at least one element associated with each of the labels. If we are > looking up element label catalog, why not to fetch all the elements > during transformation itself rather than waiting all the way till > the rewriting phase. So I changed the code to do that. And I think the > resultant code is much simpler, moves the error handling to > appropriate places and simplifies a lot of the rewriteGraphTable.c > code. Flip side is transform* functions are heavier, however in the > end it's code simplification. Since we are expanding the empty label > expression during transformation phase itself, we replace empty label > expression with a disjunction. But we need to know whether the > original label expression was empty or not in the ruleutils and when > consolidating path elements (generate_queries_for_path_pattern()). The > later usage will vanish once we support label disjunction. So I > introduced a flag to retain that status. All that refactoring is patch > 0005. > > Peter, if you think 0005 is larger to be acceptable at this stage, we > could revisit it later as well. > > In order to apply 0005, 0004 is needed even though 0005 nullifies that > change. I have separated 0004, so that those changes can be committed > even if we decide to postpone 0005. > I have missed adding pg_node_attr(equal_ignore, query_jumble_ignore) to the three new fields in GraphLabelRef, since the equality of other fields is enough and those three fields don't need to be part of query jumbling. If a node with those fields populated is written ignoring those fields, what would resurrect those fields when read back? I don't think there is anything that would do it. So didn't add read_write_ignore. But I am not sure. List *properties pg_node_attr(equal_ignore, query_jumble_ignore); List *elements pg_node_attr(equal_ignore, query_jumble_ignore); List *elem_labels pg_node_attr(equal_ignore, query_jumble_ignore); -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On 11.03.26 08:34, Ashutosh Bapat wrote: > There are two new patches 0004 and 0005 in the attached patchset. I have committed this, including the 0004 patch. Let's consider the 0005 patch separately. The buildfarm shows some instability in the pg_upgrade test, because labels are printed by pg_get_propgraphdef() in implementation-dependent order. Attached is a quick patch to sort the labels before printing. Check please.
Re: SQL Property Graph Queries (SQL/PGQ)
On Mon, 16 Mar 2026 at 17:43, Peter Eisentraut wrote: > > On 11.03.26 08:34, Ashutosh Bapat wrote: > > There are two new patches 0004 and 0005 in the attached patchset. > > I have committed this, including the 0004 patch. Let's consider the > 0005 patch separately. > > The buildfarm shows some instability in the pg_upgrade test, because > labels are printed by pg_get_propgraphdef() in implementation-dependent > order. Attached is a quick patch to sort the labels before printing. > Check please. Hi! Do we need to keep relation lock until end of function (table_close(pglrel, AccessShareLock);)? I'm not sure if list_sort is interruptible. -- Best regards, Kirill Reshke
Re: SQL Property Graph Queries (SQL/PGQ)
Hi, The commit 2f094e7ac691abc9d2fe0f4dcf0feac4a6ce1d9c delivers an excellent feature, and the file `rewriteGraphTable.c` was introduced as part of this commit. I've noticed that this code file could benefit from some tidying up, so please review the diff file attached below. This diff only includes **basic cleanup** of `rewriteGraphTable.c` – it’s just a simple pass, and there may be other minor omissions that haven’t been addressed yet. -- regards, Man Zeng
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Peter, > On Mon, 16 Mar 2026 at 17:43, Peter Eisentraut wrote: > > > > On 11.03.26 08:34, Ashutosh Bapat wrote: > > > There are two new patches 0004 and 0005 in the attached patchset. > > > > I have committed this, including the 0004 patch. Thanks a lot. > > Let's consider the > > 0005 patch separately. Will share the rebased patch soon. This thread may see discussion about the commit itself. Should I start a new thread for 0005 or use this one? New one seems better to me with a new CF entry. > > > > The buildfarm shows some instability in the pg_upgrade test, because > > labels are printed by pg_get_propgraphdef() in implementation-dependent > > order. Attached is a quick patch to sort the labels before printing. > > Check please. The patch looks fine to me. While reviewing it, I noticed that the function has an extra loop to count the number of variables. I don't think it's needed. The count can be obtained from the list length. In the attached patch, I have removed that loop. Am I missing something? 0001 is your patch 0002 removes the loop + some cosmetic changes Hi Kirill, > Do we need to keep relation lock until end of function > (table_close(pglrel, AccessShareLock);)? I think you are right. Fixed in the attached. > I'm not sure if list_sort is > interruptible. I don't think it matters here. It will be very rare, if not impossible, to have so many labels as to let the sorting run for milliseconds together. The foreach loop afterwards is also not interruptible. Any reason you think it should be interruptible? -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Mon, Mar 16, 2026 at 8:39 PM zengman wrote: > > Hi, > > The commit 2f094e7ac691abc9d2fe0f4dcf0feac4a6ce1d9c delivers an excellent feature, and the file `rewriteGraphTable.c` was introduced as part of this commit. > I've noticed that this code file could benefit from some tidying up, so please review the diff file attached below. > This diff only includes **basic cleanup** of `rewriteGraphTable.c` – it’s just a simple pass, > and there may be other minor omissions that haven’t been addressed yet. Hi Man, Thanks for the patch. I reviewed the cleanup you propose. Most of the changes look good to me, except the changes related to pstate. We have both patterns in the code, one which uses free_parsestate() explicitly and another that doesn't. In this case, we don't set p_target_relation, and we don't touch p_next_resno. So the only thing that free_parsestate() does it to free pstate, which will taken care of by the memory context management. So not needed. Any other reason you want to call free_parsestate() explicitly? Attached patch has changes other that pstate related changes. I think, Peter may want to collect more such changes before applying them. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
> > Hi, > > > > The commit 2f094e7ac691abc9d2fe0f4dcf0feac4a6ce1d9c delivers an excellent feature, and the file `rewriteGraphTable.c` was > introduced as part of this commit. > > I've noticed that this code file could benefit from some tidying up, so please review the diff file attached below. > > This diff only includes **basic cleanup** of `rewriteGraphTable.c` – it’s just a simple pass, > > and there may be other minor omissions that haven’t been addressed yet. > > Hi Man, > Thanks for the patch. I reviewed the cleanup you propose. Most of the > changes look good to me, except the changes related to pstate. We have > both patterns in the code, one which uses free_parsestate() explicitly > and another that doesn't. In this case, we don't set > p_target_relation, and we don't touch p_next_resno. So the only thing > that free_parsestate() does it to free pstate, which will taken care > of by the memory context management. So not needed. Any other reason > you want to call free_parsestate() explicitly? > > Attached patch has changes other that pstate related changes. > > I think, Peter may want to collect more such changes before applying them. Hi, Thank you for your review. I understand your feedback – this was a result of my personal coding habit: I prefer to explicitly call `free_parsestate()`, and also want to respect the comment associated with `make_parsestate()` (shown below): ``` /* * make_parsestate * Allocate and initialize a new ParseState. * * Caller should eventually release the ParseState via free_parsestate(). */ ``` For this reason, I have made minor modifications to this section of the code. -- regards, Man Zeng
Re: SQL Property Graph Queries (SQL/PGQ)
On Tue, Mar 17, 2026 at 6:56 AM zengman wrote: > > > > Hi, > > > > > > The commit 2f094e7ac691abc9d2fe0f4dcf0feac4a6ce1d9c delivers an excellent feature, and the file `rewriteGraphTable.c` was > introduced as part of this commit. > > > I've noticed that this code file could benefit from some tidying up, so please review the diff file attached below. > > > This diff only includes **basic cleanup** of `rewriteGraphTable.c` – it’s just a simple pass, > > > and there may be other minor omissions that haven’t been addressed yet. > > > > Hi Man, > > Thanks for the patch. I reviewed the cleanup you propose. Most of the > > changes look good to me, except the changes related to pstate. We have > > both patterns in the code, one which uses free_parsestate() explicitly > > and another that doesn't. In this case, we don't set > > p_target_relation, and we don't touch p_next_resno. So the only thing > > that free_parsestate() does it to free pstate, which will taken care > > of by the memory context management. So not needed. Any other reason > > you want to call free_parsestate() explicitly? > > > > Attached patch has changes other that pstate related changes. > > > > I think, Peter may want to collect more such changes before applying them. > > Hi, > > Thank you for your review. I understand your feedback – this was a result of my personal coding habit: I prefer to explicitly call `free_parsestate()`, and also want to respect the comment associated with `make_parsestate()` (shown below): > ``` As Robert Haas explained in a nearby thread, we usually don't accept patches that modify code for personal preferences. We instead follow precedence. Also the email proposing the patches should explain why those changes are being proposed, especially when they are more than trivial changes. > /* > * make_parsestate > * Allocate and initialize a new ParseState. > * > * Caller should eventually release the ParseState via free_parsestate(). > */ > ``` > For this reason, I have made minor modifications to this section of the code. > Given that we have many other callers who do not call free_parsestate(), probably this should change, as a separate patch though. Maybe there is a pattern of when to call free_parsestate() and when not to. It will be good to add a clarifying comment here. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
> > Hi, > > > > Thank you for your review. I understand your feedback – this was a result of my personal coding habit: I prefer to > explicitly call `free_parsestate()`, and also want to respect the comment associated with `make_parsestate()` (shown below): > > ``` > > As Robert Haas explained in a nearby thread, we usually don't accept > patches that modify code for personal preferences. We instead follow > precedence. Also the email proposing the patches should explain why > those changes are being proposed, especially when they are more than > trivial changes. > I understand, thank you very much for your guidance. > > /* > > * make_parsestate > > * Allocate and initialize a new ParseState. > > * > > * Caller should eventually release the ParseState via free_parsestate(). > > */ > > ``` > > For this reason, I have made minor modifications to this section of the code. > > > > Given that we have many other callers who do not call > free_parsestate(), probably this should change, as a separate patch > though. Maybe there is a pattern of when to call free_parsestate() and > when not to. It will be good to add a clarifying comment here. Yes, I completely agree with your suggestion. -- regards, Man Zeng
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Ashutosh, On Mon, Mar 16, 2026 at 11:55 PM Ashutosh Bapat wrote: > > Hi Peter, > > > On Mon, 16 Mar 2026 at 17:43, Peter Eisentraut wrote: > > > > > > On 11.03.26 08:34, Ashutosh Bapat wrote: > > > > There are two new patches 0004 and 0005 in the attached patchset. > > > > > > I have committed this, including the 0004 patch. > > Thanks a lot. > > > > Let's consider the > > > 0005 patch separately. > > Will share the rebased patch soon. This thread may see discussion > about the commit itself. Should I start a new thread for 0005 or use > this one? New one seems better to me with a new CF entry. > > > > > > > The buildfarm shows some instability in the pg_upgrade test, because > > > labels are printed by pg_get_propgraphdef() in implementation-dependent > > > order. Attached is a quick patch to sort the labels before printing. > > > Check please. > > The patch looks fine to me. While reviewing it, I noticed that the > function has an extra loop to count the number of variables. I don't > think it's needed. The count can be obtained from the list length. In > the attached patch, I have removed that loop. Am I missing something? > > 0001 is your patch > 0002 removes the loop + some cosmetic changes > > Hi Kirill, > > > Do we need to keep relation lock until end of function > > (table_close(pglrel, AccessShareLock);)? > > I think you are right. Fixed in the attached. > > > I'm not sure if list_sort is > > interruptible. > > I don't think it matters here. It will be very rare, if not > impossible, to have so many labels as to let the sorting run for > milliseconds together. The foreach loop afterwards is also not > interruptible. Any reason you think it should be interruptible? > > -- > Best Wishes, > Ashutosh Bapat Do you think it's necessary to add a list_free_deep(label_list) at the end? make_propgraphdef_labels itself it not on critical path so explicit free non-used memory doesn't impact performance. -- Regards Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
On Tue, Mar 17, 2026 at 10:08 AM Junwang Zhao wrote: > > Hi Ashutosh, > > On Mon, Mar 16, 2026 at 11:55 PM Ashutosh Bapat > wrote: > > > > Hi Peter, > > > > > On Mon, 16 Mar 2026 at 17:43, Peter Eisentraut wrote: > > > > > > > > On 11.03.26 08:34, Ashutosh Bapat wrote: > > > > > There are two new patches 0004 and 0005 in the attached patchset. > > > > > > > > I have committed this, including the 0004 patch. > > > > Thanks a lot. > > > > > > Let's consider the > > > > 0005 patch separately. > > > > Will share the rebased patch soon. This thread may see discussion > > about the commit itself. Should I start a new thread for 0005 or use > > this one? New one seems better to me with a new CF entry. > > > > > > > > > > The buildfarm shows some instability in the pg_upgrade test, because > > > > labels are printed by pg_get_propgraphdef() in implementation-dependent > > > > order. Attached is a quick patch to sort the labels before printing. > > > > Check please. > > > > The patch looks fine to me. While reviewing it, I noticed that the > > function has an extra loop to count the number of variables. I don't > > think it's needed. The count can be obtained from the list length. In > > the attached patch, I have removed that loop. Am I missing something? > > > > 0001 is your patch > > 0002 removes the loop + some cosmetic changes > > > > Hi Kirill, > > > > > Do we need to keep relation lock until end of function > > > (table_close(pglrel, AccessShareLock);)? > > > > I think you are right. Fixed in the attached. > > > > > I'm not sure if list_sort is > > > interruptible. > > > > I don't think it matters here. It will be very rare, if not > > impossible, to have so many labels as to let the sorting run for > > milliseconds together. The foreach loop afterwards is also not > > interruptible. Any reason you think it should be interruptible? > > > > -- > > Best Wishes, > > Ashutosh Bapat > > Do you think it's necessary to add a list_free_deep(label_list) at > the end? make_propgraphdef_labels itself it not on critical path > so explicit free non-used memory doesn't impact performance. > It's not that the list or the labels will be too long to consume a lot of memory. If that would have been the case, calling list_free_deep() makes sense. But in this case, the memory will get freed when the immediate memory context gets freed; in worst case that will be when the statement finishes. I don't think it's worth the distraction and the possible minimal risk it carries. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Tue, Mar 17, 2026 at 12:57 PM Ashutosh Bapat wrote: > > On Tue, Mar 17, 2026 at 10:08 AM Junwang Zhao wrote: > > > > Hi Ashutosh, > > > > On Mon, Mar 16, 2026 at 11:55 PM Ashutosh Bapat > > wrote: > > > > > > Hi Peter, > > > > > > > On Mon, 16 Mar 2026 at 17:43, Peter Eisentraut wrote: > > > > > > > > > > On 11.03.26 08:34, Ashutosh Bapat wrote: > > > > > > There are two new patches 0004 and 0005 in the attached patchset. > > > > > > > > > > I have committed this, including the 0004 patch. > > > > > > Thanks a lot. > > > > > > > > Let's consider the > > > > > 0005 patch separately. > > > > > > Will share the rebased patch soon. This thread may see discussion > > > about the commit itself. Should I start a new thread for 0005 or use > > > this one? New one seems better to me with a new CF entry. > > > > > > > > > > > > > The buildfarm shows some instability in the pg_upgrade test, because > > > > > labels are printed by pg_get_propgraphdef() in implementation-dependent > > > > > order. Attached is a quick patch to sort the labels before printing. > > > > > Check please. > > > > > > The patch looks fine to me. While reviewing it, I noticed that the > > > function has an extra loop to count the number of variables. I don't > > > think it's needed. The count can be obtained from the list length. In > > > the attached patch, I have removed that loop. Am I missing something? > > > > > > 0001 is your patch > > > 0002 removes the loop + some cosmetic changes > > > > > > Hi Kirill, > > > > > > > Do we need to keep relation lock until end of function > > > > (table_close(pglrel, AccessShareLock);)? > > > > > > I think you are right. Fixed in the attached. > > > > > > > I'm not sure if list_sort is > > > > interruptible. > > > > > > I don't think it matters here. It will be very rare, if not > > > impossible, to have so many labels as to let the sorting run for > > > milliseconds together. The foreach loop afterwards is also not > > > interruptible. Any reason you think it should be interruptible? > > > > > > -- > > > Best Wishes, > > > Ashutosh Bapat > > > > Do you think it's necessary to add a list_free_deep(label_list) at > > the end? make_propgraphdef_labels itself it not on critical path > > so explicit free non-used memory doesn't impact performance. > > > > It's not that the list or the labels will be too long to consume a lot > of memory. If that would have been the case, calling list_free_deep() > makes sense. But in this case, the memory will get freed when the > immediate memory context gets freed; in worst case that will be when > the statement finishes. I don't think it's worth the distraction and > the possible minimal risk it carries. Fair enough. Andrew mentioned in the SQL/PGQ commit thread that we should fence the dependency check in pg_dump.c, maybe collecting it in your patch set, see: https://www.postgresql.org/message-id/attachment/192197/fix-propgraph-def.patch > > -- > Best Wishes, > Ashutosh Bapat -- Regards Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
On Tue, Mar 17, 2026 at 11:25 AM Junwang Zhao wrote: > > On Tue, Mar 17, 2026 at 12:57 PM Ashutosh Bapat > wrote: > > > > On Tue, Mar 17, 2026 at 10:08 AM Junwang Zhao wrote: > > > > > > Hi Ashutosh, > > > > > > On Mon, Mar 16, 2026 at 11:55 PM Ashutosh Bapat > > > wrote: > > > > > > > > Hi Peter, > > > > > > > > > On Mon, 16 Mar 2026 at 17:43, Peter Eisentraut wrote: > > > > > > > > > > > > On 11.03.26 08:34, Ashutosh Bapat wrote: > > > > > > > There are two new patches 0004 and 0005 in the attached patchset. > > > > > > > > > > > > I have committed this, including the 0004 patch. > > > > > > > > Thanks a lot. > > > > > > > > > > Let's consider the > > > > > > 0005 patch separately. > > > > > > > > Will share the rebased patch soon. This thread may see discussion > > > > about the commit itself. Should I start a new thread for 0005 or use > > > > this one? New one seems better to me with a new CF entry. > > > > > > > > > > > > > > > > The buildfarm shows some instability in the pg_upgrade test, because > > > > > > labels are printed by pg_get_propgraphdef() in implementation-dependent > > > > > > order. Attached is a quick patch to sort the labels before printing. > > > > > > Check please. > > > > > > > > The patch looks fine to me. While reviewing it, I noticed that the > > > > function has an extra loop to count the number of variables. I don't > > > > think it's needed. The count can be obtained from the list length. In > > > > the attached patch, I have removed that loop. Am I missing something? > > > > > > > > 0001 is your patch > > > > 0002 removes the loop + some cosmetic changes > > > > > > > > Hi Kirill, > > > > > > > > > Do we need to keep relation lock until end of function > > > > > (table_close(pglrel, AccessShareLock);)? > > > > > > > > I think you are right. Fixed in the attached. > > > > > > > > > I'm not sure if list_sort is > > > > > interruptible. > > > > > > > > I don't think it matters here. It will be very rare, if not > > > > impossible, to have so many labels as to let the sorting run for > > > > milliseconds together. The foreach loop afterwards is also not > > > > interruptible. Any reason you think it should be interruptible? > > > > > > > > -- > > > > Best Wishes, > > > > Ashutosh Bapat > > > > > > Do you think it's necessary to add a list_free_deep(label_list) at > > > the end? make_propgraphdef_labels itself it not on critical path > > > so explicit free non-used memory doesn't impact performance. > > > > > > > It's not that the list or the labels will be too long to consume a lot > > of memory. If that would have been the case, calling list_free_deep() > > makes sense. But in this case, the memory will get freed when the > > immediate memory context gets freed; in worst case that will be when > > the statement finishes. I don't think it's worth the distraction and > > the possible minimal risk it carries. > > Fair enough. > > Andrew mentioned in the SQL/PGQ commit thread that we should > fence the dependency check in pg_dump.c, maybe collecting it > in your patch set, see: > > https://www.postgresql.org/message-id/attachment/192197/fix-propgraph-def.patch Can you please share the link to the message? This is an attachment without message context. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Tue, Mar 17, 2026 at 2:05 PM Ashutosh Bapat wrote: > > On Tue, Mar 17, 2026 at 11:25 AM Junwang Zhao wrote: > > > > On Tue, Mar 17, 2026 at 12:57 PM Ashutosh Bapat > > wrote: > > > > > > On Tue, Mar 17, 2026 at 10:08 AM Junwang Zhao wrote: > > > > > > > > Hi Ashutosh, > > > > > > > > On Mon, Mar 16, 2026 at 11:55 PM Ashutosh Bapat > > > > wrote: > > > > > > > > > > Hi Peter, > > > > > > > > > > > On Mon, 16 Mar 2026 at 17:43, Peter Eisentraut wrote: > > > > > > > > > > > > > > On 11.03.26 08:34, Ashutosh Bapat wrote: > > > > > > > > There are two new patches 0004 and 0005 in the attached patchset. > > > > > > > > > > > > > > I have committed this, including the 0004 patch. > > > > > > > > > > Thanks a lot. > > > > > > > > > > > > Let's consider the > > > > > > > 0005 patch separately. > > > > > > > > > > Will share the rebased patch soon. This thread may see discussion > > > > > about the commit itself. Should I start a new thread for 0005 or use > > > > > this one? New one seems better to me with a new CF entry. > > > > > > > > > > > > > > > > > > > The buildfarm shows some instability in the pg_upgrade test, because > > > > > > > labels are printed by pg_get_propgraphdef() in implementation-dependent > > > > > > > order. Attached is a quick patch to sort the labels before printing. > > > > > > > Check please. > > > > > > > > > > The patch looks fine to me. While reviewing it, I noticed that the > > > > > function has an extra loop to count the number of variables. I don't > > > > > think it's needed. The count can be obtained from the list length. In > > > > > the attached patch, I have removed that loop. Am I missing something? > > > > > > > > > > 0001 is your patch > > > > > 0002 removes the loop + some cosmetic changes > > > > > > > > > > Hi Kirill, > > > > > > > > > > > Do we need to keep relation lock until end of function > > > > > > (table_close(pglrel, AccessShareLock);)? > > > > > > > > > > I think you are right. Fixed in the attached. > > > > > > > > > > > I'm not sure if list_sort is > > > > > > interruptible. > > > > > > > > > > I don't think it matters here. It will be very rare, if not > > > > > impossible, to have so many labels as to let the sorting run for > > > > > milliseconds together. The foreach loop afterwards is also not > > > > > interruptible. Any reason you think it should be interruptible? > > > > > > > > > > -- > > > > > Best Wishes, > > > > > Ashutosh Bapat > > > > > > > > Do you think it's necessary to add a list_free_deep(label_list) at > > > > the end? make_propgraphdef_labels itself it not on critical path > > > > so explicit free non-used memory doesn't impact performance. > > > > > > > > > > It's not that the list or the labels will be too long to consume a lot > > > of memory. If that would have been the case, calling list_free_deep() > > > makes sense. But in this case, the memory will get freed when the > > > immediate memory context gets freed; in worst case that will be when > > > the statement finishes. I don't think it's worth the distraction and > > > the possible minimal risk it carries. > > > > Fair enough. > > > > Andrew mentioned in the SQL/PGQ commit thread that we should > > fence the dependency check in pg_dump.c, maybe collecting it > > in your patch set, see: > > > > https://www.postgresql.org/message-id/attachment/192197/fix-propgraph-def.patch > > Can you please share the link to the message? This is an attachment > without message context. here https://www.postgresql.org/message-id/afe3f099-3271-4fc4-8e32-467b5309affb%40dunslane.net > > -- > Best Wishes, > Ashutosh Bapat -- Regards Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
On Mon, 16 Mar 2026 at 20:55, Ashutosh Bapat wrote: > > Hi Peter, > > > On Mon, 16 Mar 2026 at 17:43, Peter Eisentraut wrote: > > > > > > On 11.03.26 08:34, Ashutosh Bapat wrote: > > > > There are two new patches 0004 and 0005 in the attached patchset. > > > > > > I have committed this, including the 0004 patch. > > Thanks a lot. > > > > Let's consider the > > > 0005 patch separately. > > Will share the rebased patch soon. This thread may see discussion > about the commit itself. Should I start a new thread for 0005 or use > this one? New one seems better to me with a new CF entry. > > > > > > > The buildfarm shows some instability in the pg_upgrade test, because > > > labels are printed by pg_get_propgraphdef() in implementation-dependent > > > order. Attached is a quick patch to sort the labels before printing. > > > Check please. > > The patch looks fine to me. While reviewing it, I noticed that the > function has an extra loop to count the number of variables. I don't > think it's needed. The count can be obtained from the list length. In > the attached patch, I have removed that loop. Am I missing something? > > 0001 is your patch > 0002 removes the loop + some cosmetic changes > > Hi Kirill, > > > Do we need to keep relation lock until end of function > > (table_close(pglrel, AccessShareLock);)? > > I think you are right. Fixed in the attached. > > > I'm not sure if list_sort is > > interruptible. > > I don't think it matters here. It will be very rare, if not > impossible, to have so many labels as to let the sorting run for > milliseconds together. The foreach loop afterwards is also not > interruptible. Any reason you think it should be interruptible? > > -- > Best Wishes, > Ashutosh Bapat Hi! v20260316-0002 looks good to me -- Best regards, Kirill Reshke
Re: SQL Property Graph Queries (SQL/PGQ)
On Tue, Mar 17, 2026 at 12:05 PM Junwang Zhao wrote: > > > > > > Andrew mentioned in the SQL/PGQ commit thread that we should > > > fence the dependency check in pg_dump.c, maybe collecting it > > > in your patch set, see: > > > > > > https://www.postgresql.org/message-id/attachment/192197/fix-propgraph-def.patch > > > > Can you please share the link to the message? This is an attachment > > without message context. > > here > > https://www.postgresql.org/message-id/afe3f099-3271-4fc4-8e32-467b5309affb%40dunslane.net Thanks Junwang. I see that without Andrew's patch the upgrade from an old cluster fails with pg_dump: error: query failed: ERROR: relation "pg_propgraph_element" does not exist LINE 7: ..., refclassid, refobjid, deptype FROM pg_depend d, pg_propgra... The error is fixed by Andrew's changes. But the patch is already committed by Peter. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Tue, Mar 17, 2026 at 5:54 PM Ashutosh Bapat wrote: > > On Tue, Mar 17, 2026 at 12:05 PM Junwang Zhao wrote: > > > > > > > > Andrew mentioned in the SQL/PGQ commit thread that we should > > > > fence the dependency check in pg_dump.c, maybe collecting it > > > > in your patch set, see: > > > > > > > > https://www.postgresql.org/message-id/attachment/192197/fix-propgraph-def.patch > > > > > > Can you please share the link to the message? This is an attachment > > > without message context. > > > > here > > > > https://www.postgresql.org/message-id/afe3f099-3271-4fc4-8e32-467b5309affb%40dunslane.net > > Thanks Junwang. > > I see that without Andrew's patch the upgrade from an old cluster fails with > pg_dump: error: query failed: ERROR: relation "pg_propgraph_element" > does not exist > LINE 7: ..., refclassid, refobjid, deptype FROM pg_depend d, pg_propgra... > > The error is fixed by Andrew's changes. But the patch is already > committed by Peter. Ok, then the patch set LGTM. > > -- > Best Wishes, > Ashutosh Bapat -- Regards Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
On 16.03.26 16:54, Ashutosh Bapat wrote: > The patch looks fine to me. While reviewing it, I noticed that the > function has an extra loop to count the number of variables. I don't > think it's needed. The count can be obtained from the list length. In > the attached patch, I have removed that loop. Am I missing something? > > 0001 is your patch > 0002 removes the loop + some cosmetic changes committed
Re: SQL Property Graph Queries (SQL/PGQ)
Hi all,
I hit a Segmentation fault due to what might be an non-standard coding approach I used. Here are the test details and error logs:
```
postgres@zxm-VMware-Virtual-Platform:~/code/postgres$ psql
psql (19devel)
Type "help" for help.
postgres=# CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(50)
);
CREATE TABLE follows (
id INT PRIMARY KEY,
follower INT REFERENCES users(id),
following INT REFERENCES users(id)
);
INSERT INTO users VALUES
(1, 'A'), (2, 'B'), (3, 'C'), (4, 'D');
INSERT INTO follows VALUES
(1, 1, 2),
(2, 1, 3),
(3, 2, 3),
(4, 2, 4),
(5, 3, 4);
CREATE PROPERTY GRAPH social_graph
VERTEX TABLES (users)
EDGE TABLES (
follows
SOURCE KEY (follower) REFERENCES users(id)
DESTINATION KEY (following) REFERENCES users(id)
);
-- ok
SELECT *
FROM GRAPH_TABLE (
social_graph
MATCH (a IS users)-[]->(x IS users)<-[]-(b IS users)
WHERE b.name != a.name
COLUMNS (a.name AS usera, x.name AS common_name, b.name AS userb)
);
-- error
SELECT *
FROM GRAPH_TABLE (
social_graph
MATCH (a IS users)-[]->(x IS users)<-[]-(b IS users WHERE b.name != a.name)
COLUMNS (a.name AS usera, x.name AS common_name, b.name AS userb)
);
CREATE TABLE
CREATE TABLE
INSERT 0 4
INSERT 0 5
CREATE PROPERTY GRAPH
usera | common_name | userb
-------+-------------+-------
A | C | B
B | C | A
B | D | C
C | D | B
(4 rows)
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
The connection to the server was lost. Attempting reset: 2026-03-18 14:09:29.522 CST [103556] LOG: client backend (PID 103851) was terminated by signal 11: Segmentation fault
2026-03-18 14:09:29.522 CST [103556] DETAIL: Failed process was running: SELECT *
FROM GRAPH_TABLE (
social_graph
MATCH (a IS users)-[]->(x IS users)<-[]-(b IS users WHERE b.name != a.name)
COLUMNS (a.name AS usera, x.name AS common_name, b.name AS userb)
);
2026-03-18 14:09:29.522 CST [103556] LOG: terminating any other active server processes
Failed.
The connection to the server was lost. Attempting reset: Failed.
2026-03-18 14:09:29.524 CST [103556] LOG: all server processes terminated; reinitializing
!?> 2026-03-18 14:09:29.546 CST [103857] LOG: database system was interrupted; last known up at 2026-03-18 14:08:06 CST
2026-03-18 14:09:29.570 CST [103857] LOG: database system was not properly shut down; automatic recovery in progress
2026-03-18 14:09:29.572 CST [103857] LOG: redo starts at 0/02487AE8
2026-03-18 14:09:29.578 CST [103857] LOG: invalid record length at 0/024E0AB0: expected at least 24, got 0
2026-03-18 14:09:29.578 CST [103857] LOG: redo done at 0/024E07A8 system usage: CPU: user: 0.00 s, system: 0.00 s, elapsed: 0.00 s
2026-03-18 14:09:29.596 CST [103556] LOG: database system is ready to accept connections
```
I checked the code and found that `found_mapping` was a null pointer because I didn’t enable assertions. The code in question is in `src/backend/rewrite/rewriteGraphTable.c`:
```
/*
* transformGraphTablePropertyRef() would not create a
* GraphPropertyRef for a variable which is not present in the graph
* path pattern.
*/
Assert(found_mapping);
mapping_factor = found_mapping->path_factor;
```
Should we remove this assertion and throw an error message instead to handle this case?
--
regards,
Man ZengRe: SQL Property Graph Queries (SQL/PGQ)
I reproduced the crash and identified the root cause.
I checked the code and found that `found_mapping` was a null pointer because
I didn't enable assertions. The code in question is in
`src/backend/rewrite/rewriteGraphTable.c`:
Should we remove this assertion and throw an error message instead to handle this case?
never create a GraphPropertyRef for a variable not present in the path
pattern. The real problem is that the element's WHERE clause was only
receiving its own mapping instead of all mappings in the path pattern.
In generate_query_for_graph_path():
tr = replace_property_refs(rte->relid, pf->whereClause, list_make1(pe));
list_make1(pe) passes only the current element's mapping to
replace_property_refs_mutator(). When the element WHERE clause references
another variable (e.g., `b.name != a.name` inside the `b` element pattern),
the mutator cannot find `a` in the mappings list, leaving found_mapping
NULL.
Note that the graph pattern-level WHERE clause already passes
graph_path (the full mapping list), which is why the same condition works
when placed outside the element pattern.
The fix is simply:
tr = replace_property_refs(rte->relid, pf->whereClause, graph_path);
Ashutosh, could you include this fix in the next patch revision?
With this fix, the reported query runs without crash and returns the
correct result. The graph_table regression test also passes cleanly.
Also, I'd like to check — do you see any potential side effects from
passing the full graph_path instead of list_make1(pe)? Since the mutator
now has access to all element mappings, I want to make sure there are no
unintended interactions in other code paths.
Regards,
Henson
Re: SQL Property Graph Queries (SQL/PGQ)
On 17.03.26 14:57, Peter Eisentraut wrote: > On 16.03.26 16:54, Ashutosh Bapat wrote: >> The patch looks fine to me. While reviewing it, I noticed that the >> function has an extra loop to count the number of variables. I don't >> think it's needed. The count can be obtained from the list length. In >> the attached patch, I have removed that loop. Am I missing something? >> >> 0001 is your patch >> 0002 removes the loop + some cosmetic changes > > committed There are still some pg_upgrade-related failures on the buildfarm, but AFAICT these are not specifically from this feature but more from the test design of the PG_TEST_EXTRA="regress_dump_restore" test. It looks like we need to drop all users at the end of src/test/regress/sql/graph_table_rls.sql to make this work.
Re: SQL Property Graph Queries (SQL/PGQ)
> The assertion itself is correct — transformGraphTablePropertyRef() should > never create a GraphPropertyRef for a variable not present in the path > pattern. The real problem is that the element's WHERE clause was only > receiving its own mapping instead of all mappings in the path pattern. > > In generate_query_for_graph_path(): > > tr = replace_property_refs(rte->relid, pf->whereClause, list_make1(pe)); > > list_make1(pe) passes only the current element's mapping to > replace_property_refs_mutator(). When the element WHERE clause references > another variable (e.g., `b.name != a.name` inside the `b` element pattern), > the mutator cannot find `a` in the mappings list, leaving found_mapping > NULL. > > Note that the graph pattern-level WHERE clause already passes > graph_path (the full mapping list), which is why the same condition works > when placed outside the element pattern. > > The fix is simply: > > tr = replace_property_refs(rte->relid, pf->whereClause, graph_path); > > Ashutosh, could you include this fix in the next patch revision? > > With this fix, the reported query runs without crash and returns the > correct result. The graph_table regression test also passes cleanly. > > Also, I'd like to check — do you see any potential side effects from > passing the full graph_path instead of list_make1(pe)? Since the mutator > now has access to all element mappings, I want to make sure there are no > unintended interactions in other code paths. Hi Henson, Thank you so much for resolving the issue so quickly. I'm a beginner in SQL/PGQ and was unsure if my syntax was compliant with standards. I might have misunderstood at the time. I thought that if it wasn't compliant, changing the assertion to throw an error message would be the simplest fix. I subsequently modified and tested it according to your suggestions, and the results were correct. -- regards, Man Zeng
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Henson,
On Wed, Mar 18, 2026 at 3:21 PM Henson Choi wrote:
>
> Hi Ashutosh, Man,
>
> I reproduced the crash and identified the root cause.
>
>
>> I checked the code and found that `found_mapping` was a null pointer because
>>
>> I didn't enable assertions. The code in question is in
>> `src/backend/rewrite/rewriteGraphTable.c`:
>>
>>
>>
>> Should we remove this assertion and throw an error message instead to handle this case?
>
>
> The assertion itself is correct — transformGraphTablePropertyRef() should
> never create a GraphPropertyRef for a variable not present in the path
> pattern. The real problem is that the element's WHERE clause was only
> receiving its own mapping instead of all mappings in the path pattern.
>
> In generate_query_for_graph_path():
>
> tr = replace_property_refs(rte->relid, pf->whereClause, list_make1(pe));
>
> list_make1(pe) passes only the current element's mapping to
> replace_property_refs_mutator(). When the element WHERE clause references
> another variable (e.g., `b.name != a.name` inside the `b` element pattern),
> the mutator cannot find `a` in the mappings list, leaving found_mapping
> NULL.
>
> Note that the graph pattern-level WHERE clause already passes
> graph_path (the full mapping list), which is why the same condition works
> when placed outside the element pattern.
>
> The fix is simply:
>
> tr = replace_property_refs(rte->relid, pf->whereClause, graph_path);
>
> Ashutosh, could you include this fix in the next patch revision?
This fixes the crash.
>
> With this fix, the reported query runs without crash and returns the
> correct result. The graph_table regression test also passes cleanly.
>
> Also, I'd like to check — do you see any potential side effects from
> passing the full graph_path instead of list_make1(pe)? Since the mutator
> now has access to all element mappings, I want to make sure there are no
> unintended interactions in other code paths.
One concern is that if we support
MATCH (a IS users)-[]->(x IS users)<-[]-(b IS users WHERE b.name != a.name)
user may expect the following also works:
MATCH (a IS users WHERE b.name != a.name)-[]->(x IS users)<-[]-(b IS users)
but the second actually failed to pass the transform phase.
I tested neo4j, both are well supported.
So we might follow the same behavior. The solution I came out is in
transformPathTerm
we collect gpstate->variables before each transformGraphElementPattern.
Something like:
transformPathTerm(ParseState *pstate, List *path_term)
{
List *result = NIL;
+ GraphTableParseState *gpstate = pstate->p_graph_table_pstate;
+
+ /*
+ * First gather all element variables from this path term so that WHERE
+ * clauses in any element pattern can reference variables
appearing anywhere
+ * in the term, regardless of order.
+ */
+ foreach_node(GraphElementPattern, gep, path_term)
+ {
+ if (gep->variable)
+ {
+ String *v = makeString(pstrdup(gep->variable));
+
+ if (!list_member(gpstate->variables, v))
+ gpstate->variables =
lappend(gpstate->variables, v);
+ }
+ }
foreach_node(GraphElementPattern, gep, path_term)
result = lappend(result,
Thoughts?
>
> Regards,
> Henson
--
Regards
Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
On Wed, Mar 18, 2026 at 12:59 PM Peter Eisentraut wrote: > > On 17.03.26 14:57, Peter Eisentraut wrote: > > On 16.03.26 16:54, Ashutosh Bapat wrote: > >> The patch looks fine to me. While reviewing it, I noticed that the > >> function has an extra loop to count the number of variables. I don't > >> think it's needed. The count can be obtained from the list length. In > >> the attached patch, I have removed that loop. Am I missing something? > >> > >> 0001 is your patch > >> 0002 removes the loop + some cosmetic changes > > > > committed > > There are still some pg_upgrade-related failures on the buildfarm, but > AFAICT these are not specifically from this feature but more from the > test design of the PG_TEST_EXTRA="regress_dump_restore" test. It looks > like we need to drop all users at the end of > src/test/regress/sql/graph_table_rls.sql to make this work. > Looking into this and the crash as well. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
> The fix is simply:
>
> tr = replace_property_refs(rte->relid, pf->whereClause, graph_path);
>
> Ashutosh, could you include this fix in the next patch revision?
This fixes the crash.
> Also, I'd like to check — do you see any potential side effects from
> passing the full graph_path instead of list_make1(pe)? Since the mutator
> now has access to all element mappings, I want to make sure there are no
> unintended interactions in other code paths.
One concern is that if we support
MATCH (a IS users)-[]->(x IS users)<-[]-(b IS users WHERE b.name != a.name)
user may expect the following also works:
MATCH (a IS users WHERE b.name != a.name)-[]->(x IS users)<-[]-(b IS users)
but the second actually failed to pass the transform phase.
I tested neo4j, both are well supported.
The standard is explicit about this. Subclause 10.6 Syntax Rule 18
(ISO/IEC 9075-16:2023) states:
"The scope of an <element variable> that is declared by an
<element pattern> EP is the innermost <graph table> containing EP."
The scope is the entire <graph table>, not "from the point of
declaration onward." So a forward reference like your second example
is just as valid as the backward reference in the first.
The current implementation registers variables into gpstate->variables
sequentially inside transformGraphElementPattern(), which makes forward
references invisible at transform time.
So we might follow the same behavior. The solution I came out is in
transformPathTerm
we collect gpstate->variables before each transformGraphElementPattern.
Something like:
transformPathTerm(ParseState *pstate, List *path_term)
{
List *result = NIL;
+ GraphTableParseState *gpstate = pstate->p_graph_table_pstate;
+
+ /*
+ * First gather all element variables from this path term so that WHERE
+ * clauses in any element pattern can reference variables
appearing anywhere
+ * in the term, regardless of order.
+ */
+ foreach_node(GraphElementPattern, gep, path_term)
+ {
+ if (gep->variable)
+ {
+ String *v = makeString(pstrdup(gep->variable));
+
+ if (!list_member(gpstate->variables, v))
+ gpstate->variables =
lappend(gpstate->variables, v);
+ }
+ }
foreach_node(GraphElementPattern, gep, path_term)
result = lappend(result,
Thoughts?
single path term.
One thing worth noting for the future: the standard says the
variable scope covers the entire <graph table> (SR 18), which
means cross-path-term references should also work once we support
multiple path patterns. For example:
MATCH (a IS users WHERE b.name != a.name)-[]->(x IS users),
(b IS users)-[]->(y IS users)
Here `b` is declared in the second path term but forward-referenced
in the first. Pre-collecting inside transformPathTerm would not see
`b` when processing the first path term. Moving the collection up
to transformPathPatternList, spanning all path terms before any
transformation, would cover both cases. I'll be posting a
multi-pattern path matching patch soon in a separate thread.
Regards,
Henson
Re: SQL Property Graph Queries (SQL/PGQ)
On Wed, Mar 18, 2026 at 6:33 PM Henson Choi wrote:
>
> Hi Junwang,
>
>> > The fix is simply:
>> >
>> > tr = replace_property_refs(rte->relid, pf->whereClause, graph_path);
>> >
>> > Ashutosh, could you include this fix in the next patch revision?
>>
>> This fixes the crash.
>
>
> Thanks for confirming.
>
>>
>> > Also, I'd like to check — do you see any potential side effects from
>> > passing the full graph_path instead of list_make1(pe)? Since the mutator
>> > now has access to all element mappings, I want to make sure there are no
>> > unintended interactions in other code paths.
>>
>> One concern is that if we support
>>
>> MATCH (a IS users)-[]->(x IS users)<-[]-(b IS users WHERE b.name != a.name)
>>
>> user may expect the following also works:
>>
>> MATCH (a IS users WHERE b.name != a.name)-[]->(x IS users)<-[]-(b IS users)
>>
>> but the second actually failed to pass the transform phase.
>>
>> I tested neo4j, both are well supported.
>
>
> Good catch. You're right -- both orderings should work.
>
> The standard is explicit about this. Subclause 10.6 Syntax Rule 18
> (ISO/IEC 9075-16:2023) states:
>
> "The scope of an that is declared by an
> EP is the innermost containing EP."
>
> The scope is the entire , not "from the point of
> declaration onward." So a forward reference like your second example
> is just as valid as the backward reference in the first.
>
> The current implementation registers variables into gpstate->variables
> sequentially inside transformGraphElementPattern(), which makes forward
> references invisible at transform time.
>
>> So we might follow the same behavior. The solution I came out is in
>> transformPathTerm
>> we collect gpstate->variables before each transformGraphElementPattern.
>>
>> Something like:
>>
>> transformPathTerm(ParseState *pstate, List *path_term)
>> {
>> List *result = NIL;
>> + GraphTableParseState *gpstate = pstate->p_graph_table_pstate;
>> +
>> + /*
>> + * First gather all element variables from this path term so that WHERE
>> + * clauses in any element pattern can reference variables
>> appearing anywhere
>> + * in the term, regardless of order.
>> + */
>> + foreach_node(GraphElementPattern, gep, path_term)
>> + {
>> + if (gep->variable)
>> + {
>> + String *v = makeString(pstrdup(gep->variable));
>> +
>> + if (!list_member(gpstate->variables, v))
>> + gpstate->variables =
>> lappend(gpstate->variables, v);
>> + }
>> + }
>>
>> foreach_node(GraphElementPattern, gep, path_term)
>> result = lappend(result,
>>
>> Thoughts?
>
>
> This correctly matches the standard's scoping semantics for a
> single path term.
>
> One thing worth noting for the future: the standard says the
> variable scope covers the entire (SR 18), which
> means cross-path-term references should also work once we support
> multiple path patterns. For example:
>
> MATCH (a IS users WHERE b.name != a.name)-[]->(x IS users),
> (b IS users)-[]->(y IS users)
>
> Here `b` is declared in the second path term but forward-referenced
> in the first. Pre-collecting inside transformPathTerm would not see
> `b` when processing the first path term. Moving the collection up
> to transformPathPatternList, spanning all path terms before any
> transformation, would cover both cases.
Yeah, I noticed that too, I will compose a patch for further review.
> I'll be posting a
> multi-pattern path matching patch soon in a separate thread.
>
> Regards,
> Henson
--
Regards
Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
Yeah, I noticed that too, I will compose a patch for further review.
Regards,
Henson
Re: SQL Property Graph Queries (SQL/PGQ)
On Wed, Mar 18, 2026 at 7:49 PM Henson Choi wrote: > > Hi Junwang, > >> >> Yeah, I noticed that too, I will compose a patch for further review. > > > Great, looking forward to reviewing it. Here. > > Regards, > Henson > -- Regards Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
>> Yeah, I noticed that too, I will compose a patch for further review.
>
>
> Great, looking forward to reviewing it.
Here.
standard's scoping semantics (SR 18).
1. pgindent alignment
The variable declaration on this line doesn't follow PostgreSQL's
tab-aligned style:
String *v = makeString(pstrdup(gep->variable));
Should be:
String *v = makeString(pstrdup(gep->variable));
Running pgindent on the file should fix this automatically.
2. Additional test coverage for edge patterns
The current tests cover vertex-to-vertex cross-references well.
How about adding a case where an edge WHERE clause references
vertex variables? For example:
-- edge WHERE cross-referencing vertex and edge properties
SELECT *
FROM GRAPH_TABLE (mygraph
MATCH (a)-[e WHERE e.weight > a.score]->(b)
COLUMNS (a.name AS a_name, e.weight AS e_wt,
b.name AS b_name)
) ORDER BY 1, 2;
This would ensure the fix covers edge element patterns too, not
just vertex patterns.
Otherwise, LGTM.
Regards,
Henson
Re: SQL Property Graph Queries (SQL/PGQ)
On Wed, Mar 18, 2026 at 12:59 PM Peter Eisentraut wrote: > > On 17.03.26 14:57, Peter Eisentraut wrote: > > On 16.03.26 16:54, Ashutosh Bapat wrote: > >> The patch looks fine to me. While reviewing it, I noticed that the > >> function has an extra loop to count the number of variables. I don't > >> think it's needed. The count can be obtained from the list length. In > >> the attached patch, I have removed that loop. Am I missing something? > >> > >> 0001 is your patch > >> 0002 removes the loop + some cosmetic changes > > > > committed > > There are still some pg_upgrade-related failures on the buildfarm, but > AFAICT these are not specifically from this feature but more from the > test design of the PG_TEST_EXTRA="regress_dump_restore" test. It looks > like we need to drop all users at the end of > src/test/regress/sql/graph_table_rls.sql to make this work. > PFA the patch. I tried using --no-owner with pg_restore and pg_dump but that doesn't work since it doesn't exclude policies. I had to add "reassign owner to" so that we could retain as many objects as possible. Also had to drop the policies which are applicable to users being dropped. Reassign doesn't work on policies, ofc. I remember thinking about using pg_dumpall instead of pg_dump in 002_pg_upgrade, but IIRC, we faced some issues doing so. Didn't try that this time. If that works, we may not need to drop users. But I am not sure if the test coverage we will get for dump/restore is worth it. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Wed, Mar 18, 2026 at 10:47 PM Henson Choi wrote: > > Hi Junwang, > >> >> Yeah, I noticed that too, I will compose a patch for further review. >> > >> > >> > Great, looking forward to reviewing it. >> >> Here. > > > Thanks for the patch. The code changes look correct and match the > standard's scoping semantics (SR 18). > > I applied the patch and ran the regression tests — all clean. > > A couple of minor items: > > 1. pgindent alignment > > The variable declaration on this line doesn't follow PostgreSQL's > tab-aligned style: > > String *v = makeString(pstrdup(gep->variable)); > > Should be: > > String *v = makeString(pstrdup(gep->variable)); > > Running pgindent on the file should fix this automatically. fixed. > > 2. Additional test coverage for edge patterns > > The current tests cover vertex-to-vertex cross-references well. > How about adding a case where an edge WHERE clause references > vertex variables? For example: > > -- edge WHERE cross-referencing vertex and edge properties > SELECT * > FROM GRAPH_TABLE (mygraph > MATCH (a)-[e WHERE e.weight > a.score]->(b) > COLUMNS (a.name AS a_name, e.weight AS e_wt, > b.name AS b_name) > ) ORDER BY 1, 2; > > This would ensure the fix covers edge element patterns too, not > just vertex patterns. I created a similar case using the social graph, applying a pattern *a followed b before a's 18th birthday*, which should work. > > Otherwise, LGTM. > > Regards, > Henson > -- Regards Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
On Wed, Mar 18, 2026 at 6:45 PM Junwang Zhao wrote: > > On Wed, Mar 18, 2026 at 7:49 PM Henson Choi wrote: > > > > Hi Junwang, > > > >> > >> Yeah, I noticed that too, I will compose a patch for further review. > > > > > > Great, looking forward to reviewing it. > > Here. Thanks for the patch. I developed a similar patch parallely; attached here. But I used the existing objects in graph_table.sql to add more tests instead of creating a whole new set of objects. The new queries test both the vertex as well as edge patterns as suggested by Henson. In my patch I have added a test for forward reference, but didn't implement the support for the same. I am not sure whether we want to support forward references right now, for the reasons mentioned below a. Other products allow cross referencing, but it seems it's optional in SQL standard. Conformance rule 11 of subclause 10.6 seems to make the feature optional. If that's the case, we need to throw an error in case of cross reference. Peter, what do you think? b. The graph pattern handling code will go through more revisions as we support path list, nested path patterns, path pattern quantifiers and other ways to specify path patterns. Implementing forward referencing right now, in a way, that fits the current code might create more work in future revisions. Doing it after we have a few more of the above list supported, will require comparatively less work. We may require subqueries to represent some path patterns like embedded path patterns or path patterns with quantifiers. Forward referencing in FROM clause is now allowed, so we will need to do magic with condition pull to support forward referencing. Delaying the forward referencing support till then is better. c. It's not a blocker: users can write the forward referencing condition in the graph pattern where clause instead of element pattern where clause. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Thanks for the patch and the analysis.
In my patch I have added a test for forward reference, but didn't
implement the support for the same. I am not sure whether we want to
support forward references right now, for the reasons mentioned below
a. Other products allow cross referencing, but it seems it's optional
in SQL standard. Conformance rule 11 of subclause 10.6 seems to make
the feature optional. If that's the case, we need to throw an error in
case of cross reference. Peter, what do you think?
"Without Feature G041, 'Non-local element pattern predicates',
in conforming SQL language, the <element pattern where clause>
of an <element pattern> EP shall only reference the
<element variable> declared in EP."
This makes *all* cross-variable references in element WHERE clauses
optional under G041 -- it does not distinguish between backward and
forward references. So if we support G041 (which we effectively do,
since backward cross-references already work after the
list_make1(pe) -> graph_path fix), then SR 18 applies in full:
"The scope of an <element variable> that is declared by an
<element pattern> EP is the innermost <graph table> containing EP."
The current state -- backward yes, forward no -- is a
half-implementation that does not correspond to either option.
We should either:
(1) Support G041 fully -- both directions. Junwang's patch handles
this cleanly with minimal code change, or
(2) Not support G041 -- reject all non-local element pattern
references, throwing an error for both directions.
What do you think?
Regards,
Henson
Re: SQL Property Graph Queries (SQL/PGQ)
Ashutosh Bapat writes:
> On Wed, Mar 18, 2026 at 12:59 PM Peter Eisentraut wrote:
>> There are still some pg_upgrade-related failures on the buildfarm, but
>> AFAICT these are not specifically from this feature but more from the
>> test design of the PG_TEST_EXTRA="regress_dump_restore" test. It looks
>> like we need to drop all users at the end of
>> src/test/regress/sql/graph_table_rls.sql to make this work.
> PFA the patch. I tried using --no-owner with pg_restore and pg_dump
> but that doesn't work since it doesn't exclude policies.
I just came across a side effect of this same thing. After running
"make installcheck", there are roles left behind:
regression=# \du
List of roles
Role name | Attributes
-------------------------------+------------------------------------------------------------
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS
regress_graph_rls_alice | Cannot login
regress_graph_rls_bob | Cannot login
regress_graph_rls_carol | Cannot login
regress_graph_rls_dave | Cannot login
regress_graph_rls_exempt_user | Cannot login, Bypass RLS
regress_graph_rls_group1 | Cannot login
regress_graph_rls_group2 | Cannot login
I don't think this is acceptable at all. The contract for
installcheck testing, IMO, is that it doesn't leave behind any
permanent global effects other than the existence of the regression
database. Roles with elevated privileges seem like a particularly
dangerous thing to leave behind.
So I think we *must* drop all these roles at the end of the test,
regardless of the fact that not doing so breaks regress_dump_restore.
If you want to test dump/restore behavior with some non-default roles,
you have to do it in a TAP test that is using a purely temporary
installation. (But I hope we have adequate coverage for that
already.)
Your patch looks like it does that, but the test script's setup
could also be simplified, since it no longer has to contend with
the possibility that those roles are already there.
regards, tom lane
Re: SQL Property Graph Queries (SQL/PGQ)
On Thu, Mar 19, 2026 at 2:46 AM Tom Lane wrote: > > Ashutosh Bapat writes: > > On Wed, Mar 18, 2026 at 12:59 PM Peter Eisentraut wrote: > >> There are still some pg_upgrade-related failures on the buildfarm, but > >> AFAICT these are not specifically from this feature but more from the > >> test design of the PG_TEST_EXTRA="regress_dump_restore" test. It looks > >> like we need to drop all users at the end of > >> src/test/regress/sql/graph_table_rls.sql to make this work. > > > PFA the patch. I tried using --no-owner with pg_restore and pg_dump > > but that doesn't work since it doesn't exclude policies. > > I just came across a side effect of this same thing. After running > "make installcheck", there are roles left behind: > > regression=# \du > List of roles > Role name | Attributes > -------------------------------+------------------------------------------------------------ > postgres | Superuser, Create role, Create DB, Replication, Bypass RLS > regress_graph_rls_alice | Cannot login > regress_graph_rls_bob | Cannot login > regress_graph_rls_carol | Cannot login > regress_graph_rls_dave | Cannot login > regress_graph_rls_exempt_user | Cannot login, Bypass RLS > regress_graph_rls_group1 | Cannot login > regress_graph_rls_group2 | Cannot login > > I don't think this is acceptable at all. The contract for > installcheck testing, IMO, is that it doesn't leave behind any > permanent global effects other than the existence of the regression > database. Roles with elevated privileges seem like a particularly > dangerous thing to leave behind. > > So I think we *must* drop all these roles at the end of the test, > regardless of the fact that not doing so breaks regress_dump_restore. > If you want to test dump/restore behavior with some non-default roles, > you have to do it in a TAP test that is using a purely temporary > installation. (But I hope we have adequate coverage for that > already.) > > Your patch looks like it does that, but the test script's setup > could also be simplified, since it no longer has to contend with > the possibility that those roles are already there. Thanks for the explanation. The test changes are on the right track then. rowsecurity.sql has similar DROP statements in the setup and at the end. The comment there mentions "-- Clean up in case a prior regression run failed ". I guess the global objects could be left behind in case the "make installcheck" aborts while after the global objects are created but before the test finishes. Rerunning the test would fail. But I didn't go deeper to investigate exactly when we need those DROP statements. I just copied that pattern in graph_table_rls.sql. Do you think we can simplify rowsecurity.sql setup the same way? -- Best Wishes, Ashutosh Bapat
[PATCH] rewriteGraphTable: Fix missing RTEs in FROM clause by setting inFromCl=true
Hi all,
I made a super simple extension `https://github.com/Z-Xiao-M/pg_pgq2sql` to get the equivalent SQL of PGQ queries – it simply calls `pg_get_querydef` after `QueryRewrite` to fetch the SQL text.
However, I noticed that some FROM clauses were missing in the generated SQL statements.
```
postgres=# SELECT * FROM pg_pgq2sql($$
SELECT common_name
FROM GRAPH_TABLE (
social_graph
MATCH (a IS users)-[]->(x IS users)<-[]-(b IS users)
WHERE a.name = 'Alice' AND b.name = 'Bob'
COLUMNS (x.name AS common_name)
)
$$);
pg_pgq2sql
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
SELECT common_name +
FROM LATERAL ( SELECT users_1.name AS common_name +
WHERE users.id = follows.follower AND users_1.id = follows.following AND users_2.id = follows_1.follower AND users_1.id = follows_1.following AND users.name::text = 'Alice'::text AND users_2.name::text = 'Bob'::text) "graph_table"
(1 row)
```
I did a quick check and found the issue: some `rte->inFromCl` were set to `false` (should be `true` here). Here’s a quick patch to fix it:
```
postgres@zxm-VMware-Virtual-Platform:~/code/postgres$ git diff
diff --git a/src/backend/rewrite/rewriteGraphTable.c b/src/backend/rewrite/rewriteGraphTable.c
index 06f2f3442d8..d43704ef233 100644
--- a/src/backend/rewrite/rewriteGraphTable.c
+++ b/src/backend/rewrite/rewriteGraphTable.c
@@ -498,7 +498,7 @@ generate_query_for_graph_path(RangeTblEntry *rte, List *graph_path)
*/
rel = table_open(pe->reloid, AccessShareLock);
pni = addRangeTableEntryForRelation(make_parsestate(NULL), rel, AccessShareLock,
- NULL, true, false);
+ NULL, true, true);
table_close(rel, NoLock);
path_query->rtable = lappend(path_query->rtable, pni->p_rte);
path_query->rteperminfos = lappend(path_query->rteperminfos, pni->p_perminfo);
```
After applying the patch, the FROM clause is now complete:
```
postgres=# SELECT * FROM pg_pgq2sql($$
SELECT common_name
FROM GRAPH_TABLE (
social_graph
MATCH (a IS users)-[]->(x IS users)<-[]-(b IS users)
WHERE a.name = 'Alice' AND b.name = 'Bob'
COLUMNS (x.name AS common_name)
)
$$);
pg_pgq2sql
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
SELECT common_name +
FROM LATERAL ( SELECT users_1.name AS common_name +
FROM users, +
follows, +
users users_1, +
follows follows_1, +
users users_2 +
WHERE users.id = follows.follower AND users_1.id = follows.following AND users_2.id = follows_1.follower AND users_1.id = follows_1.following AND users.name::text = 'Alice'::text AND users_2.name::text = 'Bob'::text) "graph_table"
(1 row)
postgres=#
postgres=# SELECT common_name
FROM GRAPH_TABLE (
social_graph
MATCH (a IS users)-[]->(x IS users)<-[]-(b IS users)
WHERE a.name = 'Alice' AND b.name = 'Bob'
COLUMNS (x.name AS common_name)
) ;
common_name
-------------
Charlie
(1 row)
postgres=# SELECT common_name
FROM LATERAL ( SELECT users_1.name AS common_name
FROM users,
follows,
users users_1,
follows follows_1,
users users_2
WHERE users.id = follows.follower AND users_1.id = follows.following AND users_2.id = follows_1.follower AND users_1.id = follows_1.following AND users.name::text = 'Alice'::text AND users_2.name::text = 'Bob'::text) "graph_table";
common_name
-------------
Charlie
(1 row)
```
Curious to hear your thoughts/suggestions on this.
--
regards,
Man ZengRe: [PATCH] rewriteGraphTable: Fix missing RTEs in FROM clause by setting inFromCl=true
I made a super simple extension `https://github.com/Z-Xiao-M/pg_pgq2sql` to get the equivalent SQL of PGQ queries – it simply calls `pg_get_querydef` after `QueryRewrite` to fetch the SQL text.
However, I noticed that some FROM clauses were missing in the generated SQL statements.
entries (they're appended to fromlist), so inFromCl should be true.
I looked at whether this has any impact beyond pg_pgq2sql:
- pg_get_viewdef() deparses the pre-rewrite query, so it outputs the
original GRAPH_TABLE(...) syntax — not affected.
- pg_dump uses pg_get_viewdef(), so also not affected.
So in practice, this only affects code that deparses the post-rewrite
query (like your extension). No core code path currently does this for
graph table queries.
pni = addRangeTableEntryForRelation(make_parsestate(NULL), rel, AccessShareLock,
- NULL, true, false);
+ NULL, true, true);
inFromCl is false for "RTEs that are added to a query behind the
scenes, such as the NEW and OLD variables for a rule, or the subqueries
of a UNION." The element table RTEs here are neither — they are
genuinely in the FROM clause.
Ashutosh, what do you think?
Best regards,
Henson
Re: [PATCH] rewriteGraphTable: Fix missing RTEs in FROM clause by setting inFromCl=true
On Thu, Mar 19, 2026 at 9:17 PM zengman wrote: > > Hi all, > > I made a super simple extension `https://github.com/Z-Xiao-M/pg_pgq2sql` to get the equivalent SQL of PGQ queries – it simply calls `pg_get_querydef` after `QueryRewrite` to fetch the SQL text. > > However, I noticed that some FROM clauses were missing in the generated SQL statements. > > ``` > postgres=# SELECT * FROM pg_pgq2sql($$ > SELECT common_name > FROM GRAPH_TABLE ( > social_graph > MATCH (a IS users)-[]->(x IS users)<-[]-(b IS users) > WHERE a.name = 'Alice' AND b.name = 'Bob' > COLUMNS (x.name AS common_name) > ) > $$); > pg_pgq2sql > -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- > SELECT common_name + > FROM LATERAL ( SELECT users_1.name AS common_name + > WHERE users.id = follows.follower AND users_1.id = follows.following AND users_2.id = follows_1.follower AND users_1.id = follows_1.following AND users.name::text = 'Alice'::text AND users_2.name::text = 'Bob'::text) "graph_table" > (1 row) > ``` > > I did a quick check and found the issue: some `rte->inFromCl` were set to `false` (should be `true` here). Here’s a quick patch to fix it: > > ``` > postgres@zxm-VMware-Virtual-Platform:~/code/postgres$ git diff > diff --git a/src/backend/rewrite/rewriteGraphTable.c b/src/backend/rewrite/rewriteGraphTable.c > index 06f2f3442d8..d43704ef233 100644 > --- a/src/backend/rewrite/rewriteGraphTable.c > +++ b/src/backend/rewrite/rewriteGraphTable.c > @@ -498,7 +498,7 @@ generate_query_for_graph_path(RangeTblEntry *rte, List *graph_path) > */ > rel = table_open(pe->reloid, AccessShareLock); > pni = addRangeTableEntryForRelation(make_parsestate(NULL), rel, AccessShareLock, > - NULL, true, false); > + NULL, true, true); > table_close(rel, NoLock); > path_query->rtable = lappend(path_query->rtable, pni->p_rte); > path_query->rteperminfos = lappend(path_query->rteperminfos, pni->p_perminfo); > ``` > > After applying the patch, the FROM clause is now complete: > > ``` > postgres=# SELECT * FROM pg_pgq2sql($$ > SELECT common_name > FROM GRAPH_TABLE ( > social_graph > MATCH (a IS users)-[]->(x IS users)<-[]-(b IS users) > WHERE a.name = 'Alice' AND b.name = 'Bob' > COLUMNS (x.name AS common_name) > ) > $$); > pg_pgq2sql > -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- > SELECT common_name + > FROM LATERAL ( SELECT users_1.name AS common_name + > FROM users, + > follows, + > users users_1, + > follows follows_1, + > users users_2 + > WHERE users.id = follows.follower AND users_1.id = follows.following AND users_2.id = follows_1.follower AND users_1.id = follows_1.following AND users.name::text = 'Alice'::text AND users_2.name::text = 'Bob'::text) "graph_table" > (1 row) > > postgres=# > postgres=# SELECT common_name > FROM GRAPH_TABLE ( > social_graph > MATCH (a IS users)-[]->(x IS users)<-[]-(b IS users) > WHERE a.name = 'Alice' AND b.name = 'Bob' > COLUMNS (x.name AS common_name) > ) ; > common_name > ------------- > Charlie > (1 row) > > postgres=# SELECT common_name > FROM LATERAL ( SELECT users_1.name AS common_name > FROM users, > follows, > users users_1, > follows follows_1, > users users_2 > WHERE users.id = follows.follower AND users_1.id = follows.following AND users_2.id = follows_1.follower AND users_1.id = follows_1.following AND users.name::text = 'Alice'::text AND users_2.name::text = 'Bob'::text) "graph_table"; > common_name > ------------- > Charlie > (1 row) > ``` > > Curious to hear your thoughts/suggestions on this. I checked the comment: * inFromCl marks those range variables that are listed in the FROM clause. * It's false for RTEs that are added to a query behind the scenes, such * as the NEW and OLD variables for a rule, or the subqueries of a UNION. Even the RTEs are not directly listed in FROM, but as we are rewriting the match pattern using join and where clause, I tend to agree with the fix. > > -- > regards, > Man Zeng -- Regards Junwang Zhao
Re: [PATCH] rewriteGraphTable: Fix missing RTEs in FROM clause by setting inFromCl=true
I checked the comment:
* inFromCl marks those range variables that are listed in the FROM clause.
* It's false for RTEs that are added to a query behind the scenes, such
* as the NEW and OLD variables for a rule, or the subqueries of a UNION.
Even the RTEs are not directly listed in FROM, but as we are rewriting the
match pattern using join and where clause, I tend to agree with the fix.
Re: [PATCH] rewriteGraphTable: Fix missing RTEs in FROM clause by setting inFromCl=true
> Would you consider adding this to the commitfest? Hi Henson, Thank you for reminding me. ``` https://commitfest.postgresql.org/patch/6602/ ``` I discovered that due to my incorrect operation, the two themes were merged together, which is quite embarrassing. -- regards, Man Zeng
Re: SQL Property Graph Queries (SQL/PGQ)
On Thu, Mar 19, 2026 at 12:52 AM Henson Choi wrote: > > Hi Ashutosh, > > Thanks for the patch and the analysis. > >> In my patch I have added a test for forward reference, but didn't >> implement the support for the same. I am not sure whether we want to >> support forward references right now, for the reasons mentioned below >> >> a. Other products allow cross referencing, but it seems it's optional >> in SQL standard. Conformance rule 11 of subclause 10.6 seems to make >> the feature optional. If that's the case, we need to throw an error in >> case of cross reference. Peter, what do you think? > > > I looked into this. Conformance Rule 11 says: > > "Without Feature G041, 'Non-local element pattern predicates', > in conforming SQL language, the > of an EP shall only reference the > declared in EP." > > This makes *all* cross-variable references in element WHERE clauses > optional under G041 -- it does not distinguish between backward and > forward references. So if we support G041 (which we effectively do, > since backward cross-references already work after the > list_make1(pe) -> graph_path fix), then SR 18 applies in full: > > "The scope of an that is declared by an > EP is the innermost containing EP." > > The current state -- backward yes, forward no -- is a > half-implementation that does not correspond to either option. > > We should either: > > (1) Support G041 fully -- both directions. Junwang's patch handles > this cleanly with minimal code change, or > (2) Not support G041 -- reject all non-local element pattern > references, throwing an error for both directions. > > What do you think? We will support the cross variable references in future once we support more path patterns leading to a more mature code in that area. But it doesn't harm to support backward references which can be easily supported now. I don't see the code to do so getting disturbed as it matures. For the segmentation fault a simple fix to add graph_pattern suffices for now. Let's see if Peter has a different opinion. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
Here's a patchset consolidating all the fixes discussed till now. The test fix for buildfarm issue is already committed. 0001: Fixes the segmentation fault reported in [1]. There is some difference of opinion about supporting non-local variable references [2]. Given that it's a segmentation fault, we need to fix this sooner. 0002: Cleanup patch proposed by Man Zeng [3]. I think we can wait to collect more such cleanups before committing this. [1] https://www.postgresql.org/message-id/tencent_0F596C3C557454CE7EC420B4@qq.com [2] https://www.postgresql.org/message-id/CAAAe_zCA_9=JWBf4S5o_C2=EO=6dBZ6-=T0TUH+z5cvJkrtaUA@mail.gmail.com [3] https://www.postgresql.org/message-id/tencent_6CA50FEF38D76F7C5BD8C765@qq.com -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On 18.03.26 16:32, Ashutosh Bapat wrote: > On Wed, Mar 18, 2026 at 12:59 PM Peter Eisentraut wrote: >> >> On 17.03.26 14:57, Peter Eisentraut wrote: >>> On 16.03.26 16:54, Ashutosh Bapat wrote: >>>> The patch looks fine to me. While reviewing it, I noticed that the >>>> function has an extra loop to count the number of variables. I don't >>>> think it's needed. The count can be obtained from the list length. In >>>> the attached patch, I have removed that loop. Am I missing something? >>>> >>>> 0001 is your patch >>>> 0002 removes the loop + some cosmetic changes >>> >>> committed >> >> There are still some pg_upgrade-related failures on the buildfarm, but >> AFAICT these are not specifically from this feature but more from the >> test design of the PG_TEST_EXTRA="regress_dump_restore" test. It looks >> like we need to drop all users at the end of >> src/test/regress/sql/graph_table_rls.sql to make this work. >> > > PFA the patch. I tried using --no-owner with pg_restore and pg_dump > but that doesn't work since it doesn't exclude policies. I had to add > "reassign owner to" so that we could retain as many objects as > possible. Also had to drop the policies which are applicable to users > being dropped. Reassign doesn't work on policies, ofc. I have committed this patch, and it seems to be clearing up the pg_upgrade test failures on the buildfarm.
Re: SQL Property Graph Queries (SQL/PGQ)
Hello hackers, I've discovered an assertion failure produced with the following script: CREATE TABLE v1 (id int primary key, t text); CREATE TABLE v2 (id int primary key, t text); CREATE TABLE e1_2 (id_1 int, id_2 int, t text); CREATE PROPERTY GRAPH g1 VERTEX TABLES (v1, v2) EDGE TABLES ( e1_2 key (id_1, id_2) SOURCE KEY (id_1) REFERENCES v1 (id) DESTINATION KEY (id_2) REFERENCES v2 (id) ); SELECT count(*) FROM GRAPH_TABLE (g1 MATCH ()-> COLUMNS (1 AS one)); #5 0x000056bad84ce223 in ExceptionalCondition (conditionName=conditionName@entry=0x56bad85bb5c2 "pf->src_pf && pf->dest_pf", fileName=fileName@entry=0x56bad85bb5ae "rewriteGraphTable.c", lineNumber=lineNumber@entry=783) at assert.c:65 #6 0x000056bad8153748 in create_pe_for_element (pf=pf@entry=0x5250000c88c0, elemoid=elemoid@entry=16421) at rewriteGraphTable.c:783 #7 0x000056bad8153932 in get_path_elements_for_path_factor (propgraphid=16406, pf=0x5250000c88c0) at rewriteGraphTable.c:926 #8 0x000056bad815594d in generate_queries_for_path_pattern (rte=rte@entry=0x525000009380, path_pattern=0x525000008df0) at rewriteGraphTable.c:334 #9 0x000056bad8156fe3 in rewriteGraphTable (parsetree=parsetree@entry=0x525000008bc0, rt_index=rt_index@entry=1) at rewriteGraphTable.c:121 #10 0x000056bad815bd03 in fireRIRrules (parsetree=0x525000008bc0, activeRIRs=activeRIRs@entry=0x0) at rewriteHandler.c:2057 #11 0x000056bad8164bfc in QueryRewrite (parsetree=parsetree@entry=0x525000008bc0) at rewriteHandler.c:4627 #12 0x000056bad8228046 in pg_rewrite_query (query=query@entry=0x525000008bc0) at postgres.c:821 #13 0x000056bad8228441 in pg_analyze_and_rewrite_fixedparams (parsetree=parsetree@entry=0x525000008a30, query_string=query_string@entry=0x525000007a00 "SELECT count(*) FROM GRAPH_TABLE (g1 MATCH ()-> COLUMNS (1 AS one));", paramTypes=paramTypes@entry=0x0, numParams=numParams@entry=0, queryEnv=queryEnv@entry=0x0) at postgres.c:695 Best regards, Alexander
Re: SQL Property Graph Queries (SQL/PGQ)
I've discovered an assertion failure produced with the following script:
CREATE TABLE v1 (id int primary key, t text);
CREATE TABLE v2 (id int primary key, t text);
CREATE TABLE e1_2 (id_1 int, id_2 int, t text);
CREATE PROPERTY GRAPH g1
VERTEX TABLES (v1, v2)
EDGE TABLES (
e1_2 key (id_1, id_2)
SOURCE KEY (id_1) REFERENCES v1 (id)
DESTINATION KEY (id_2) REFERENCES v2 (id)
);
SELECT count(*) FROM GRAPH_TABLE (g1 MATCH ()-> COLUMNS (1 AS one));
at rewriteGraphTable.c:783 because the edge's dest_pf is NULL -- there
is no destination vertex following the edge pattern.
Per SQL/PGQ standard (ISO/IEC 9075-16:2023), Section 10.6 Syntax
Rules 13c and 13d, implicit empty vertex patterns should be inserted
when an edge pattern is not preceded or followed by a vertex pattern
at the same depth of graph pattern matching. Specifically:
SR 13c: If an edge pattern EP contained in a <path term> PST at
the same depth of graph pattern matching is not preceded
by a <vertex pattern> contained in PST at the same depth
of graph pattern matching, then an implicit empty
<vertex pattern> VP is inserted in PST immediately
prior to EP.
SR 13d: If an edge pattern EP contained in a <path term> PST at
the same depth of graph pattern matching is not followed
by a <vertex pattern> contained in PST at the same depth
of graph pattern matching, then an implicit empty
<vertex pattern> VP is inserted in PST immediately
after EP.
So `()->` should be treated as `()->()`, and `->` as `()->()`.
This also applies to left-pointing edges (`<-`, `()<-`) and
any-direction edges (`-[]-`).
The crash affects all patterns where a vertex is missing adjacent
to an edge:
-- trailing edge (SR 13d)
MATCH ()-> MATCH ()<- MATCH ()-[]-
-- leading edge (SR 13c)
MATCH ->() MATCH <-()
-- edge only (SR 13c + 13d)
MATCH -> MATCH <- MATCH -[]-
-- consecutive edges (SR 13b, with separator to avoid SR 3)
MATCH ()-> ->()
In a non-assert build, this results in a segfault (NULL pointer
dereference at pf->dest_pf->factorpos).
I have a fix that inserts implicit empty vertex patterns in the
rewrite stage (not the parser), so that ruleutils can still
reconstruct the original user-written pattern from the parse tree.
The fix handles all three cases: SR 13b (consecutive edges),
SR 13c (leading edge), and SR 13d (trailing edge).
The change is in generate_queries_for_path_pattern(), before the
path factor linking loop:
/*
* Per SQL standard 10.6 SR 13b/c/d, insert implicit empty vertex
* patterns where needed:
* SR 13b: between two consecutive edge patterns
* SR 13c: before a leading edge pattern
* SR 13d: after a trailing edge pattern
*
* We do this in the rewrite stage (not the parser) so that ruleutils
* can reconstruct the original user-written pattern from the parse tree.
*/
{
List *expanded = NIL;
GraphElementPattern *prev_gep = NULL;
foreach_node(GraphElementPattern, gep, path_pattern)
{
/* SR 13c: leading edge needs a vertex before it */
/* SR 13b: consecutive edges need a vertex between them */
if (IS_EDGE_PATTERN(gep->kind) &&
(prev_gep == NULL || IS_EDGE_PATTERN(prev_gep->kind)))
{
GraphElementPattern *implicit_vp = makeNode(GraphElementPattern);
implicit_vp->kind = VERTEX_PATTERN;
expanded = lappend(expanded, implicit_vp);
}
expanded = lappend(expanded, gep);
prev_gep = gep;
}
/* SR 13d: trailing edge needs a vertex after it */
if (prev_gep && IS_EDGE_PATTERN(prev_gep->kind))
{
GraphElementPattern *implicit_vp = makeNode(GraphElementPattern);
implicit_vp->kind = VERTEX_PATTERN;
expanded = lappend(expanded, implicit_vp);
}
path_pattern = expanded;
}
Separately, while testing various edge patterns I noticed that
`<-[]->` (full edge left or right) produces a syntax error:
SELECT count(*) FROM GRAPH_TABLE (g1 MATCH ()<-[]->() COLUMNS (1 AS one));
ERROR: syntax error at or near "->"
Per the standard BNF, this should be valid:
<full edge left or right> ::=
<left arrow bracket> <element pattern filler> <bracket right arrow>
i.e., `<-[]->` = `<-[` + `]->`. This is a separate parser issue,
not related to the implicit vertex insertion above.
All existing regression tests (graph_table, graph_table_rls, and
the full pg-check suite) pass with this change.
Ashutosh, since you designed the path factor linking logic in
generate_queries_for_path_pattern(), you would know best whether
this insertion point has any side effects on cyclic patterns or
the edge-vertex qual construction downstream. Could you take
this snippet and fold it into a proper patch if it looks right?
Regards,
Henson
Re: SQL Property Graph Queries (SQL/PGQ)
On Sat, Mar 21, 2026 at 6:19 PM Henson Choi wrote:
>
> Hi Alexander,
>
>> I've discovered an assertion failure produced with the following script:
>> CREATE TABLE v1 (id int primary key, t text);
>> CREATE TABLE v2 (id int primary key, t text);
>> CREATE TABLE e1_2 (id_1 int, id_2 int, t text);
>> CREATE PROPERTY GRAPH g1
>> VERTEX TABLES (v1, v2)
>> EDGE TABLES (
>> e1_2 key (id_1, id_2)
>> SOURCE KEY (id_1) REFERENCES v1 (id)
>> DESTINATION KEY (id_2) REFERENCES v2 (id)
>> );
>>
>> SELECT count(*) FROM GRAPH_TABLE (g1 MATCH ()-> COLUMNS (1 AS one));
>
Thanks for the report.
>
> I looked into this. The pattern `()->` causes an assertion failure
> at rewriteGraphTable.c:783 because the edge's dest_pf is NULL -- there
> is no destination vertex following the edge pattern.
>
> Per SQL/PGQ standard (ISO/IEC 9075-16:2023), Section 10.6 Syntax
> Rules 13c and 13d, implicit empty vertex patterns should be inserted
> when an edge pattern is not preceded or followed by a vertex pattern
> at the same depth of graph pattern matching. Specifically:
>
> SR 13c: If an edge pattern EP contained in a PST at
> the same depth of graph pattern matching is not preceded
> by a contained in PST at the same depth
> of graph pattern matching, then an implicit empty
> VP is inserted in PST immediately
> prior to EP.
>
> SR 13d: If an edge pattern EP contained in a PST at
> the same depth of graph pattern matching is not followed
> by a contained in PST at the same depth
> of graph pattern matching, then an implicit empty
> VP is inserted in PST immediately
> after EP.
>
> So `()->` should be treated as `()->()`, and `->` as `()->()`.
> This also applies to left-pointing edges (`<-`, `()<-`) and
> any-direction edges (`-[]-`).
>
> The crash affects all patterns where a vertex is missing adjacent
> to an edge:
>
> -- trailing edge (SR 13d)
> MATCH ()-> MATCH ()<- MATCH ()-[]-
>
> -- leading edge (SR 13c)
> MATCH ->() MATCH <-()
>
> -- edge only (SR 13c + 13d)
> MATCH -> MATCH <- MATCH -[]-
>
> -- consecutive edges (SR 13b, with separator to avoid SR 3)
> MATCH ()-> ->()
>
> In a non-assert build, this results in a segfault (NULL pointer
> dereference at pf->dest_pf->factorpos).
>
> I have a fix that inserts implicit empty vertex patterns in the
> rewrite stage (not the parser), so that ruleutils can still
> reconstruct the original user-written pattern from the parse tree.
> The fix handles all three cases: SR 13b (consecutive edges),
> SR 13c (leading edge), and SR 13d (trailing edge).
>
> The change is in generate_queries_for_path_pattern(), before the
> path factor linking loop:
>
> /*
> * Per SQL standard 10.6 SR 13b/c/d, insert implicit empty vertex
> * patterns where needed:
> * SR 13b: between two consecutive edge patterns
> * SR 13c: before a leading edge pattern
> * SR 13d: after a trailing edge pattern
> *
> * We do this in the rewrite stage (not the parser) so that ruleutils
> * can reconstruct the original user-written pattern from the parse tree.
> */
> {
> List *expanded = NIL;
> GraphElementPattern *prev_gep = NULL;
>
> foreach_node(GraphElementPattern, gep, path_pattern)
> {
> /* SR 13c: leading edge needs a vertex before it */
> /* SR 13b: consecutive edges need a vertex between them */
> if (IS_EDGE_PATTERN(gep->kind) &&
> (prev_gep == NULL || IS_EDGE_PATTERN(prev_gep->kind)))
> {
> GraphElementPattern *implicit_vp = makeNode(GraphElementPattern);
>
> implicit_vp->kind = VERTEX_PATTERN;
> expanded = lappend(expanded, implicit_vp);
> }
>
> expanded = lappend(expanded, gep);
> prev_gep = gep;
> }
>
> /* SR 13d: trailing edge needs a vertex after it */
> if (prev_gep && IS_EDGE_PATTERN(prev_gep->kind))
> {
> GraphElementPattern *implicit_vp = makeNode(GraphElementPattern);
>
> implicit_vp->kind = VERTEX_PATTERN;
> expanded = lappend(expanded, implicit_vp);
> }
>
> path_pattern = expanded;
> }
An empty pattern has no label expression which is equivalent to
disjunction of all applicable labels. If we add an empty pattern in
the rewrite phase, we will require its label expression to be resolved
in the rewrite phase. Looking at the proposed changes for all
properties reference [1], I am moving towards resolving the label
expression in the transformation stage itself. So I think it's better
to add the implicit vertex patterns during the transformation stage to
be future proof. Rewriter should just then rewrite the patterns into
joins and unions. Your point is correct that the implicit vertex
should not be visible in view definition or deparsed query. For that I
have added a flag implicit to GraphElementPattern.
GraphElementPatterns with implicit = true are ignored by ruleutils.
Implemented it that way in the attached patch.
Vertex patterns without an edge pattern in between are not supported
OTOH. Added an ereport for the same.
I have also added a few tests. I didn't add queries with all the
patterns you mentioned above. I tested a few by hand and all of them
worked as expected. Can you please check?
>
> Separately, while testing various edge patterns I noticed that
> `<-[]->` (full edge left or right) produces a syntax error:
>
> SELECT count(*) FROM GRAPH_TABLE (g1 MATCH ()<-[]->() COLUMNS (1 AS one));
> ERROR: syntax error at or near "->"
>
> Per the standard BNF, this should be valid:
>
> ::=
>
>
> i.e., `<-[]->` = `<-[` + `]->`. This is a separate parser issue,
> not related to the implicit vertex insertion above.
Yes. That's a grammar issue. gram.y doesn't support it. Peter, do you
remember or know the reason why we don't support full edge left or
right? In fact, I am wondering what's the difference between full edge
left or right and full edge any direction?
Here's cumulative patchset
0001 - Fixes the segmentation fault reported in [2]. There is some
difference of opinion about supporting non-local variable references
[3].
0002 - implicit vertex patterns as discussed in this email
0003: Cleanup patch proposed by Man Zeng [4]. Added some cosmetic
changes to ereports in parse_graphtable.c. It can wait to collect more
such cleanups before committing this.
[1] https://www.postgresql.org/message-id/CAExHW5tYCE9QyCvVraKUeesKW5RTR%2Bmrzsg3u64qSps-RPJR5A%40mail.gmail.com
[2] https://www.postgresql.org/message-id/tencent_0F596C3C557454CE7EC420B4@qq.com
[3] https://www.postgresql.org/message-id/CAAAe_zCA_9=JWBf4S5o_C2=EO=6dBZ6-=T0TUH+z5cvJkrtaUA@mail.gmail.com
[4] https://www.postgresql.org/message-id/tencent_6CA50FEF38D76F7C5BD8C765@qq.com
--
Best Wishes,
Ashutosh Bapat
Re: [PATCH] rewriteGraphTable: Fix missing RTEs in FROM clause by setting inFromCl=true
On Thu, Mar 19, 2026 at 8:35 PM Junwang Zhao wrote: > > On Thu, Mar 19, 2026 at 9:17 PM zengman wrote: > > > > Hi all, > > > > I made a super simple extension `https://github.com/Z-Xiao-M/pg_pgq2sql` to get the equivalent SQL of PGQ queries – it simply calls `pg_get_querydef` after `QueryRewrite` to fetch the SQL text. > > > > However, I noticed that some FROM clauses were missing in the generated SQL statements. > > > > ``` > > postgres=# SELECT * FROM pg_pgq2sql($$ > > SELECT common_name > > FROM GRAPH_TABLE ( > > social_graph > > MATCH (a IS users)-[]->(x IS users)<-[]-(b IS users) > > WHERE a.name = 'Alice' AND b.name = 'Bob' > > COLUMNS (x.name AS common_name) > > ) > > $$); > > pg_pgq2sql > > -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- > > SELECT common_name + > > FROM LATERAL ( SELECT users_1.name AS common_name + > > WHERE users.id = follows.follower AND users_1.id = follows.following AND users_2.id = follows_1.follower AND users_1.id = follows_1.following AND users.name::text = 'Alice'::text AND users_2.name::text = 'Bob'::text) "graph_table" > > (1 row) > > ``` > > > > I did a quick check and found the issue: some `rte->inFromCl` were set to `false` (should be `true` here). Here’s a quick patch to fix it: > > > > ``` > > postgres@zxm-VMware-Virtual-Platform:~/code/postgres$ git diff > > diff --git a/src/backend/rewrite/rewriteGraphTable.c b/src/backend/rewrite/rewriteGraphTable.c > > index 06f2f3442d8..d43704ef233 100644 > > --- a/src/backend/rewrite/rewriteGraphTable.c > > +++ b/src/backend/rewrite/rewriteGraphTable.c > > @@ -498,7 +498,7 @@ generate_query_for_graph_path(RangeTblEntry *rte, List *graph_path) > > */ > > rel = table_open(pe->reloid, AccessShareLock); > > pni = addRangeTableEntryForRelation(make_parsestate(NULL), rel, AccessShareLock, > > - NULL, true, false); > > + NULL, true, true); > > table_close(rel, NoLock); > > path_query->rtable = lappend(path_query->rtable, pni->p_rte); > > path_query->rteperminfos = lappend(path_query->rteperminfos, pni->p_perminfo); > > ``` > > > > After applying the patch, the FROM clause is now complete: > > > > ``` > > postgres=# SELECT * FROM pg_pgq2sql($$ > > SELECT common_name > > FROM GRAPH_TABLE ( > > social_graph > > MATCH (a IS users)-[]->(x IS users)<-[]-(b IS users) > > WHERE a.name = 'Alice' AND b.name = 'Bob' > > COLUMNS (x.name AS common_name) > > ) > > $$); > > pg_pgq2sql > > -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- > > SELECT common_name + > > FROM LATERAL ( SELECT users_1.name AS common_name + > > FROM users, + > > follows, + > > users users_1, + > > follows follows_1, + > > users users_2 + > > WHERE users.id = follows.follower AND users_1.id = follows.following AND users_2.id = follows_1.follower AND users_1.id = follows_1.following AND users.name::text = 'Alice'::text AND users_2.name::text = 'Bob'::text) "graph_table" > > (1 row) > > > > postgres=# > > postgres=# SELECT common_name > > FROM GRAPH_TABLE ( > > social_graph > > MATCH (a IS users)-[]->(x IS users)<-[]-(b IS users) > > WHERE a.name = 'Alice' AND b.name = 'Bob' > > COLUMNS (x.name AS common_name) > > ) ; > > common_name > > ------------- > > Charlie > > (1 row) > > > > postgres=# SELECT common_name > > FROM LATERAL ( SELECT users_1.name AS common_name > > FROM users, > > follows, > > users users_1, > > follows follows_1, > > users users_2 > > WHERE users.id = follows.follower AND users_1.id = follows.following AND users_2.id = follows_1.follower AND users_1.id = follows_1.following AND users.name::text = 'Alice'::text AND users_2.name::text = 'Bob'::text) "graph_table"; > > common_name > > ------------- > > Charlie > > (1 row) > > ``` > > > > Curious to hear your thoughts/suggestions on this. > > I checked the comment: > > * inFromCl marks those range variables that are listed in the FROM clause. > * It's false for RTEs that are added to a query behind the scenes, such > * as the NEW and OLD variables for a rule, or the subqueries of a UNION. > > Even the RTEs are not directly listed in FROM, but as we are rewriting the > match pattern using join and where clause, I tend to agree with the fix. I would look at the code which adds subqueries corresponding to the views when rewriting queries. Do these subquery RTEs have their inFromCl set to true? A few instances I examined, set inFromCl = false and rightly so since they are not part of the original from clause. I think setting it for subqueries derived for GRAPH_TABLE. I also think that the proposed fix isn't traversing the UNION query tree. Have you tried a GRAPH_TABLE clause which resuts into UNION of JOINs. For the sake of the extension, (which looks useful), inFromCl can be set to true for the desired RTEs after fetching rewritten query and copying it. You would need query tree mutator for the same. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
I have also added a few tests. I didn't add queries with all the
patterns you mentioned above. I tested a few by hand and all of them
worked as expected. Can you please check?
correct results.
One thing I noticed while reviewing the rewriter changes: the Assert
at generate_queries_for_path_pattern() that checks alternating
implicit/explicit elements doesn't actually work:
#ifdef USE_ASSERT_CHECKING
GraphElementPattern *prev_gep = NULL;
#endif
...
Assert(!prev_gep || prev_gep->implicit != gep->implicit);
prev_gep is never updated in the loop -- it stays NULL throughout,
so the Assert is always trivially true. It needs a
"prev_gep = gep;" at the end of the loop body to actually perform
the intended check.
Yes. That's a grammar issue. gram.y doesn't support it. Peter, do you
remember or know the reason why we don't support full edge left or
right? In fact, I am wondering what's the difference between full edge
left or right and full edge any direction?
I looked into this. The lexer tokenizes "]->` as "]" + RIGHT_ARROW,
so gram.y needs two alternatives -- just like the existing full edge
right rule already does. The full edge left or right was simply
missing both forms. Adding them fixes it:
| '<' '-' '[' ... ']' '-' '>'
| '<' '-' '[' ... ']' RIGHT_ARROW
Per the standard, <-[]-> matches left or right direction while -[]-
matches any direction. For simple directed graphs the results are
the same, so EDGE_PATTERN_ANY seems like a reasonable mapping.
Regards,
Henson
Re: SQL Property Graph Queries (SQL/PGQ)
Hallo Everyone!
Good to see this progressing rapidly.
I did not see much documentation committed yet, so I am asking here.
What is the best way to find out which parts of the SQL/PGQ standard
we aim to implement for v19 and what are the know limitations?
The reason I'm asking is that the first thing I tried with fresh
checkout was a minimally modified sample from
https://duckpgq.org/documentation/sql_pgq/ and it immediately failed
------8<------------8<------------8<------------8<------------8<------------8<------------8<------
=# CREATE TABLE person(id serial primary key, name text);
CREATE TABLE
=# CREATE TABLE person_knows_person(
person1id int REFERENCES person ( id ),
person2id int REFERENCES person ( id )
);
CREATE TABLE
=# CREATE PROPERTY GRAPH snb
VERTEX TABLES (
Person
)
EDGE TABLES (
Person_knows_person
SOURCE KEY ( person1id ) REFERENCES Person ( id )
DESTINATION KEY ( person2id ) REFERENCES Person ( id )
LABEL Knows
);
ERROR: 42P17: no key specified and no suitable primary key exists for
definition of element "person_knows_person"
LINE 6: Person_knows_person
^
LOCATION: propgraph_element_get_key, propgraphcmds.c:334
Time: 0.459 ms
------8<------------8<------------8<------------8<------------8<------------8<------------8<------
It worked when I changed person_knows_person.person1id into PRIMARY KEY.
---
Cheers
Hannu
On Tue, Mar 24, 2026 at 2:05 AM Henson Choi wrote:
>
> Hi Ashutosh,
>
>> I have also added a few tests. I didn't add queries with all the
>> patterns you mentioned above. I tested a few by hand and all of them
>> worked as expected. Can you please check?
>
>
>
> I tested all the patterns and they all work correctly. No crashes,
> correct results.
>
> One thing I noticed while reviewing the rewriter changes: the Assert
> at generate_queries_for_path_pattern() that checks alternating
> implicit/explicit elements doesn't actually work:
>
> #ifdef USE_ASSERT_CHECKING
> GraphElementPattern *prev_gep = NULL;
> #endif
> ...
> Assert(!prev_gep || prev_gep->implicit != gep->implicit);
>
> prev_gep is never updated in the loop -- it stays NULL throughout,
> so the Assert is always trivially true. It needs a
> "prev_gep = gep;" at the end of the loop body to actually perform
> the intended check.
>
>>
>> Yes. That's a grammar issue. gram.y doesn't support it. Peter, do you
>> remember or know the reason why we don't support full edge left or
>> right? In fact, I am wondering what's the difference between full edge
>> left or right and full edge any direction?
>
>
>
> I looked into this. The lexer tokenizes "]->` as "]" + RIGHT_ARROW,
> so gram.y needs two alternatives -- just like the existing full edge
> right rule already does. The full edge left or right was simply
> missing both forms. Adding them fixes it:
>
> | '<' '-' '[' ... ']' '-' '>'
> | '<' '-' '[' ... ']' RIGHT_ARROW
>
> Per the standard, <-[]-> matches left or right direction while -[]-
> matches any direction. For simple directed graphs the results are
> the same, so EDGE_PATTERN_ANY seems like a reasonable mapping.
>
> Regards,
> Henson
Re: SQL Property Graph Queries (SQL/PGQ)
On Tue, Mar 24, 2026 at 6:35 AM Henson Choi wrote: > > Hi Ashutosh, > >> I have also added a few tests. I didn't add queries with all the >> patterns you mentioned above. I tested a few by hand and all of them >> worked as expected. Can you please check? > > > > I tested all the patterns and they all work correctly. No crashes, > correct results. > Thanks a lot for the confirmation. > One thing I noticed while reviewing the rewriter changes: the Assert > at generate_queries_for_path_pattern() that checks alternating > implicit/explicit elements doesn't actually work: > > #ifdef USE_ASSERT_CHECKING > GraphElementPattern *prev_gep = NULL; > #endif > ... > Assert(!prev_gep || prev_gep->implicit != gep->implicit); > > prev_gep is never updated in the loop -- it stays NULL throughout, > so the Assert is always trivially true. It needs a > "prev_gep = gep;" at the end of the loop body to actually perform > the intended check. > Ah. Thanks for catching it. I think the Assertion is also not doing what it mentions in the comment. It just checks whether the two consecutive elements are not implicit ones; that doesn't necessarily lead to an infinite or very long chain of implicit element patterns. I have removed the assertion for now. We will add it if necessary, e.g. when we start adding implicit edge patterns in which case the possibility of long chains of implicit element patterns becomes real. >> >> Yes. That's a grammar issue. gram.y doesn't support it. Peter, do you >> remember or know the reason why we don't support full edge left or >> right? In fact, I am wondering what's the difference between full edge >> left or right and full edge any direction? > > > > I looked into this. The lexer tokenizes "]->` as "]" + RIGHT_ARROW, > so gram.y needs two alternatives -- just like the existing full edge > right rule already does. The full edge left or right was simply > missing both forms. Adding them fixes it: > > | '<' '-' '[' ... ']' '-' '>' > | '<' '-' '[' ... ']' RIGHT_ARROW > > Per the standard, <-[]-> matches left or right direction while -[]- > matches any direction. For simple directed graphs the results are > the same, so EDGE_PATTERN_ANY seems like a reasonable mapping. Our grammar is pretty tricky in this area especially because we can treat a string of operators as a SQL operator. Peter may have intentionally left it unsupported. Here's the updated patchset. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Tue, Mar 24, 2026 at 6:54 PM Hannu Krosing wrote: > > Hallo Everyone! > > Good to see this progressing rapidly. > > I did not see much documentation committed yet, so I am asking here. > > What is the best way to find out which parts of the SQL/PGQ standard > we aim to implement for v19 and what are the know limitations? > > > The reason I'm asking is that the first thing I tried with fresh > checkout was a minimally modified sample from > https://duckpgq.org/documentation/sql_pgq/ and it immediately failed > > ------8<------------8<------------8<------------8<------------8<------------8<------------8<------ > =# CREATE TABLE person(id serial primary key, name text); > CREATE TABLE > > =# CREATE TABLE person_knows_person( > person1id int REFERENCES person ( id ), > person2id int REFERENCES person ( id ) > ); > CREATE TABLE > > =# CREATE PROPERTY GRAPH snb > VERTEX TABLES ( > Person > ) > EDGE TABLES ( > Person_knows_person > SOURCE KEY ( person1id ) REFERENCES Person ( id ) > DESTINATION KEY ( person2id ) REFERENCES Person ( id ) > LABEL Knows > ); > ERROR: 42P17: no key specified and no suitable primary key exists for > definition of element "person_knows_person" > LINE 6: Person_knows_person > ^ > LOCATION: propgraph_element_get_key, propgraphcmds.c:334 > Time: 0.459 ms > ------8<------------8<------------8<------------8<------------8<------------8<------------8<------ > > It worked when I changed person_knows_person.person1id into PRIMARY KEY. Yes, each element is expected to have a key, either defined explicitly when creating the graph or implicitly via its primary key. I'm not sure whether we should infer the key from the source and destination keys, though it's doable. see https://www.postgresql.org/docs/devel/catalog-pg-propgraph-element.html > > --- > Cheers > Hannu > > > On Tue, Mar 24, 2026 at 2:05 AM Henson Choi wrote: > > > > Hi Ashutosh, > > > >> I have also added a few tests. I didn't add queries with all the > >> patterns you mentioned above. I tested a few by hand and all of them > >> worked as expected. Can you please check? > > > > > > > > I tested all the patterns and they all work correctly. No crashes, > > correct results. > > > > One thing I noticed while reviewing the rewriter changes: the Assert > > at generate_queries_for_path_pattern() that checks alternating > > implicit/explicit elements doesn't actually work: > > > > #ifdef USE_ASSERT_CHECKING > > GraphElementPattern *prev_gep = NULL; > > #endif > > ... > > Assert(!prev_gep || prev_gep->implicit != gep->implicit); > > > > prev_gep is never updated in the loop -- it stays NULL throughout, > > so the Assert is always trivially true. It needs a > > "prev_gep = gep;" at the end of the loop body to actually perform > > the intended check. > > > >> > >> Yes. That's a grammar issue. gram.y doesn't support it. Peter, do you > >> remember or know the reason why we don't support full edge left or > >> right? In fact, I am wondering what's the difference between full edge > >> left or right and full edge any direction? > > > > > > > > I looked into this. The lexer tokenizes "]->` as "]" + RIGHT_ARROW, > > so gram.y needs two alternatives -- just like the existing full edge > > right rule already does. The full edge left or right was simply > > missing both forms. Adding them fixes it: > > > > | '<' '-' '[' ... ']' '-' '>' > > | '<' '-' '[' ... ']' RIGHT_ARROW > > > > Per the standard, <-[]-> matches left or right direction while -[]- > > matches any direction. For simple directed graphs the results are > > the same, so EDGE_PATTERN_ANY seems like a reasonable mapping. > > > > Regards, > > Henson -- Regards Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
> ERROR: 42P17: no key specified and no suitable primary key exists for
> definition of element "person_knows_person"
> LINE 6: Person_knows_person
> ^
> LOCATION: propgraph_element_get_key, propgraphcmds.c:334
> Time: 0.459 ms
> ------8<------------8<------------8<------------8<------------8<------------8<------------8<------
>
> It worked when I changed person_knows_person.person1id into PRIMARY KEY.
Yes, each element is expected to have a key, either defined explicitly
when creating the graph or implicitly via its primary key.
descriptor", Syntax Rule 4:
a) If <element table key clause> is not specified, then
i) If the table descriptor of ET includes a unique constraint
descriptor UCD that specifies PRIMARY KEY, then let ETK be
the list of the names of the unique columns included in UCD
in order of their ordinal position in ET.
ii) Otherwise, the table descriptor of ET shall include a
preferred candidate key. Let ETK be the list of columns in
that preferred candidate key in order of their ordinal
position in ET.
b) Otherwise, let ETK be the <column name list> simply contained
in <element table key clause>.
Note: our current implementation only checks for PRIMARY KEY when
no KEY clause is specified. The standard also allows falling back
to a "preferred candidate key", which we don't support yet.
I'm not sure whether we should infer the key from the source and
destination keys, though it's doable.
(Part 2), which I don't have access to -- I suspect it refers
to a UNIQUE NOT NULL constraint. But if the source +
destination key columns happen to qualify as one, they would
already be covered by rule 4.a.ii above. So rather than
special-casing source + destination inference, implementing
preferred candidate key support would cover that case naturally.
Henson
Re: SQL Property Graph Queries (SQL/PGQ)
Thanks! The SQL standard (ISO/IEC 9075-2: Foundation) defines these terms as follows: - *Candidate Key*: Any combination of columns that can uniquely identify a row in a table. A table can have multiple candidate keys (for example, a Users table might have both an EmployeeID and a SocialSecurityNumber, both of which are unique). - *Preferred Candidate Key*: Because a table can have multiple candidate keys, the SQL standard designates one as the "preferred" key to represent the table when an arbitrary unique identifier is required. - If the table has a defined PRIMARY KEY, that primary key is automatically the preferred candidate key. - If the table has no primary key but has UNIQUE constraints, the standard uses a specific set of rules (typically the "left-most" unique constraint in the table definition) to elect the preferred candidate key. I guess the reason the example works in DuckDB is that they have an implicit RowID which can be used as a fall-back "Preferred candidate key" to make rows in table "person_knows_person" UNIQUE. On Tue, Mar 24, 2026 at 4:07 PM Henson Choi wrote: >> >> > ERROR: 42P17: no key specified and no suitable primary key exists for >> > definition of element "person_knows_person" >> > LINE 6: Person_knows_person >> > ^ >> > LOCATION: propgraph_element_get_key, propgraphcmds.c:334 >> > Time: 0.459 ms >> > ------8<------------8<------------8<------------8<------------8<------------8<------------8<------ >> > >> > It worked when I changed person_knows_person.person1id into PRIMARY KEY. >> >> Yes, each element is expected to have a key, either defined explicitly >> when creating the graph or implicitly via its primary key. > > > Right. Per SQL/PGQ Subclause 9.12 "Creation of an element table > descriptor", Syntax Rule 4: > > a) If is not specified, then > i) If the table descriptor of ET includes a unique constraint > descriptor UCD that specifies PRIMARY KEY, then let ETK be > the list of the names of the unique columns included in UCD > in order of their ordinal position in ET. > ii) Otherwise, the table descriptor of ET shall include a > preferred candidate key. Let ETK be the list of columns in > that preferred candidate key in order of their ordinal > position in ET. > > b) Otherwise, let ETK be the simply contained > in . > > Note: our current implementation only checks for PRIMARY KEY when > no KEY clause is specified. The standard also allows falling back > to a "preferred candidate key", which we don't support yet. > >> >> I'm not sure whether we should infer the key from the source and >> destination keys, though it's doable. > > > "Preferred candidate key" is likely defined in SQL Foundation > (Part 2), which I don't have access to -- I suspect it refers > to a UNIQUE NOT NULL constraint. But if the source + > destination key columns happen to qualify as one, they would > already be covered by rule 4.a.ii above. So rather than > special-casing source + destination inference, implementing > preferred candidate key support would cover that case naturally. > > Regards, > Henson
Re: SQL Property Graph Queries (SQL/PGQ)
On 16.03.26 17:28, Ashutosh Bapat wrote: > On Mon, Mar 16, 2026 at 8:39 PM zengman wrote: >> >> Hi, >> >> The commit 2f094e7ac691abc9d2fe0f4dcf0feac4a6ce1d9c delivers an excellent feature, and the file `rewriteGraphTable.c` was introduced as part of this commit. >> I've noticed that this code file could benefit from some tidying up, so please review the diff file attached below. >> This diff only includes **basic cleanup** of `rewriteGraphTable.c` – it’s just a simple pass, >> and there may be other minor omissions that haven’t been addressed yet. > > Hi Man, > Thanks for the patch. I reviewed the cleanup you propose. Most of the > changes look good to me, except the changes related to pstate. We have > both patterns in the code, one which uses free_parsestate() explicitly > and another that doesn't. In this case, we don't set > p_target_relation, and we don't touch p_next_resno. So the only thing > that free_parsestate() does it to free pstate, which will taken care > of by the memory context management. So not needed. Any other reason > you want to call free_parsestate() explicitly? > > Attached patch has changes other that pstate related changes. committed this
Re: SQL Property Graph Queries (SQL/PGQ)
On 20.03.26 14:42, Ashutosh Bapat wrote: >> We should either: >> >> (1) Support G041 fully -- both directions. Junwang's patch handles >> this cleanly with minimal code change, or >> (2) Not support G041 -- reject all non-local element pattern >> references, throwing an error for both directions. >> >> What do you think? > > We will support the cross variable references in future once we > support more path patterns leading to a more mature code in that area. > But it doesn't harm to support backward references which can be easily > supported now. I don't see the code to do so getting disturbed as it > matures. For the segmentation fault a simple fix to add graph_pattern > suffices for now. Let's see if Peter has a different opinion. I think we should not allow non-local references in either direction (until we implement feature G041), option 2 above. Allowing only backward references seems kind of an arbitrary implementation artifact.
Re: SQL Property Graph Queries (SQL/PGQ)
On 23.03.26 16:00, Ashutosh Bapat wrote: > An empty pattern has no label expression which is equivalent to > disjunction of all applicable labels. If we add an empty pattern in > the rewrite phase, we will require its label expression to be resolved > in the rewrite phase. Looking at the proposed changes for all > properties reference [1], I am moving towards resolving the label > expression in the transformation stage itself. So I think it's better > to add the implicit vertex patterns during the transformation stage to > be future proof. Rewriter should just then rewrite the patterns into > joins and unions. Your point is correct that the implicit vertex > should not be visible in view definition or deparsed query. For that I > have added a flag implicit to GraphElementPattern. > GraphElementPatterns with implicit = true are ignored by ruleutils. > Implemented it that way in the attached patch. > > Vertex patterns without an edge pattern in between are not supported > OTOH. Added an ereport for the same. > > I have also added a few tests. I didn't add queries with all the > patterns you mentioned above. I tested a few by hand and all of them > worked as expected. Can you please check? This functionality that you can leave off empty vertex patterns at the beginning and end is part of the optional feature G047, which we don't claim to support. So we should reject these path patterns. >> Separately, while testing various edge patterns I noticed that >> `<-[]->` (full edge left or right) produces a syntax error: >> >> SELECT count(*) FROM GRAPH_TABLE (g1 MATCH ()<-[]->() COLUMNS (1 AS one)); >> ERROR: syntax error at or near "->" >> >> Per the standard BNF, this should be valid: >> >> ::= >> >> >> i.e., `<-[]->` = `<-[` + `]->`. This is a separate parser issue, >> not related to the implicit vertex insertion above. > > Yes. That's a grammar issue. gram.y doesn't support it. Peter, do you > remember or know the reason why we don't support full edge left or > right? In fact, I am wondering what's the difference between full edge > left or right and full edge any direction? is part of optional feature G043, which we don't claim to support.
Re: SQL Property Graph Queries (SQL/PGQ)
On Wed, Mar 25, 2026 at 2:27 PM Peter Eisentraut wrote: > > On 23.03.26 16:00, Ashutosh Bapat wrote: > > An empty pattern has no label expression which is equivalent to > > disjunction of all applicable labels. If we add an empty pattern in > > the rewrite phase, we will require its label expression to be resolved > > in the rewrite phase. Looking at the proposed changes for all > > properties reference [1], I am moving towards resolving the label > > expression in the transformation stage itself. So I think it's better > > to add the implicit vertex patterns during the transformation stage to > > be future proof. Rewriter should just then rewrite the patterns into > > joins and unions. Your point is correct that the implicit vertex > > should not be visible in view definition or deparsed query. For that I > > have added a flag implicit to GraphElementPattern. > > GraphElementPatterns with implicit = true are ignored by ruleutils. > > Implemented it that way in the attached patch. > > > > Vertex patterns without an edge pattern in between are not supported > > OTOH. Added an ereport for the same. > > > > I have also added a few tests. I didn't add queries with all the > > patterns you mentioned above. I tested a few by hand and all of them > > worked as expected. Can you please check? > > This functionality that you can leave off empty vertex patterns at the > beginning and end is part of the optional feature G047, which we don't > claim to support. So we should reject these path patterns. > Thanks for the clarification. What about the implicit empty vertex patterns in the middle of the path? Should we reject these path patterns also? > >> Separately, while testing various edge patterns I noticed that > >> `<-[]->` (full edge left or right) produces a syntax error: > >> > >> SELECT count(*) FROM GRAPH_TABLE (g1 MATCH ()<-[]->() COLUMNS (1 AS one)); > >> ERROR: syntax error at or near "->" > >> > >> Per the standard BNF, this should be valid: > >> > >> ::= > >> > >> > >> i.e., `<-[]->` = `<-[` + `]->`. This is a separate parser issue, > >> not related to the implicit vertex insertion above. > > > > Yes. That's a grammar issue. gram.y doesn't support it. Peter, do you > > remember or know the reason why we don't support full edge left or > > right? In fact, I am wondering what's the difference between full edge > > left or right and full edge any direction? > > is part of optional feature G043, which we > don't claim to support. > Ok. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On 25.03.26 10:12, Ashutosh Bapat wrote: > On Wed, Mar 25, 2026 at 2:27 PM Peter Eisentraut wrote: >> >> On 23.03.26 16:00, Ashutosh Bapat wrote: >>> An empty pattern has no label expression which is equivalent to >>> disjunction of all applicable labels. If we add an empty pattern in >>> the rewrite phase, we will require its label expression to be resolved >>> in the rewrite phase. Looking at the proposed changes for all >>> properties reference [1], I am moving towards resolving the label >>> expression in the transformation stage itself. So I think it's better >>> to add the implicit vertex patterns during the transformation stage to >>> be future proof. Rewriter should just then rewrite the patterns into >>> joins and unions. Your point is correct that the implicit vertex >>> should not be visible in view definition or deparsed query. For that I >>> have added a flag implicit to GraphElementPattern. >>> GraphElementPatterns with implicit = true are ignored by ruleutils. >>> Implemented it that way in the attached patch. >>> >>> Vertex patterns without an edge pattern in between are not supported >>> OTOH. Added an ereport for the same. >>> >>> I have also added a few tests. I didn't add queries with all the >>> patterns you mentioned above. I tested a few by hand and all of them >>> worked as expected. Can you please check? >> >> This functionality that you can leave off empty vertex patterns at the >> beginning and end is part of the optional feature G047, which we don't >> claim to support. So we should reject these path patterns. >> > > Thanks for the clarification. What about the implicit empty vertex > patterns in the middle of the path? Should we reject these path > patterns also? Yes, I think so. The specification of feature G047 is: "... in conforming SQL language, any shall be immediately preceded and followed by a ." So if you write () -[]-> -[]-> () then the first edge pattern is not followed immediately by a vertex pattern, and so it would be invalid without feature G047.
Re: SQL Property Graph Queries (SQL/PGQ)
On Wed, Mar 25, 2026 at 2:11 PM Peter Eisentraut wrote: > > On 20.03.26 14:42, Ashutosh Bapat wrote: > >> We should either: > >> > >> (1) Support G041 fully -- both directions. Junwang's patch handles > >> this cleanly with minimal code change, or > >> (2) Not support G041 -- reject all non-local element pattern > >> references, throwing an error for both directions. > >> > >> What do you think? > > > > We will support the cross variable references in future once we > > support more path patterns leading to a more mature code in that area. > > But it doesn't harm to support backward references which can be easily > > supported now. I don't see the code to do so getting disturbed as it > > matures. For the segmentation fault a simple fix to add graph_pattern > > suffices for now. Let's see if Peter has a different opinion. > > I think we should not allow non-local references in either direction > (until we implement feature G041), option 2 above. Allowing only > backward references seems kind of an arbitrary implementation artifact. > Sorry, I didn't explain well earlier. It isn't arbitrary. It mimics backward lateral references. Consider following query Query1 SELECT x1.a, g.* FROM x1, GRAPH_TABLE (myshop MATCH (x1 IS customers)-[IS customer_orders]->(o IS orders WHERE o.order_id = x1.a) COLUMNS (x1.name AS customer_name, x1.customer_id AS cid)) g; x1 is a table referenced in from clause as well as an element pattern variable in path pattern. If we don't allow backward (cross) referencing, x1.a in the element pattern o resolves to the table x1's column a, but x1.name resolves to element x1's property reference name. So within the same graph pattern x1 may get resolved to two different things, even though x1 was declared before using it. Is that how we expect it to happen? Let's call this inconsistency1. However, if we allow backward references, we resolve x1 to the table column reference till the point where x1 appears in the path pattern and then onwards resolve x1 to the element pattern variable. So x1.a and x1.name are both resolved into a property of element x1. Ofc, in this example x1.a will result in an error since there is no property with name a in the property graph. But in case label "customers" also exposes property a, x1.a will be resolved to a property reference - applying resolution rule consistently everywhere. The behaviour remains consistent even with a forward reference like Query 2 SELECT x1.a, g.* FROM x1, GRAPH_TABLE (myshop MATCH (c IS customers WHERE c.address = 'US' AND c.customer_id = x1.a)-[IS customer_orders]->(x1 IS orders) COLUMNS (c.name AS customer_name, c.customer_id AS cid, x1.order_id)) g; x1 in element pattern c is resolved to table x1 since that's the only known resolution so far. x1.order_id however gets resolved to order_id property of label orders as by then there is a closer reference available. If we do not support backward references now, but start supporting it later, the Query 1's semantics will change, breaking backward compatibility. Let's call this "backward incompatibility 1". If we do not support forward element pattern references, that will be inline with the fact that we don't support forward lateral references. Those products which do not support lateral with graph_table don't have to worry about any of these problems when supporting cross element references. We have the following options 1. Don't support cross referencing element variables, but then we have "inconsistency1". 2. Support backward referencing element variables, with a risk of "backward incompatibility 1". I think the standard leaves room to not support forward referencing at all while supporting backward referencing 3. Support both backward and forward referencing now, with a risk that it may become a hurdle when we support more advanced features in graph pattern matching. Given that we are in an early phase of implementing PGQ query support, avoiding such hurdles is better. I am leaning towards 2 + not supporting forward referencing at all. But in the attached patchset I have implemented option 1 as you suggested. If you are fine with option 1, let's use that patch. On Wed, Mar 25, 2026 at 3:04 PM Peter Eisentraut wrote: > > On 25.03.26 10:12, Ashutosh Bapat wrote: > > On Wed, Mar 25, 2026 at 2:27 PM Peter Eisentraut wrote: > >> > >> This functionality that you can leave off empty vertex patterns at the > >> beginning and end is part of the optional feature G047, which we don't > >> claim to support. So we should reject these path patterns. > >> > > > > Thanks for the clarification. What about the implicit empty vertex > > patterns in the middle of the path? Should we reject these path > > patterns also? > Yes, I think so. > > The specification of feature G047 is: > > "... in conforming SQL language, any shall be immediately > preceded and followed by a ." > > So if you write > > () -[]-> -[]-> () > > then the first edge pattern is not followed immediately by a vertex > pattern, and so it would be invalid without feature G047. Implemented it this way in the attached patchset. 0001: is a small adjustment to make sure that we add an element variable name to the graph table namespace only once. This isn't a problem right now, but we will have to do that anyway in [1] and it has some effect one 0002. 0002: prohibits cross element variable references within graph_table clause. It adds a new member GraphTableParseState::cur_variable to track the variable name of the current pattern being transformed. We can not use llast() simply because a. pattern currently being transformed may not have name, so llast will be misleading b. changes in 0001. We may want to combine 0001 and 0002 when committing. 0003: prohibits consecutive element patterns of the same kind 0004: some cleanup remaining from 5282bf535e474dc2517f2e835d147420ae2144de. We may want to wait to accumulate more cleanups. [1] https://www.postgresql.org/message-id/CAExHW5tYCE9QyCvVraKUeesKW5RTR%2Bmrzsg3u64qSps-RPJR5A%40mail.gmail.com -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On 26.03.26 08:08, Ashutosh Bapat wrote: > Consider following query > Query1 > SELECT x1.a, g.* FROM x1, GRAPH_TABLE (myshop MATCH (x1 IS > customers)-[IS customer_orders]->(o IS orders WHERE o.order_id = x1.a) > COLUMNS (x1.name AS customer_name, x1.customer_id AS cid)) g; > > x1 is a table referenced in from clause as well as an element pattern > variable in path pattern. If we don't allow backward (cross) > referencing, x1.a in the element pattern o resolves to the table x1's > column a, but x1.name resolves to element x1's property reference > name. So within the same graph pattern x1 may get resolved to two > different things, even though x1 was declared before using it. Is that > how we expect it to happen? Let's call this inconsistency1. I don't think this interpretation is correct. Even if we don't support non-local element variable references, we still need to *recognize* them. We just don't need to be able to process them, we can error out if we see them. > 0001: is a small adjustment to make sure that we add an element > variable name to the graph table namespace only once. This isn't a > problem right now, but we will have to do that anyway in [1] and it > has some effect one 0002. committed > 0002: prohibits cross element variable references within graph_table > clause. It adds a new member GraphTableParseState::cur_variable to > track the variable name of the current pattern being transformed. We > can not use llast() simply because a. pattern currently being > transformed may not have name, so llast will be misleading b. changes > in 0001. We may want to combine 0001 and 0002 when committing. (under discussion) > 0003: prohibits consecutive element patterns of the same kind committed (I made the error message wording a bit more compact.) > 0004: some cleanup remaining from > 5282bf535e474dc2517f2e835d147420ae2144de. We may want to wait to > accumulate more cleanups. I don't think this patch goes into the right direction. The existing code seems preferable.
Re: SQL Property Graph Queries (SQL/PGQ)
On Fri, Mar 27, 2026 at 3:28 PM Peter Eisentraut wrote: > > On 26.03.26 08:08, Ashutosh Bapat wrote: > > Consider following query > > Query1 > > SELECT x1.a, g.* FROM x1, GRAPH_TABLE (myshop MATCH (x1 IS > > customers)-[IS customer_orders]->(o IS orders WHERE o.order_id = x1.a) > > COLUMNS (x1.name AS customer_name, x1.customer_id AS cid)) g; > > > > x1 is a table referenced in from clause as well as an element pattern > > variable in path pattern. If we don't allow backward (cross) > > referencing, x1.a in the element pattern o resolves to the table x1's > > column a, but x1.name resolves to element x1's property reference > > name. So within the same graph pattern x1 may get resolved to two > > different things, even though x1 was declared before using it. Is that > > how we expect it to happen? Let's call this inconsistency1. > > I don't think this interpretation is correct. > > Even if we don't support non-local element variable references, we still > need to *recognize* them. We just don't need to be able to process > them, we can error out if we see them. patch 0002 in the attached patchset implements it this way. It collects all the element variables before transforming the path pattern. Later it uses this list to detect non-local variable references and throws error. While implementing this I found another bug. In trasformColumnRef() we try to resolve the column ref as a table.column first which may resolve a property reference if a lateral table has the same name as the variable name and has a column with the same name as a property. Given that variables in the GRAPH_TABLE form the innermost namespace, we should try resolving the column reference as a property before lateral table reference. Since we do not allow subquery inside GRAPH_TABLE, there is no way a tables/columns/function will form the innermost namespace. The patch has a test demonstrating the bug and also the fix. Please let me know what you do you think of the fix. > > > 0001: is a small adjustment to make sure that we add an element > > variable name to the graph table namespace only once. This isn't a > > problem right now, but we will have to do that anyway in [1] and it > > has some effect one 0002. > > committed Thanks. > > > 0002: prohibits cross element variable references within graph_table > > clause. It adds a new member GraphTableParseState::cur_variable to > > track the variable name of the current pattern being transformed. We > > can not use llast() simply because a. pattern currently being > > transformed may not have name, so llast will be misleading b. changes > > in 0001. We may want to combine 0001 and 0002 when committing. > > (under discussion) > > > 0003: prohibits consecutive element patterns of the same kind > > committed (I made the error message wording a bit more compact.) That looks better. Thanks. > > > 0004: some cleanup remaining from > > 5282bf535e474dc2517f2e835d147420ae2144de. We may want to wait to > > accumulate more cleanups. > > I don't think this patch goes into the right direction. The existing > code seems preferable. > Removed from my patch set. -- Best Wishes, Ashutosh Bapat
Re: SQL Property Graph Queries (SQL/PGQ)
On Fri, Mar 27, 2026 at 9:47 PM Ashutosh Bapat
wrote:
>
> On Fri, Mar 27, 2026 at 3:28 PM Peter Eisentraut wrote:
> >
> > On 26.03.26 08:08, Ashutosh Bapat wrote:
> > > Consider following query
> > > Query1
> > > SELECT x1.a, g.* FROM x1, GRAPH_TABLE (myshop MATCH (x1 IS
> > > customers)-[IS customer_orders]->(o IS orders WHERE o.order_id = x1.a)
> > > COLUMNS (x1.name AS customer_name, x1.customer_id AS cid)) g;
> > >
> > > x1 is a table referenced in from clause as well as an element pattern
> > > variable in path pattern. If we don't allow backward (cross)
> > > referencing, x1.a in the element pattern o resolves to the table x1's
> > > column a, but x1.name resolves to element x1's property reference
> > > name. So within the same graph pattern x1 may get resolved to two
> > > different things, even though x1 was declared before using it. Is that
> > > how we expect it to happen? Let's call this inconsistency1.
> >
> > I don't think this interpretation is correct.
> >
> > Even if we don't support non-local element variable references, we still
> > need to *recognize* them. We just don't need to be able to process
> > them, we can error out if we see them.
>
> patch 0002 in the attached patchset implements it this way. It
> collects all the element variables before transforming the path
> pattern. Later it uses this list to detect non-local variable
> references and throws error.
Seeing the comment above transformGraphTablePropertyRef:
*
* A property reference is parsed as a ColumnRef of the form:
* .. If is one of the variables bound to an
* element pattern in the graph pattern and can be resolved as a
* property of the property graph, then we return a GraphPropertyRef node
it seems to imply that G041 is supported. Should we update this comment
to better reflect the current behavior?
>
> While implementing this I found another bug. In trasformColumnRef() we
> try to resolve the column ref as a table.column first which may
> resolve a property reference if a lateral table has the same name as
> the variable name and has a column with the same name as a property.
> Given that variables in the GRAPH_TABLE form the innermost namespace,
> we should try resolving the column reference as a property before
> lateral table reference. Since we do not allow subquery inside
> GRAPH_TABLE, there is no way a tables/columns/function will form the
> innermost namespace. The patch has a test demonstrating the bug and
> also the fix. Please let me know what you do you think of the fix.
I have a question about this. Why do we allow a ColumnRef to reference a
lateral table outside the graph pattern?
For example, in the following query:
SELECT x1.a, g.*
FROM x1,
GRAPH_TABLE (
myshop
MATCH (x1 IS customers WHERE address = 'US')
-[IS customer_orders]->(o IS orders)
COLUMNS (x1.name AS customer_name,
x1.customer_id AS cid,
o.order_id)
) g;
It’s easy for users to get confused and assume that `address` is a column
of customers rather than the outside x1.
>
> >
> > > 0001: is a small adjustment to make sure that we add an element
> > > variable name to the graph table namespace only once. This isn't a
> > > problem right now, but we will have to do that anyway in [1] and it
> > > has some effect one 0002.
> >
> > committed
>
> Thanks.
>
> >
> > > 0002: prohibits cross element variable references within graph_table
> > > clause. It adds a new member GraphTableParseState::cur_variable to
> > > track the variable name of the current pattern being transformed. We
> > > can not use llast() simply because a. pattern currently being
> > > transformed may not have name, so llast will be misleading b. changes
> > > in 0001. We may want to combine 0001 and 0002 when committing.
> >
> > (under discussion)
> >
> > > 0003: prohibits consecutive element patterns of the same kind
> >
> > committed (I made the error message wording a bit more compact.)
>
> That looks better. Thanks.
>
> >
> > > 0004: some cleanup remaining from
> > > 5282bf535e474dc2517f2e835d147420ae2144de. We may want to wait to
> > > accumulate more cleanups.
> >
> > I don't think this patch goes into the right direction. The existing
> > code seems preferable.
> >
>
> Removed from my patch set.
>
>
> --
> Best Wishes,
> Ashutosh Bapat
--
Regards
Junwang Zhao
Re: SQL Property Graph Queries (SQL/PGQ)
> patch 0002 in the attached patchset implements it this way. It
> collects all the element variables before transforming the path
> pattern. Later it uses this list to detect non-local variable
> references and throws error.
beyond the included regression tests. All non-local cross-references
are properly rejected across every combination I tried:
vertex <-> edge cross-references:
- vertex WHERE referencing a later edge (forward) -> ERROR
- vertex WHERE referencing an earlier edge (backward) -> ERROR
- edge WHERE referencing a later vertex (forward) -> ERROR
- edge WHERE referencing an earlier vertex (backward) -> ERROR
longer patterns ()-[]->()-[]->():
- 3rd vertex -> 1st vertex (long backward) -> ERROR
- 1st edge -> 3rd vertex (long forward) -> ERROR
- 2nd vertex -> 1st vertex (adjacent backward) -> ERROR
- 2nd vertex -> 3rd vertex (adjacent forward) -> ERROR
- 1st vertex -> 3rd vertex (long forward) -> ERROR
- all references local -> OK
All combinations -- vertex-vertex, vertex-edge, edge-vertex, adjacent
and long-distance -- are blocked as expected. Looks good.
Seeing the comment above transformGraphTablePropertyRef:
*
* A property reference is parsed as a ColumnRef of the form:
* <variable>.<property>. If <variable> is one of the variables bound to an
* element pattern in the graph pattern and <property> can be resolved as a
* property of the property graph, then we return a GraphPropertyRef node
it seems to imply that G041 is supported. Should we update this comment
to better reflect the current behavior?
non-local element variable references are now rejected.
I have a question about this. Why do we allow a ColumnRef to reference a
lateral table outside the graph pattern?
For example, in the following query:
SELECT x1.a, g.*
FROM x1,
GRAPH_TABLE (
myshop
MATCH (x1 IS customers WHERE address = 'US')
-[IS customer_orders]->(o IS orders)
COLUMNS (x1.name AS customer_name,
x1.customer_id AS cid,
o.order_id)
) g;
It’s easy for users to get confused and assume that `address` is a column
of customers rather than the outside x1.
GRAPH_TABLE has implicit LATERAL semantics per the SQL standard
(ISO/IEC 9075-16, Syntax Rule 5 of Subclause 7.6: <graph table derived
table> is added to the list of <table primary>s that support lateral
join), so referencing outer FROM items is expected behavior.
When the FROM table name doesn't conflict with an element variable,
lateral references work as expected:
SELECT x2.a, g.*
FROM x2,
GRAPH_TABLE (myshop
MATCH (c IS customers WHERE c.address = 'US'
AND c.customer_id = x2.a)
-[IS customer_orders]->(o IS orders)
COLUMNS (c.name AS customer_name,
c.customer_id AS cid, o.order_id)) g;
-- OK: x2.a resolves to lateral table x2
But when the same name is used for both (as in your example with x1),
qualified references are always captured by the element variable:
SELECT x1.a, g.*
FROM x1,
GRAPH_TABLE (myshop
MATCH (x1 IS customers WHERE x1.address = 'US')
-[IS customer_orders]->(o IS orders
WHERE o.order_id = x1.a)
COLUMNS (x1.name AS customer_name,
x1.customer_id AS cid, o.order_id)) g;
-- ERROR: non-local element variable reference is not supported
-- x1.a is recognized as element variable x1, not lateral table x1
I agree this can be a bit confusing for users, but given that PGQ is
still in its early stage, prioritizing stability seems reasonable
for now. This should be resolved once G041 support is added in the
future.
Best Regards,
Re: SQL Property Graph Queries (SQL/PGQ)
Hi Henson, On Sat, Mar 28, 2026 at 9:03 PM Henson Choi wrote: > > Hi Ashutosh and Junwang, > >> > patch 0002 in the attached patchset implements it this way. It >> > collects all the element variables before transforming the path >> > pattern. Later it uses this list to detect non-local variable >> > references and throws error. > > > I applied both patches (0001 and 0002) and ran some extended testing > beyond the included regression tests. All non-local cross-references > are properly rejected across every combination I tried: > > vertex <-> edge cross-references: > - vertex WHERE referencing a later edge (forward) -> ERROR > - vertex WHERE referencing an earlier edge (backward) -> ERROR > - edge WHERE referencing a later vertex (forward) -> ERROR > - edge WHERE referencing an earlier vertex (backward) -> ERROR > > longer patterns ()-[]->()-[]->(): > - 3rd vertex -> 1st vertex (long backward) -> ERROR > - 1st edge -> 3rd vertex (long forward) -> ERROR > - 2nd vertex -> 1st vertex (adjacent backward) -> ERROR > - 2nd vertex -> 3rd vertex (adjacent forward) -> ERROR > - 1st vertex -> 3rd vertex (long forward) -> ERROR > - all references local -> OK > > All combinations -- vertex-vertex, vertex-edge, edge-vertex, adjacent > and long-distance -- are blocked as expected. Looks good. > >> Seeing the comment above transformGraphTablePropertyRef: >> >> * >> * A property reference is parsed as a ColumnRef of the form: >> * .. If is one of the variables bound to an >> * element pattern in the graph pattern and can be resolved as a >> * property of the property graph, then we return a GraphPropertyRef node >> >> it seems to imply that G041 is supported. Should we update this comment >> to better reflect the current behavior? > > > Agreed, it would be nice to update the comment to reflect that > non-local element variable references are now rejected. > >> >> I have a question about this. Why do we allow a ColumnRef to reference a >> lateral table outside the graph pattern? >> >> For example, in the following query: >> >> SELECT x1.a, g.* >> FROM x1, >> GRAPH_TABLE ( >> myshop >> MATCH (x1 IS customers WHERE address = 'US') >> -[IS customer_orders]->(o IS orders) >> COLUMNS (x1.name AS customer_name, >> x1.customer_id AS cid, >> o.order_id) >> ) g; >> >> It’s easy for users to get confused and assume that `address` is a column >> of customers rather than the outside x1. > > > > > GRAPH_TABLE has implicit LATERAL semantics per the SQL standard > (ISO/IEC 9075-16, Syntax Rule 5 of Subclause 7.6: table> is added to the list of
Re: SQL Property Graph Queries (SQL/PGQ)
Okay, thanks for sharing this. My copy of SQL/PGQ seems
incomplete, it only includes subclauses 7.1 and 7.2 ;(
9075-16, which you already have. The first line of Section 7.1
says it modifies Subclause 7.6 ("<table reference>") of ISO/IEC
9075-2, and its Syntax Rule 1 augments SR 5 of that subclause
by adding <graph table derived table> to the list of <table
Re: SQL Property Graph Queries (SQL/PGQ)
On Sat, Mar 28, 2026 at 10:43 PM Henson Choi wrote:
>>
>> Okay, thanks for sharing this. My copy of SQL/PGQ seems
>> incomplete, it only includes subclauses 7.1 and 7.2 ;(
>
>
> To clarify: the lateral join rule is in Section 7.1 of ISO/IEC
> 9075-16, which you already have. The first line of Section 7.1
> says it modifies Subclause 7.6 ("Re: SQL Property Graph Queries (SQL/PGQ)
On Sat, Mar 28, 2026 at 6:33 PM Henson Choi wrote: > > Hi Ashutosh and Junwang, > >> > patch 0002 in the attached patchset implements it this way. It >> > collects all the element variables before transforming the path >> > pattern. Later it uses this list to detect non-local variable >> > references and throws error. > > > I applied both patches (0001 and 0002) and ran some extended testing > beyond the included regression tests. All non-local cross-references > are properly rejected across every combination I tried: > > vertex <-> edge cross-references: > - vertex WHERE referencing a later edge (forward) -> ERROR > - vertex WHERE referencing an earlier edge (backward) -> ERROR > - edge WHERE referencing a later vertex (forward) -> ERROR > - edge WHERE referencing an earlier vertex (backward) -> ERROR > > longer patterns ()-[]->()-[]->(): > - 3rd vertex -> 1st vertex (long backward) -> ERROR > - 1st edge -> 3rd vertex (long forward) -> ERROR > - 2nd vertex -> 1st vertex (adjacent backward) -> ERROR > - 2nd vertex -> 3rd vertex (adjacent forward) -> ERROR > - 1st vertex -> 3rd vertex (long forward) -> ERROR > - all references local -> OK > > All combinations -- vertex-vertex, vertex-edge, edge-vertex, adjacent > and long-distance -- are blocked as expected. Looks good. Thanks a lot for testing all these cases. Anything worth including in the graph_table.sql? I mean, we don't want to include tests which can be proved to be working (as expected) by induction e.g. If there's test testing a reference from element just before or after the current element, by induction it also tests references separated longer than that. It's good to make sure such cases work as expected once but testing them every time someone runs make check may not be worth it. But in case there's a non-trivial test, please provide a patch such that it uses existing property graphs and underlying tables. > >> Seeing the comment above transformGraphTablePropertyRef: >> >> * >> * A property reference is parsed as a ColumnRef of the form: >> * .. If is one of the variables bound to an >> * element pattern in the graph pattern and can be resolved as a >> * property of the property graph, then we return a GraphPropertyRef node >> >> it seems to imply that G041 is supported. Should we update this comment >> to better reflect the current behavior? > > > Agreed, it would be nice to update the comment to reflect that > non-local element variable references are now rejected. I am -0.1 on modifying the prologue since the comment in the function explains it. The prologue high level functionality - i.e. what constitutes a property reference, and how it's resolved, and what happens if it can not be resolved as a property reference. A cross reference case is a case where a reference can be resolved but we are choosing not to do so, temporarily. So, I think a comment within the function suffices. When we support cross reference, we remove the code and comment together without disturbing the prologue. However, I don't have a strong opinion here. > >> >> I have a question about this. Why do we allow a ColumnRef to reference a >> lateral table outside the graph pattern? >> >> For example, in the following query: >> >> SELECT x1.a, g.* >> FROM x1, >> GRAPH_TABLE ( >> myshop >> MATCH (x1 IS customers WHERE address = 'US') >> -[IS customer_orders]->(o IS orders) >> COLUMNS (x1.name AS customer_name, >> x1.customer_id AS cid, >> o.order_id) >> ) g; >> >> It’s easy for users to get confused and assume that `address` is a column >> of customers rather than the outside x1. > > > > > GRAPH_TABLE has implicit LATERAL semantics per the SQL standard > (ISO/IEC 9075-16, Syntax Rule 5 of Subclause 7.6: table> is added to the list of
Re: SQL Property Graph Queries (SQL/PGQ)
Thanks a lot for testing all these cases. Anything worth including in
the graph_table.sql?
proposal for regression test additions. I agree there's no reason to
include them in graph_table.sql -- adjacent element tests are
Re: SQL Property Graph Queries (SQL/PGQ)
On 27.03.26 14:47, Ashutosh Bapat wrote: > On Fri, Mar 27, 2026 at 3:28 PM Peter Eisentraut wrote: >> >> On 26.03.26 08:08, Ashutosh Bapat wrote: >>> Consider following query >>> Query1 >>> SELECT x1.a, g.* FROM x1, GRAPH_TABLE (myshop MATCH (x1 IS >>> customers)-[IS customer_orders]->(o IS orders WHERE o.order_id = x1.a) >>> COLUMNS (x1.name AS customer_name, x1.customer_id AS cid)) g; >>> >>> x1 is a table referenced in from clause as well as an element pattern >>> variable in path pattern. If we don't allow backward (cross) >>> referencing, x1.a in the element pattern o resolves to the table x1's >>> column a, but x1.name resolves to element x1's property reference >>> name. So within the same graph pattern x1 may get resolved to two >>> different things, even though x1 was declared before using it. Is that >>> how we expect it to happen? Let's call this inconsistency1. >> >> I don't think this interpretation is correct. >> >> Even if we don't support non-local element variable references, we still >> need to *recognize* them. We just don't need to be able to process >> them, we can error out if we see them. > > patch 0002 in the attached patchset implements it this way. It > collects all the element variables before transforming the path > pattern. Later it uses this list to detect non-local variable > references and throws error. > > While implementing this I found another bug. In trasformColumnRef() we > try to resolve the column ref as a table.column first which may > resolve a property reference if a lateral table has the same name as > the variable name and has a column with the same name as a property. > Given that variables in the GRAPH_TABLE form the innermost namespace, > we should try resolving the column reference as a property before > lateral table reference. Since we do not allow subquery inside > GRAPH_TABLE, there is no way a tables/columns/function will form the > innermost namespace. The patch has a test demonstrating the bug and > also the fix. Please let me know what you do you think of the fix. both committed