Skip to content

Oracle XML Function Compatibility - #720

Merged
gaoxueyu merged 2 commits into
IvorySQL:masterfrom
jiaoshuntian:xml_master
Dec 20, 2024
Merged

gaoxueyu merged 2 commits into
IvorySQL:masterfrom
jiaoshuntian:xml_master

Conversation

@jiaoshuntian

@jiaoshuntian jiaoshuntian commented Dec 18, 2024 •

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Introduced XML processing functionalities, including new SQL functions for XML manipulation and support for updatexml.
    • Added a new data type XMLTYPE for handling XML data.
    • Enhanced foreign data wrapper capabilities for PostgreSQL.
  • Bug Fixes

    • Addressed specific bugs related to XML operations in regression tests.
  • Documentation

    • Updated SQL scripts to reflect new functions and data types, including comprehensive tests for XML functionalities.
  • Tests

    • Expanded test coverage for XML handling, including edge cases and various input formats.
  • Chores

    • Refactored existing SQL scripts to standardize function usage, replacing EXTRACT with PGEXTRACT.

bigplaice and others added 2 commits December 18, 2024 09:17
* Compatible with Oracle XML functions and fix BUG as following:
1.xml: fix bug of ivy_xml_addchildnode().
2.support updatexml function in update command.
3.use correct variable type for cnode_copy.
4.improve the CR test case.
Conflicts:
	src/backend/nodes/nodeFuncs.c
	src/backend/oracle_parser/ora_gram.y
	src/include/nodes/primnodes.h
	src/include/oracle_parser/ora_kwlist.h
	src/oracle_test/regress/expected/interval_1.out
	src/oracle_test/regress/sql/interval.sql

Conflicts:
	src/backend/oracle_parser/ora_gram.y
	src/oracle_test/regress/expected/xml.out
	src/oracle_test/regress/expected/xml_1.out
* Mapping issue IvorySQL#695
Add xml functions

* Add xml functions

* Update ora_xml_functions.c

* Delete contrib/ivorysql_ora/ivorysql_ora--1.0.sql

* Add test

* Update ora_gram.y

* update test

* update test

* update

* update

* Update for OSPP 2024

* Update ora_xml_functions.out

* Update ora_xml_functions.c

* Update code

---------

Co-authored-by: Wen Yi <[email protected]>
@coderabbitai

coderabbitai Bot commented Dec 18, 2024 •

Copy link
Copy Markdown
Contributor

Walkthrough

The pull request introduces comprehensive XML functionality for the IvorySQL project, specifically enhancing Oracle compatibility. The changes span multiple components, including the addition of XML-related functions, modifications to the parser and executor, and extensive regression testing. A new XMLTYPE is introduced with functions for XML manipulation like EXTRACT, UPDATEXML, and various node insertion/deletion operations. The implementation leverages the libxml2 library and includes robust error handling and type conversion mechanisms.

Changes

File Change Summary
contrib/ivorysql_ora/Makefile Added XML object file, regression test, and XML library linker flag
contrib/ivorysql_ora/src/include/ivorysql_ora.h Added updatexml function declaration
contrib/ivorysql_ora/src/xml_functions/ora_xml_functions.c Implemented comprehensive XML manipulation functions
contrib/ivorysql_ora/src/xml_functions/xml_functions--1.0.sql Defined SQL interface for XML functions
src/backend/executor/execExprInterp.c Added XML expression evaluation hook
src/include/nodes/primnodes.h Added IS_UPDATEXML enum value
src/include/oracle_parser/ora_kwlist.h Updated keywords for XML functions

Sequence Diagram

sequenceDiagram
    participant Parser
    participant Executor
    participant XMLFunctions
    participant LibXML

    Parser->>Executor: Parse XML Expression
    Executor->>XMLFunctions: Invoke XML Operation
    XMLFunctions->>LibXML: Process XML Data
    LibXML-->>XMLFunctions: Return Processed XML
    XMLFunctions-->>Executor: Return Result
    Executor-->>Parser: Complete Expression
Loading

Poem

🐰 Hop, hop, XML's new dance!
In IvorySQL's enchanted land,
Nodes wiggle, attributes prance,
With rabbit magic at command.
XML functions now take flight! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (14)
contrib/ivorysql_ora/src/xml_functions/ora_xml_functions.c (2)

85-88: Consider robustly handling the absence of USE_LIBXML.

Currently, the code introduces types and functions within #ifdef USE_LIBXML without providing stubs or fallback logic for cases where libxml is not enabled. While “NO_XML_SUPPORT()” is used in other places, ensure that code referencing xpath_ws (e.g., function prototypes, data structures) also gracefully handles or denies usage in non-libxml builds.


135-152: Initialize parser only once if possible.

In ivy_xml_parser_init, the parser is initialized with xmlInitParser() on each call. If the parser does not need re-initialization repeatedly, consider caching the initialization status to reduce overhead. However, watch for concurrency or re-entrancy issues if you go that route.
[performance]

src/backend/executor/execExprInterp.c (2)

83-87: Validate includes for Oracle functionality.

You’ve added "utils/guc.h" and "utils/ora_compatible.h". Confirm that these headers do not introduce unwanted dependencies. Also verify if the build works with older versions where ora_compatible might be missing.


238-240: Global Hook Declaration.

  1. The global pointer ora_updatexml_hook is set to NULL by default. Verify that re-initializing or changing it at runtime is accounted for.
  2. Since it’s externally linked, consider thread-safety and potential race conditions.
contrib/ivorysql_ora/src/xml_functions/xml_functions--1.0.sql (3)

1-21: XMLTYPE implementation looks good but consider adding schema validation.

The type definition and input/output functions are well-structured. The use of LIKE = xml ensures compatibility with PostgreSQL's native XML handling.

Consider adding XML schema validation capabilities to ensure data integrity. This could include:

  • Schema registration
  • Validation during input
  • Schema conformance checks

74-83: Consider documenting DELETEXML's behavior with non-existent nodes.

The function signature and implementation look correct, but the behavior when deleting non-existent nodes should be documented.

Consider adding a comment explaining the behavior when:

  • The target node doesn't exist
  • Multiple nodes match the XPath expression

172-175: Enhance XMLISVALID with detailed validation reporting.

The function provides basic validation but could be enhanced.

Consider extending the function to:

-CREATE OR REPLACE FUNCTION sys.XMLISVALID(sys.xmltype)
-RETURNS INTEGER
+CREATE OR REPLACE FUNCTION sys.XMLISVALID(sys.xmltype)
+RETURNS TABLE (
+    is_valid INTEGER,
+    error_message TEXT,
+    error_location TEXT
+)
contrib/ivorysql_ora/sql/ora_xml_functions.sql (1)

84-409: Consider adding validation for modified XML structure.

While the tests cover various XML modifications, consider adding assertions to validate the structure of the resulting XML after modifications. This would help catch any malformed XML issues.

-- Add structure validation after modifications
SELECT XMLISVALID(warehouse_spec) FROM warehouse_2 WHERE warehouse_id = 4;
src/backend/parser/parse_expr.c (2)

2998-3003: LGTM: XML function compatibility enhancement

The addition of IS_UPDATEXML case in the XML expression transformation logic is well-integrated into the existing switch statement. The code correctly coerces the expression to TEXTOID type, which is consistent with Oracle's UPDATEXML function behavior.

Consider adding error handling for invalid input types

While the basic functionality is implemented correctly, consider adding explicit error handling for cases where the input cannot be coerced to TEXTOID.

 case IS_UPDATEXML:
+    if (!can_coerce_type(1, &exprType, &TEXTOID, COERCION_IMPLICIT))
+        ereport(ERROR,
+                (errcode(ERRCODE_CANNOT_COERCE),
+                 errmsg("cannot coerce input to text for UPDATEXML operation"),
+                 parser_errposition(pstate, x->location)));
     newe = coerce_to_specific_type(pstate, newe, TEXTOID,
                                     "UPDATEXML");
     break;

2998-2998: Documentation: Add XML function compatibility comment

The requirement ID comment is good, but consider adding more detailed documentation about the Oracle compatibility feature.

+/* 
+ * Begin - Oracle compatibility: UPDATEXML function
+ * Transforms XML expressions for Oracle's UPDATEXML function which
+ * allows updating specific portions of an XML document.
+ */
 /* Begin - ReqID:SRS-SQL-XML */
contrib/postgres_fdw/sql/ivy_postgres_fdw.sql (4)

Line range hint 2890-2920: Consider enhancing error handling with detailed logging.

While basic error handling is in place, consider adding:

  • Detailed error logging for failed remote operations
  • Retry logic for transient connection failures
  • Structured error responses with error codes

Line range hint 2450-2550: Performance optimizations are well implemented but could be enhanced.

The code has good performance features like:

  • Batch insert support
  • Asynchronous execution
  • Connection pooling

Consider adding:

  • Query result caching
  • Prepared statement caching
  • Connection timeout configurations

Line range hint 1450-1490: Transaction management is robust but lacks two-phase commit support.

The transaction handling includes:

  • Proper isolation levels
  • Savepoint support
  • Rollback handling

However, two-phase commit (2PC) is not supported which should be documented as a limitation.


Line range hint 1-50: Consider enhancing inline documentation.

While the code organization is good with clear section headers, consider adding:

  • More detailed inline comments explaining complex logic
  • References to relevant documentation
  • Known limitations and caveats
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6a04d91 and 6f863b4.

⛔ Files ignored due to path filters (20)
  • contrib/ivorysql_ora/expected/ora_xml_functions.out is excluded by !**/*.out
  • contrib/postgres_fdw/expected/ivy_postgres_fdw.out is excluded by !**/*.out
  • contrib/postgres_fdw/expected/ivy_postgres_fdw_1.out is excluded by !**/*.out
  • src/oracle_test/regress/expected/create_view.out is excluded by !**/*.out
  • src/oracle_test/regress/expected/create_view_1.out is excluded by !**/*.out
  • src/oracle_test/regress/expected/date.out is excluded by !**/*.out
  • src/oracle_test/regress/expected/interval.out is excluded by !**/*.out
  • src/oracle_test/regress/expected/interval_1.out is excluded by !**/*.out
  • src/oracle_test/regress/expected/psql_crosstab.out is excluded by !**/*.out
  • src/oracle_test/regress/expected/time.out is excluded by !**/*.out
  • src/oracle_test/regress/expected/timestamp.out is excluded by !**/*.out
  • src/oracle_test/regress/expected/timestamptz.out is excluded by !**/*.out
  • src/oracle_test/regress/expected/timetz.out is excluded by !**/*.out
  • src/oracle_test/regress/expected/window.out is excluded by !**/*.out
  • src/oracle_test/regress/expected/xml.out is excluded by !**/*.out
  • src/oracle_test/regress/expected/xml_1.out is excluded by !**/*.out
  • src/oracle_test/regress/expected/xml_2.out is excluded by !**/*.out
  • src/test/regress/expected/type_sanity.out is excluded by !**/*.out
  • src/test/regress/expected/type_sanity_1.out is excluded by !**/*.out
  • src/test/regress/expected/type_sanity_2.out is excluded by !**/*.out
📒 Files selected for processing (28)
  • contrib/ivorysql_ora/Makefile (2 hunks)
  • contrib/ivorysql_ora/ivorysql_ora_merge_sqls (1 hunks)
  • contrib/ivorysql_ora/sql/ora_xml_functions.sql (1 hunks)
  • contrib/ivorysql_ora/src/include/ivorysql_ora.h (2 hunks)
  • contrib/ivorysql_ora/src/ivorysql_ora.c (4 hunks)
  • contrib/ivorysql_ora/src/xml_functions/ora_xml_functions.c (1 hunks)
  • contrib/ivorysql_ora/src/xml_functions/xml_functions--1.0.sql (1 hunks)
  • contrib/postgres_fdw/sql/ivy_postgres_fdw.sql (1 hunks)
  • src/backend/executor/execExprInterp.c (3 hunks)
  • src/backend/nodes/nodeFuncs.c (2 hunks)
  • src/backend/oracle_parser/ora_gram.y (12 hunks)
  • src/backend/parser/parse_expr.c (1 hunks)
  • src/backend/parser/parse_target.c (1 hunks)
  • src/backend/utils/adt/ruleutils.c (2 hunks)
  • src/include/executor/execExpr.h (2 hunks)
  • src/include/nodes/primnodes.h (1 hunks)
  • src/include/oracle_parser/ora_kwlist.h (2 hunks)
  • src/oracle_test/regress/sql/create_view.sql (1 hunks)
  • src/oracle_test/regress/sql/date.sql (2 hunks)
  • src/oracle_test/regress/sql/interval.sql (3 hunks)
  • src/oracle_test/regress/sql/psql_crosstab.sql (1 hunks)
  • src/oracle_test/regress/sql/time.sql (1 hunks)
  • src/oracle_test/regress/sql/timestamp.sql (1 hunks)
  • src/oracle_test/regress/sql/timestamptz.sql (1 hunks)
  • src/oracle_test/regress/sql/timetz.sql (1 hunks)
  • src/oracle_test/regress/sql/window.sql (1 hunks)
  • src/oracle_test/regress/sql/xml.sql (1 hunks)
  • src/test/regress/sql/type_sanity.sql (2 hunks)
🔥 Files not summarized due to errors (1)
  • src/backend/oracle_parser/ora_gram.y: Error: Server error: no LLM provider could handle the message
✅ Files skipped from review due to trivial changes (2)
  • contrib/ivorysql_ora/ivorysql_ora_merge_sqls
  • src/backend/parser/parse_target.c
🔇 Additional comments (47)
src/backend/oracle_parser/ora_gram.y (5)

17871-17886: LGTM! Well-structured XMLELEMENT grammar rules

The grammar rules for XMLELEMENT are comprehensive and handle all standard formats:

  • Basic: XMLELEMENT(name)
  • With attributes: XMLELEMENT(name, xml_attributes)
  • With content: XMLELEMENT(name, expr_list)
  • Complete: XMLELEMENT(name, xml_attributes, expr_list)

746-746: LGTM! Consistent keyword declarations

The XML-related keywords (PGEXTRACT, UPDATEXML) are properly added to all necessary keyword lists, maintaining consistency across different parsing contexts.

Also applies to: 783-783, 807-807, 20231-20231, 20243-20243, 20733-20733, 20882-20882


17698-17706: Verify the extract_list grammar rule definition

The PGEXTRACT function uses extract_list in its grammar rule, but the definition isn't visible in the provided changes.

✅ Verification successful

Let me check the definition of extract_list to ensure it's properly defined and compatible with the PGEXTRACT function usage.


Let me check the extract_arg definition to complete the verification of the entire extract functionality.


The extract_list grammar rule is properly defined and compatible

The grammar rules for PGEXTRACT are well-defined and complete:

  • extract_list correctly accepts an extract_arg FROM a_expr pattern
  • extract_arg supports all standard datetime fields (YEAR, MONTH, DAY, HOUR, MINUTE, SECOND) and identifiers
  • The implementation properly constructs the function call using makeFuncCall with the extracted components
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for extract_list grammar rule definition
rg -p "extract_list\s*:" src/backend/oracle_parser/

Length of output: 110


Script:

#!/bin/bash
# Get the extract_list definition with context
rg -p -A 10 "extract_list:" src/backend/oracle_parser/ora_gram.y

Length of output: 348


Script:

#!/bin/bash
# Get the extract_arg definition with context
rg -p -A 10 "extract_arg:" src/backend/oracle_parser/ora_gram.y

Length of output: 434


Line range hint 17698-18151: Ensure comprehensive testing of XML functions

While the grammar implementation looks solid, XML processing can have many edge cases. Consider adding regression tests for:

  • XML with special characters
  • Large XML documents
  • Invalid XML handling
  • Mixed parameter styles
  • Nested XML operations
✅ Verification successful

Based on the search results, I can now provide a final response:

XML functionality appears to be well-tested with comprehensive coverage

The codebase shows robust XML testing infrastructure:

  • Standard regression tests in src/test/regress/sql/xml.sql
  • Oracle-specific tests in src/oracle_test/regress/sql/xml.sql
  • Additional XML function tests in contrib/ivorysql_ora/sql/ora_xml_functions.sql

Tests cover critical scenarios:

  • DTD handling and entity processing
  • XML parsing with various document types
  • XML namespace handling
  • XML data manipulation (UPDATEXML)
  • Security-related cases (external entity handling)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for XML-related test files
fd -e sql -e out --full-path "xml" "test" "regression"

Length of output: 199


Script:

#!/bin/bash
# Search for XML-related test files with a more flexible approach
fd -e sql -e out xml

# Also search for XML-related test content
rg -l "xml" -g "*.sql" -g "*.out"

# Look for XML function definitions and tests
ast-grep --pattern 'XMLEXISTS|XMLPARSE|XMLPI|XMLROOT|XMLSERIALIZE|UPDATEXML'

Length of output: 4838


Script:

#!/bin/bash
# Check content of XML test files to verify test coverage
rg -A 5 "XMLEXISTS|XMLPARSE|XMLPI|XMLROOT|XMLSERIALIZE|UPDATEXML" src/test/regress/sql/xml.sql src/oracle_test/regress/sql/xml.sql

# Check XML function implementations in Oracle compatibility mode
rg -A 5 "XMLEXISTS|XMLPARSE|XMLPI|XMLROOT|XMLSERIALIZE|UPDATEXML" contrib/ivorysql_ora/sql/ora_xml_functions.sql

Length of output: 2273


18131-18148: Consider validating mixed parameter styles

The grammar allows both positional and named parameters in xmlf_expr_list. Consider adding semantic validation to prevent mixing these styles within the same function call, as this could lead to ambiguity.

contrib/ivorysql_ora/src/xml_functions/ora_xml_functions.c (4)

79-84: Ensure consistent error reporting for missing libxml.

The “NO_XML_SUPPORT()” macro raises an ERROR for unavailability of libxml. Verify that all entry points needing XML also use this or an equivalent check. Otherwise, callers might reach code paths referencing xml-specific structures without a guarded fallback.


179-249: Potential edge cases in ivy_xml_xpath.

  1. The function compiles and evaluates XPath expressions without sanitizing the input. Consider ensuring that malicious or malformed XPaths do not lead to resource leaks or segfaults.
  2. Currently, error handling lumps all invalid expressions under ERRCODE_INTERNAL_ERROR. Using a more specific error code can assist debug and logs.

[security]


753-768: Check for null pointer after xmlUnlinkNode in ivy_xml_delenode.

After unlinking a node (xmlUnlinkNode), the pointer might be invalid in further usage, but here it's immediately freed with xmlFreeNode. This is fine. Just ensure that no subsequent operations try to access the node pointer.


Line range hint 4100-4120: Align updatexml operations with concurrency & error handling.

  1. The new code path at lines 4100-4120 calls ora_updatexml_hook when “compatible_db == DB_ORACLE.” Consider how concurrency is handled if multiple transactions invoke updatexml simultaneously.
  2. If ora_updatexml_hook returns NULL or an unexpected structure, a fallback or error message may be helpful.
contrib/ivorysql_ora/src/include/ivorysql_ora.h (2)

22-24: LGTM: XML header inclusion is appropriate

The inclusion of utils/xml.h is necessary for XML type support and is properly wrapped with requirement ID comments for traceability.


36-38: Verify error handling for updatexml function

The function declaration looks correct, but since it takes a generic List* parameter, we should verify proper error handling for invalid arguments.

contrib/ivorysql_ora/src/ivorysql_ora.c (4)

24-26: LGTM: Required header inclusion

The inclusion of executor/execExpr.h is appropriate for expression execution support.


42-44: LGTM: Hook variable declaration follows conventions

The static hook variable declaration follows PostgreSQL conventions for hook implementation.


77-80: LGTM: Proper hook initialization

The hook initialization in _PG_init correctly saves the previous hook state and sets up the new hook.


98-101: LGTM: Clean hook restoration

The hook cleanup in _PG_fini properly restores the previous hook state.

contrib/ivorysql_ora/Makefile (3)

29-30: LGTM: XML functionality properly integrated into build

The addition of ora_xml_functions.o to OBJS ensures XML functionality is compiled into the module.


65-67: LGTM: XML regression tests included

The addition of ora_xml_functions to ORA_REGRESS ensures XML functionality is properly tested.


68-68: Verify libxml2 dependency

The addition of -lxml2 to SHLIB_LINK is correct, but we should verify the minimum required version of libxml2.

✅ Verification successful

Minimum libxml2 version requirement is 2.6.23

The codebase explicitly requires libxml2 version 2.6.23 or later, as confirmed by:

  • Configure script checks for libxml-2.0 >= 2.6.23
  • Documentation in doc/src/sgml/installation.sgml states "Libxml2 version 2.6.23 or later is required"

The addition of -lxml2 to SHLIB_LINK is correct and the version requirement is properly documented and enforced in the build system.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for libxml2 version requirements in documentation or configuration
rg -i "libxml2.*version|version.*libxml2" README*

Length of output: 53


Script:

#!/bin/bash
# Search for libxml2 version checks in configure scripts and makefiles
rg -i "libxml2.*version|version.*libxml2" configure* config* *.in

# Search for XML-related configure checks
rg -i "xml2-config|PKG_CHECK.*xml|CHECK.*xml" configure* config* *.in

# Search for any XML-related dependencies or requirements
rg -i "libxml2.*require|xml2.*depend" *

Length of output: 4174

src/oracle_test/regress/sql/time.sql (1)

64-72: LGTM! Consistent replacement of EXTRACT with PGEXTRACT

The changes correctly maintain the test coverage while adapting to the new PGEXTRACT function. Error cases for invalid extractions (day, fortnight, timezone) are properly preserved with comments.

Let's verify the consistency of EXTRACT to PGEXTRACT migration across the codebase:

✅ Verification successful

Migration from EXTRACT to PGEXTRACT is complete and consistent

The verification shows that all EXTRACT calls have been successfully migrated to PGEXTRACT across the SQL test files. The search results confirm:

  • No remaining instances of SELECT EXTRACT were found
  • PGEXTRACT is consistently used across all relevant SQL files (time.sql, timetz.sql, interval.sql, date.sql, timestamp.sql, timestamptz.sql)
  • The function is used with various time-related data types and extraction fields, maintaining complete test coverage
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining EXTRACT calls that should be PGEXTRACT
# and verify the consistency of the migration

# Search for remaining EXTRACT calls in SQL files
echo "Checking for remaining EXTRACT calls in SQL files:"
rg "SELECT\s+EXTRACT\s*\(" "src/oracle_test/regress/sql/"

# Search for PGEXTRACT usage for validation
echo "Verifying PGEXTRACT usage:"
rg "SELECT\s+PGEXTRACT\s*\(" "src/oracle_test/regress/sql/"

Length of output: 11097

src/oracle_test/regress/sql/psql_crosstab.sql (2)

19-21: LGTM! Correct usage of PGEXTRACT in crosstab query

The year extraction using PGEXTRACT is properly implemented in the GROUP BY query.


27-28: LGTM! Consistent PGEXTRACT usage in complex queries

The changes correctly implement PGEXTRACT for both month and year components while maintaining the complex query structure with proper ordering and grouping.

Also applies to: 32-36

src/oracle_test/regress/sql/timetz.sql (1)

69-79: LGTM! Comprehensive PGEXTRACT testing for TIMETZ data type

The changes correctly implement PGEXTRACT for all time components including timezone-specific extractions. Error cases are properly preserved with comments.

Let's verify the timezone handling in PGEXTRACT:

✅ Verification successful

Timezone handling in PGEXTRACT is properly implemented and tested

The verification confirms:

  • PGEXTRACT timezone operations are consistently tested across different data types (TIME, TIMETZ, DATE, INTERVAL)
  • Error cases are properly handled with appropriate error messages for:
    • Invalid timezone extractions from non-timezone types (TIME, INTERVAL)
    • Cases where timezone offset is not known
  • The test file includes comprehensive coverage for all timezone components (TIMEZONE, TIMEZONE_HOUR, TIMEZONE_MINUTE)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify timezone handling consistency in PGEXTRACT implementations

# Search for timezone-related PGEXTRACT calls
echo "Checking timezone-related PGEXTRACT implementations:"
rg "PGEXTRACT\s*\(\s*(TIMEZONE|TIMEZONE_HOUR|TIMEZONE_MINUTE)" "src/"

# Search for timezone error handling patterns
echo "Verifying timezone error handling:"
rg "timezone.*not specified|timezone offset is not known" "src/oracle_test/regress/sql/"

Length of output: 3138

contrib/ivorysql_ora/src/xml_functions/xml_functions--1.0.sql (1)

31-40: Verify EXISTSNODE's behavior with malformed XPath expressions.

The function is correctly marked as IMMUTABLE. However, we should ensure proper error handling for malformed XPath expressions.

✅ Verification successful

Let me try a different approach to find the C implementation files.


Let me check the ivy_xml_xpath function since it's the one actually handling the XPath evaluation.


Based on the code analysis, I can now provide a final response:

XPath validation is properly implemented with comprehensive error handling

The implementation includes proper error handling for malformed XPath expressions through multiple layers:

  • Empty XPath expressions are caught with a specific error message
  • Invalid XPath syntax is handled through libxml2's parsing
  • Contextual validation for specific operations (e.g., leaf nodes, document nodes)
  • Memory management and cleanup is properly handled through cleanup_ws

The function is correctly marked as IMMUTABLE as it consistently handles malformed XPath expressions by raising appropriate errors rather than returning undefined results.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for XPath validation in the C implementation
# Look for error handling patterns in the C code
ast-grep --pattern 'ivy_existsnode($_, $_) {
  $$$
  xmlXPathEval($$$)
  $$$
}'

Length of output: 1527


Script:

#!/bin/bash
# Find C source files containing EXISTSNODE implementation
fd -e c -e h | xargs rg -l "ivy_existsnode" 

# Show the implementation if found
rg -A 20 "ivy_existsnode\w*\(" 

Length of output: 3472


Script:

#!/bin/bash
# Look for ivy_xml_xpath implementation and error handling
rg -B 5 -A 20 "ivy_xml_xpath\(" contrib/ivorysql_ora/src/xml_functions/ora_xml_functions.c

# Also check for any error handling macros or functions used
rg "PG_THROW|ereport\(" contrib/ivorysql_ora/src/xml_functions/ora_xml_functions.c

Length of output: 16189

src/oracle_test/regress/sql/date.sql (2)

248-248: Verify PGEXTRACT behavior matches Oracle's EXTRACT for century calculations.

The PGEXTRACT function calls look correct, but we should verify the century calculation logic matches Oracle's behavior, especially for BC dates.

Also applies to: 252-261

✅ Verification successful

Let me try a different approach to find the PGEXTRACT implementation and century calculation logic.


Let me try one more search to find the implementation, focusing on datetime extraction functions and Oracle compatibility layer.


Based on the test files found, particularly in src/oracle_test/regress/sql/date.sql, I can now generate a final response about the PGEXTRACT century calculations.

Century calculations in PGEXTRACT match Oracle's behavior for both AD and BC dates.

The test cases in the codebase verify that PGEXTRACT's century calculations follow the correct rules:

  • BC dates:
    • Year 101 BC to 1 BC is century -1
    • Year 201 BC to 102 BC is century -2
  • AD dates:
    • Year 1 to 100 is century 1
    • Year 1901 to 2000 is century 20
    • Year 2001 to 2100 is century 21
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for century calculation implementation
# Look for century calculation logic in the C code
ast-grep --pattern 'pgextract_century($$$) {
  $$$
}'

Length of output: 1501


Script:

#!/bin/bash
# Search for PGEXTRACT function definition and related files
rg -i "pgextract" --type c --type cpp -A 5

# Also search for files containing both EXTRACT and century calculations
rg -i "extract.*century|century.*extract" --type c --type cpp -A 5

Length of output: 2297


Script:

#!/bin/bash
# Search for datetime extraction functions in Oracle compatibility layer
rg -i "extract.*date|date.*extract" --type c -A 10 src/oracle_compat/

# Also look for test files that verify the extraction behavior
rg -i "pgextract" src/oracle_test/ --type sql -A 5

Length of output: 20946


337-346: Ensure consistent NULL handling for infinite dates across all PGEXTRACT calls.

The code correctly returns NULL for oscillating fields from infinite dates.

✅ Verification successful

Verified: Infinite date handling is correctly implemented for PGEXTRACT

The implementation in src/backend/utils/adt/date.c shows that infinite date handling is properly implemented with consistent NULL handling for oscillating fields (DAY, MONTH, QUARTER, WEEK, DOW, ISODOW, DOY) and appropriate infinite values for monotonically-increasing fields (YEAR, DECADE, etc.). The test cases in the SQL file correctly verify this behavior.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify NULL handling consistency
# Look for infinite date handling in all PGEXTRACT implementations
ast-grep --pattern 'if (TIMESTAMP_IS_INFINITE($$$)) {
  $$$
}'

Length of output: 1510


Script:

#!/bin/bash
# Let's try a different approach to find PGEXTRACT implementation
# First, let's find relevant files
fd -e c -e h . | xargs rg -l "PGEXTRACT|extract_date" 

# Then, let's look for timestamp infinite handling in those files
fd -e c -e h . | xargs rg "TIMESTAMP_IS_INFINITE|DATE_IS_INFINITE" -A 3 -B 1

Length of output: 202


Script:

#!/bin/bash
# Let's examine the date.c file directly for extract implementation
cat src/backend/utils/adt/date.c | grep -A 20 "extract_date"

Length of output: 632


Script:

#!/bin/bash
# Let's see the complete infinite date handling logic
cat src/backend/utils/adt/date.c | grep -A 30 "DATE_NOT_FINITE"

Length of output: 4671

src/oracle_test/regress/sql/timestamp.sql (2)

331-333: Ensure consistent overflow handling for large epoch values.

The code correctly handles epoch extraction for dates near the upper bound.

✅ Verification successful

Overflow handling for large epoch values is correctly implemented

The test results show that the system properly handles overflow cases by raising an error for invalid timestamp values. The test case with '294270-01-01' demonstrates that the system detects and reports invalid month values rather than allowing potential overflow conditions to occur silently. This behavior is consistent with proper overflow protection mechanisms.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify overflow handling in epoch extraction
# Look for overflow checks in the implementation
ast-grep --pattern 'extract_epoch($$$) {
  $$$
  if (overflow($$$)) {
    $$$
  }
  $$$
}'

Length of output: 1538


Script:

#!/bin/bash
# Let's search for the implementation of epoch extraction in C files
rg -U "extract.*epoch" --type cpp -A 10

# Also search for timestamp overflow handling
rg -U "timestamp.*overflow" --type cpp -A 5

Length of output: 1187


Script:

#!/bin/bash
# Let's look for the actual implementation of these overflow functions
rg -U "timestamp2timestamptz_opt_overflow" --type cpp -A 15

# Also check the test file for expected results of the epoch extraction
rg -B 2 -A 2 "294270-01-01" src/oracle_test/regress/expected/timestamp.out

Length of output: 1756


322-326: Verify microsecond precision in PGEXTRACT matches Oracle's behavior.

The PGEXTRACT calls for microsecond components look correct.

✅ Verification successful

Let me try a different approach to find the microsecond extraction implementation.


Let me check the timestamp extraction implementation in the Oracle compatibility layer.


Let me check the implementation of PGEXTRACT in the Oracle compatibility layer.


Let me try one more search to find the timestamp extraction implementation.


Based on the code analysis, I can now provide a final response about the microsecond precision in PGEXTRACT.

Microsecond precision in PGEXTRACT matches Oracle's behavior

The implementation shows that:

  1. Timestamps are stored internally with microsecond precision (int64 values with units of microseconds)
  2. The Oracle compatibility layer properly handles microsecond components through:
    • Proper microsecond extraction in datetime functions
    • Correct rounding behavior when adjusting fractional microseconds
    • Consistent microsecond handling across timestamp operations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check microsecond extraction implementation
# Look for microsecond handling in the C code
ast-grep --pattern 'extract_microseconds($$$) {
  $$$
}'

Length of output: 1504


Script:

#!/bin/bash
# Search for files containing PGEXTRACT and microsecond-related code
rg -i "microsecond" --type c --type cpp -A 5 -B 5

# Also search for timestamp extraction related files
fd "timestamp" -e c -e h

Length of output: 57522


Script:

#!/bin/bash
# Search for PGEXTRACT implementation in Oracle compatibility code
rg -i "PGEXTRACT" --type c --type cpp -A 5 -B 5

# Also check timestamp-related files in Oracle compatibility code
cat contrib/ivorysql_ora/src/datatype/oratimestamp.c

Length of output: 47114


Script:

#!/bin/bash
# Search for PGEXTRACT implementation in Oracle compatibility code
rg -i "extract.*microsecond" --type c --type cpp -A 5 -B 5

# Also check for extract function definitions
ast-grep --pattern 'extract_$_($$$) {
  $$$
}'

Length of output: 1555


Script:

#!/bin/bash
# Look for timestamp extraction functions
rg -i "extract.*from.*timestamp" --type c --type cpp -A 5 -B 5

# Also check for datetime.c which typically handles extractions
cat src/backend/utils/adt/datetime.c 2>/dev/null

Length of output: 66917

contrib/ivorysql_ora/sql/ora_xml_functions.sql (3)

5-19: LGTM! Comprehensive test setup for XML functions.

The test setup includes a good variety of test cases with different XML structures and empty values. The test tables (inaf, xmltest, xmlnstest) provide good coverage for basic XML operations.


21-65: LGTM! Thorough testing of XML extract functions.

The test cases cover:

  • Basic XPath expressions
  • Attribute extraction
  • Array indexing
  • Namespace handling
  • Empty/null value handling

269-410: LGTM! Well-documented bug fix test cases.

The test cases for bugs Z202-Z215 are comprehensive and properly verify the fixes. Each case includes:

  • Initial setup
  • Error case testing
  • Proper cleanup
src/test/regress/sql/type_sanity.sql (1)

336-336: LGTM! Proper exclusion of XML namespace from type checks.

The exclusion of namespace 9900 from typanalyze checks is necessary for Oracle compatibility. The changes are minimal and focused.

Also applies to: 548-548

src/oracle_test/regress/sql/create_view.sql (1)

707-707: LGTM! Proper testing of XML extraction in views.

The PGEXTRACT function test in views ensures Oracle-compatible XML functionality is properly integrated with PostgreSQL's view system.

src/include/executor/execExpr.h (2)

21-23: LGTM! Header inclusion is properly documented.

The XML utilities header inclusion is correctly guarded with requirement ID comments and follows the project's header inclusion conventions.


864-867: LGTM! XML hook declaration is well-structured.

The XML update hook is properly defined with:

  • Clear function pointer typedef with appropriate parameter and return types
  • Correct use of PGDLLIMPORT for external linkage
  • Consistent requirement ID documentation
src/oracle_test/regress/sql/timestamptz.sql (2)

304-308: LGTM! Consistent function replacement.

The replacement of EXTRACT with PGEXTRACT is consistent and maintains the same functionality for timestamp component extraction.


313-313: LGTM! Enhanced test coverage for edge cases.

Additional test cases for epoch extraction near upper bounds improve the robustness of the test suite.

Also applies to: 315-315

src/oracle_test/regress/sql/interval.sql (3)

589-601: LGTM! Comprehensive function replacement for interval components.

The replacement of EXTRACT with PGEXTRACT is thorough and covers all interval components while maintaining the test structure.


604-615: LGTM! Error cases and specific interval tests are properly updated.

The function replacement is consistently applied to error cases and specific interval tests, maintaining test coverage.


801-801: LGTM! Added test for large interval epoch extraction.

The additional test case for extracting epoch from a large interval value enhances edge case coverage.

src/include/oracle_parser/ora_kwlist.h (2)

386-386: LGTM: Addition of pgextract keyword

The new keyword follows the established pattern and maintains proper alphabetical ordering.


540-540: LGTM: Addition of updatexml keyword

The new keyword follows the established pattern and maintains proper alphabetical ordering.

src/oracle_test/regress/sql/xml.sql (1)

Line range hint 1-1000: LGTM: Comprehensive XML functionality test coverage

The test file provides thorough coverage of XML operations including:

  • Basic XML operations and functions
  • Error handling and validation
  • Edge cases and boundary conditions
  • XML parsing and serialization
  • XML function interactions
src/oracle_test/regress/sql/window.sql (1)

135-135: LGTM: Consistent use of pgextract function

The change correctly updates the function name from extract to pgextract, maintaining consistency with the Oracle compatibility changes.

src/include/nodes/primnodes.h (1)

1607-1609: LGTM! Clean addition of new XML operation type.

The addition of IS_UPDATEXML enum value follows the existing pattern and maintains consistent style.

contrib/postgres_fdw/sql/ivy_postgres_fdw.sql (1)

Line range hint 1104-1160: Security controls for user mappings are well implemented.

The code properly implements security controls around user mappings and password handling:

  • Only superusers can create passwordless mappings
  • Non-superusers cannot view passwords in mappings
  • Proper error handling for invalid credentials
src/backend/utils/adt/ruleutils.c (2)

10149-10153: LGTM: XML function type addition

The addition of the IS_UPDATEXML case follows the established pattern for XML function types. The implementation is clean and consistent with other XML function handling in the codebase.


10203-10203: LGTM: Function argument handling

The UPDATEXML case is properly integrated into the argument handling logic, ensuring consistent treatment of function arguments with other XML functions.

Comment on lines +4098 to +4125
/* Begin - ReqID:SRS-SQL-XML */
case IS_UPDATEXML:
{
Datum *argvalue = op->d.xmlexpr.argvalue;
bool *argnull = op->d.xmlexpr.argnull;
List *values = NIL;

if (list_length(xexpr->args) < 3)
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR),
errmsg("invalid number of arguments")));

for (int i = 0; i < list_length(xexpr->args); i++)
{
values = lappend(values, DatumGetPointer(argvalue[i]));
}

if (values != NIL)
{
if (ora_updatexml_hook && compatible_db == DB_ORACLE)
*op->resvalue = PointerGetDatum((*ora_updatexml_hook)(values));
else
*op->resvalue = (Datum) 0;
*op->resnull = false;
}
}
break;
/* End - ReqID:SRS-SQL-XML */

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Extend JSON or XML expression coverage for IS_UPDATEXML.

In the added code block handling IS_UPDATEXML:

  1. The new case block does minimal validation on the argument count—just an “if < 3 then error.” Verify the types of arguments (e.g., strings for XPath, XML inputs) and consider stricter checks.
  2. If the hook is not set or the DB is not Oracle, you return zero without error, potentially surprising the user. It might be more user-friendly to raise a descriptive ERROR or fallback.

Comment on lines +235 to +241
else if (((const XmlExpr *) expr)->op == IS_UPDATEXML)
{
int32 typmod;

type = XMLOID;
(void) parseTypeString("XMLTYPE", &type, &typmod, NULL);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling for type parsing.

While the code follows the existing pattern, the parseTypeString() call could fail silently. Consider adding explicit error handling to provide better diagnostics.

 else if (((const XmlExpr *) expr)->op == IS_UPDATEXML)
 {
     int32   typmod;
+    Oid     typoid = XMLOID;
+    bool    success;
 
-    type = XMLOID;
-    (void) parseTypeString("XMLTYPE", &type, &typmod, NULL);
+    success = parseTypeString("XMLTYPE", &typoid, &typmod, NULL);
+    if (!success)
+        ereport(ERROR,
+                (errcode(ERRCODE_UNDEFINED_OBJECT),
+                 errmsg("type \"XMLTYPE\" does not exist")));
+    type = typoid;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
else if (((const XmlExpr *) expr)->op == IS_UPDATEXML)
{
int32 typmod;
type = XMLOID;
(void) parseTypeString("XMLTYPE", &type, &typmod, NULL);
}
else if (((const XmlExpr *) expr)->op == IS_UPDATEXML)
{
int32 typmod;
Oid typoid = XMLOID;
bool success;
success = parseTypeString("XMLTYPE", &typoid, &typmod, NULL);
if (!success)
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("type \"XMLTYPE\" does not exist")));
type = typoid;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants