Repository navigation
Callinto master - #935
Callinto master#935
Conversation
… psql and handle the reference of bind variables at the sql and plsql.
WalkthroughThis pull request extends IvorySQL with comprehensive CALL and DO statement support, introducing parameter-length metadata handling, host variable binding in psql, Oracle-compatible command parsing (VAR/EXECUTE), and new libpq API variants (Ivy*2 functions) for prepared statement execution. Includes grammar extensions, parameter typmod tracking, PL/iSQL inline compilation enhancements, and extensive test coverage across multiple regression test files. Changes
Sequence Diagram(s)sequenceDiagram
participant psql
participant parser as Oracle Parser
participant backend as Backend
participant plisql as PL/iSQL
participant executor as Executor
psql->>parser: EXECUTE stmt (rewritten to BEGIN...END)
activate parser
parser->>parser: Recognize PARAMSLENGTH, opt_do_from_where
parser->>parser: Create DoStmt with paramslen, do_from_call
parser-->>psql: DoStmt AST
deactivate parser
psql->>backend: BIND with host variables
activate backend
backend->>backend: dostmt_plength = dostmt->paramslen
backend->>backend: Validate param count matches length count
loop For each Oracle character type parameter
backend->>backend: Set ptypmod = length + VARHDRSZ
end
backend-->>psql: Bound parameters with typmod
deactivate backend
psql->>plisql: EXECUTE (inline code with do_from_call=true)
activate plisql
plisql->>plisql: plisql_compile_inline(..., do_from_call=true)
plisql->>plisql: Use ptypmod from ParamExternData for datatype
plisql->>plisql: Set function->do_from_call = true
plisql-->>psql: PLiSQL function object
deactivate plisql
psql->>executor: ExecuteDoStmt
activate executor
executor->>executor: Propagate do_from_call to InlineCodeBlock
executor->>plisql: Execute inline code
activate plisql
plisql->>plisql: resolve_type() with pstate->do_from_call
plisql->>plisql: Use COERCION_EXPLICIT for Oracle types
plisql-->>executor: Results
deactivate plisql
executor-->>psql: Output parameters
deactivate executor
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Areas requiring extra attention:
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 22
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (8)
src/bin/psql/variables.c (2)
743-767: Avoid leak and unnecessary round-trip: validate typmod before casting value.value is computed before length checks; early returns leak value and waste a server call.
Apply:
- char *value = valid_bind_variable_value(typoid, typmod, initval); + char *value = NULL; ... - if (typoid == ORACHARCHAROID || + if (typoid == ORACHARCHAROID || typoid == ORACHARBYTEOID || typoid == ORAVARCHARCHAROID || typoid == ORAVARCHARBYTEOID) { if (typmod - 4 < 1) ... if ((typoid == ORACHARCHAROID || typoid == ORACHARBYTEOID) && typmod - 4 > MaxOraCharLen) ... if ((typoid == ORAVARCHARCHAROID || typoid == ORAVARCHARBYTEOID) && typmod - 4 > MaxOraVarcharLen) ... } + /* Only now, after structural validation, coerce/validate the value */ + value = valid_bind_variable_value(typoid, typmod, initval);Also applies to: 774-780
869-876: Handle NULL PGresult in ListBindVariables().Guard against PQexec() returning NULL before dereferencing.
Apply:
- res = PQexec(pset.db, query->data); - if (PQresultStatus(res) == PGRES_TUPLES_OK && + res = PQexec(pset.db, query->data); + if (res && + PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1 && !PQgetisnull(res, 0, 0))Also applies to: 893-896
src/include/nodes/params.h (1)
92-101: ptypmod must be included in serialization and restoration to preserve per-parameter typmod across shared memory boundaries.The struct field addition is present, but critical gaps exist:
- SerializeParamList (src/backend/nodes/params.c:248–289) writes type OID and flags but omits ptypmod, causing data loss when parameters cross into parallel workers.
- RestoreParamList (src/backend/nodes/params.c:311–339) reads type OID and flags but never reads ptypmod; restored params revert to -1 (from makeParamList initialization).
- BuildParamLogString (src/backend/nodes/params.c:354–420) does not reference ptypmod when formatting parameter values for logs.
- copyParamList correctly copies ptypmod via struct assignment, so local parameter passing is unaffected.
Add ptypmod serialization/restoration immediately after pflags in both SerializeParamList and RestoreParamList. Update BuildParamLogString to include ptypmod in output if needed for diagnostics.
src/bin/psql/settings.h (1)
165-188: Add EXECUTE_RUN_PREPARE documentation to helpVariables().Core wiring is in place: field initialized (startup.c:205), hook registered (startup.c:1320-1322), and used in mainloop (mainloop.c:554). However,
\? variableshelp output is incomplete—EXECUTE_RUN_PREPARE is missing from the helpVariables() function (help.c:389-470). Add an entry describing its purpose and effect on query execution.src/interfaces/libpq/libpq-ivy.h (1)
22-26: Public header uses ‘bool’ without including <stdbool.h>.This will break consumers that include libpq-ivy.h without pulling PostgreSQL’s c.h. Add stdbool.
#include <stdio.h> #include "pg_config.h" #include "ivy_sema.h" #include "postgres_ext.h" +#include <stdbool.h>Also, please document ownership of HostVariable* memory (who allocates/frees hostvars[i].name and convertcall) since this is exposed in the public API.
Also applies to: 149-163
src/backend/oracle_parser/ora_gram.y (2)
10315-10335: Param modes and lengths: enforce invariants.
- Validate PARAMSLENGTH entries are non‑negative.
- Ensure the number of PARAMSLENGTH entries matches USING param count.
This prevents subtle runtime errors and clearer syntax diagnostics.
Apply these diffs:
@@ param_mode_item: opt_param_name param_mode { DefElem *def = makeDefElem($1, $2, @1); $$ = (Node *) def; } @@ -params_length_list: - SignedIconst - { - $$ = list_make1(makeInteger($1)); - } - | params_length_list ',' SignedIconst - { - $$ = lappend($1, makeInteger($3)); - } +params_length_list: + SignedIconst + { + if ($1 < 0) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("PARAMSLENGTH must be non-negative"), + parser_errposition(@1))); + $$ = list_make1(makeInteger($1)); + } + | params_length_list ',' SignedIconst + { + if ($3 < 0) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("PARAMSLENGTH must be non-negative"), + parser_errposition(@3))); + $$ = lappend($1, makeInteger($3)); + }And in the DO ... USING ... PARAMSLENGTH production:
@@ - | DO dostmt_opt_list USING param_mode_list PARAMSLENGTH params_length_list opt_do_from_where + | DO dostmt_opt_list USING param_mode_list PARAMSLENGTH params_length_list opt_do_from_where { DoStmt *n = makeNode(DoStmt); n->args = $2; n->paramsmode = $4; n->paramslen = $6; n->do_from_call = $7; + if (list_length($4) != list_length($6)) + ereport(ERROR, + (errcode(ERRCODE_SYNTAX_ERROR), + errmsg("PARAMSLENGTH count (%d) must match USING parameter count (%d)", + list_length($6), list_length($4)), + parser_errposition(@5))); determineLanguage(n->args); $$ = (Node *)n; }Also applies to: 10337-10346, 10348-10351
9431-9435: Add regression test cases for both '=' and ':=' in function argument defaults.The code change correctly uses
plassign_equalsto support both syntaxes. However, verification shows no existing tests cover the:=variant in CREATE FUNCTION DEFAULT clauses—only=is tested. Add test cases with both forms to prevent regressions on Oracle-compatible syntax.src/interfaces/libpq/ivy-exec.c (1)
3789-3815: Potential memory leak in quote doubling.The
newsqlbuffer allocated at line 3801 is freed at line 3814, but if any error occurs between these lines (e.g.,mallocfailure forquery),newsqlwill leak.Move the free closer to allocation or add error handling:
newsql = malloc(stmtHandle->query_len * 2); /* enough */ + if (!newsql) + { + snprintf(errmsg, size_error_buf, "%s", "failed to allocate memory"); + return 0; + } + ptr = newsql; while (stmtHandle->query[i] != '\0') { if (stmtHandle->query[i] == '\'') *ptr++ = stmtHandle->query[i]; *ptr++ = stmtHandle->query[i]; i++; } *ptr = '\0'; query_len = (stmtHandle->query_len * 2) + strlen("select * from get_parameter_description(") + 5; query = (char *) malloc(query_len); if (query == NULL) { + free(newsql); snprintf(errmsg, size_error_buf, "%s", "failed to allocate memory"); return 0; }
🧹 Nitpick comments (27)
src/oracle_test/regress/sql/plancache.sql (1)
5-5: Avoid test cross-talk: unset at end.Set at Line 5; consider unsetting to keep tests isolated.
Apply:
\set EXECUTE_RUN_PREPARE on ... reset ivorysql.enable_emptystring_to_null; +\\unset EXECUTE_RUN_PREPAREsrc/bin/psql/variables.c (1)
1076-1108: Public API returns internal mutable pointer.BindVariableExist exposes internal struct for external mutation. Prefer const-qualified accessor or a copy to preserve invariants.
Option: return const struct _variable *, or add getters for fields needed by callers.
src/bin/psql/psqlplusparse.y (3)
63-69: Remove unused TYPECAST token (or wire it up).Unused tokens can trigger warnings and drift. If not used by this grammar, drop it; otherwise, add productions.
593-604: yyerror no-op loses diagnostics; consider minimal forwarding.At least log the message in debug mode to aid troubleshooting; keep user-facing behavior unchanged if desired.
Example:
void psqlplus_yyerror(yyscan_t yyscanner, const char *message) { - /* do nothing */ + pg_log_debug("psqlplus parse error: %s", message); }
46-46: Name mismatch nit: psql_yysype field.Minor readability nit: psql_yysype looks like a typo of “yystype”. If feasible, rename to psql_yystype for consistency.
src/backend/utils/adt/rowtypes.c (2)
2111-2114: Prefer PG_GETARG_TEXT_PP and text_to_cstring for fewer detoasts.Slightly more idiomatic and avoids an extra copy before switching to multi-call ctx.
- Datum txt = PG_GETARG_DATUM(0); - char *sql = TextDatumGetCString(txt); + text *txt = PG_GETARG_TEXT_PP(0); + char *sql = text_to_cstring(txt);
2274-2304: Emission contract is clear (header row + params).Consider documenting that position=0 is a header row; positions 1..N are parameters. No functional change needed.
src/backend/parser/analyze.c (1)
3018-3037: Verify type-specific coercion logic and consider adding documentation.The conditional coercion introduces special handling for Oracle CHAR/VARCHAR types when invoked from a CALL statement. While the implementation preserves existing behavior for non-matching cases, the rationale for using
COERCION_EXPLICITfor these specific type pairs is not documented.Consider adding a comment explaining:
- Why these specific Oracle types require different coercion semantics
- What problem this solves in the CALL/DO from-call context
- Any relevant Oracle compatibility requirements
Additionally, the nested condition on lines 3018-3021 could be extracted to a helper function for improved readability:
static bool needs_explicit_coercion_for_call(Oid source_type, Oid target_type) { return ((source_type == ORACHARCHAROID || source_type == ORACHARBYTEOID) && (target_type == ORACHARCHAROID || target_type == ORACHARBYTEOID)) || (target_type == ORAVARCHARCHAROID || target_type == ORAVARCHARBYTEOID); }Can you confirm:
- The specific use case that requires COERCION_EXPLICIT for these Oracle types
- Whether this has been tested with existing PL/iSQL and PL/pgSQL code to ensure no regressions
- The expected behavior difference between COERCION_EXPLICIT and COERCION_PLPGSQL for these types
src/pl/plisql/src/plisql.h (1)
1319-1320: ABI/signature change rippleEnsure all call sites updated (pl_handler.c updated here). If this is part of a shared library interface, document the signature change in release notes.
src/interfaces/libpq/ivytest/testlibpq_call.c (3)
10-13: Remove duplicate include<string.h> is included twice. Safe to drop one.
63-81: Check return values from bind helpersIvybindOutParameterByPos returns status but is ignored. Check and abort on non-zero to avoid undefined behavior in later execute.
96-105: Error message wording and resource safety
- Message says PQexecPrepared; this path uses IvyexecPreparedStatement—update for clarity.
- On failure, ensure stmthandle is freed before exiting to avoid leaks.
src/pl/plisql/src/pl_exec.c (1)
2517-2524: Good fix to unwrap host vars for CALL→DO, but tidy the comment.Using ParseParamVariable(n) here correctly peels Relabel/IO wrappers so OUT/INOUT targets resolve to Param under DO-from-CALL inline blocks. Please remove the ambiguous “I’m not sure…” comment and state the intent.
Apply:
- /* - * I'm not sure if this is a bug, so I'm only temporarily - * fixing it for scenarios that I care about. - */ + /* Unwrap wrappers (Relabel/IO/ArrayCoerce) so CALL INTO host variables + * map to writable Params when the CALL is rewritten as an inline DO block. + * See ParseParamVariable() for supported node shapes. + */Based on learnings.
src/bin/psql/mainloop.c (1)
548-601: EXECUTE rewrite flow looks correct; minor robustness nit.Rewriting EXECUTE into “BEGIN … END;” and rescan is fine, and exec_dostmt gates the send at EOL. Consider trimming trailing whitespace before checking the last char for ‘;’ to avoid rare false negatives (e.g., a trailing space after semicolon).
- if (newline_buf->data[newline_buf->len - 1] != ';') + while (newline_buf->len > 0 && + isspace((unsigned char)newline_buf->data[newline_buf->len - 1])) + newline_buf->data[--newline_buf->len] = '\0'; + if (newline_buf->len == 0 || newline_buf->data[newline_buf->len - 1] != ';') appendPQExpBufferChar(newline_buf, ';');src/interfaces/libpq/libpq-ivy.h (1)
164-167: Ivyconnectdb2/Ivyfinish2 contract clarity.Since Ivyfinish2 doesn’t PQfinish(PGconn), clarify in a header comment that the caller retains ownership of the supplied PGconn and must close it separately.
src/interfaces/libpq/ivytest/testlibpqstmt2_call.c (1)
121-152: Initialize dtype (and related) in IvyBindOutInfo for clearer intent.The test currently leaves dtype/indicators defaulted via struct assignment. To avoid latent UB if these fields are read by assertion/printing paths, set dtype explicitly (e.g., VARCHAR/INT).
src/backend/parser/parse_param.c (1)
662-670: SQLSTATE choice for duplicate OUT binds.Using ERRCODE_AMBIGUOUS_PARAMETER works but is semantically off. Consider ERRCODE_SYNTAX_ERROR or a closer fit if available, to align with “output parameter cannot be a duplicate bind”.
src/interfaces/libpq/ivytest/testlibpq_prepare_call.c (2)
37-177: Deduplicate bind/execute boilerplate in tests.exec_prepare_func/proc share most of the flow. Consider extracting a small helper to allocate handles, bind (by name/pos), execute, and print, to keep tests concise.
Also applies to: 179-290
313-336: Check create errors for function/procedure.You immediately Ivyclear() after Ivyexec(). If creation fails, consider asserting PGRES_COMMAND_OK and exiting, to avoid cascading failures.
res = Ivyexec(conn, function_str1); -if (IvyresultStatus(res) != PGRES_COMMAND_OK) { fprintf(stderr, "create function failed\n"); Ivyclear(res); exit_nicely(conn); } +if (IvyresultStatus(res) != PGRES_COMMAND_OK) { fprintf(stderr, "create function failed\n"); Ivyclear(res); exit_nicely(conn); } Ivyclear(res);src/interfaces/libpq/ivytest/testlibpq.c (3)
49-53: Use fixed-width int32 for bound OUT parameters to avoid ABI/sizeof surprises.Binding with plain int risks sizeof(int) ≠ 4 on some targets. Prefer int32_t for buffers passed to IvybindOutParameterByPos.
Apply:
- int prestmt3_integer=0; - int prestmt3_name3=0; + int32_t prestmt3_integer = 0; + int32_t prestmt3_name3 = 0; char prestmt3_name32[256]; - int prestmt3_name33=0; + int32_t prestmt3_name33 = 0;And adjust the three bind sizes accordingly (see below).
277-279: Ensure size and byte order correctness for integer OUT binds.
- Pass sizeof(int32_t) to match the proposed int32_t buffers.
- Verify whether IvybindOutParameterByPos delivers integers in network or host byte order. You already use ntohl for name3_out but not for prestmt3_*; this inconsistency may print wrong values on big‑endian systems.
Apply:
- (void *) &prestmt3_integer, - sizeof(int), + (void *) &prestmt3_integer, + sizeof(int32_t),- (void *) &prestmt3_name3, - sizeof(int), + (void *) &prestmt3_name3, + sizeof(int32_t),- (void *) &prestmt3_name33, - sizeof(int), + (void *) &prestmt3_name33, + sizeof(int32_t),If Ivy returns network byte order here, convert on read:
prestmt3_integer = (int32_t) ntohl(prestmt3_integer); prestmt3_name3 = (int32_t) ntohl(prestmt3_name3); prestmt3_name33 = (int32_t) ntohl(prestmt3_name33);Would you confirm the binding’s byte order for OUT integers?
Also applies to: 291-293, 320-322
349-351: Format specifiers should match fixed-width types.If switching to int32_t, print with PRId32 to avoid UB.
Example:
- printf("anonymous: %d,%d,%s,%d\n", prestmt3_integer, prestmt3_name3, prestmt3_name32,prestmt3_name33); + printf("anonymous: %" PRId32 ",%" PRId32 ",%s,%" PRId32 "\n", + prestmt3_integer, prestmt3_name3, prestmt3_name32, prestmt3_name33);Add headers:
#include <stdint.h> #include <inttypes.h>src/backend/tcop/postgres.c (2)
1163-1168: Use FEATURE_NOT_SUPPORTED for simple-protocol CALL INTO, and reword slightly.ERRCODE_PROGRAM_LIMIT_EXCEEDED is misleading. Prefer ERRCODE_FEATURE_NOT_SUPPORTED.
- ereport(ERROR, - (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), - errmsg("Simple query protocol does not support CALL INTO stmt"))); + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("simple query protocol does not support CALL INTO")));
2147-2169: Confirm Oracle char/varchar typmod coverage is complete; NCHAR/NVARCHAR not supported.The code correctly handles all four defined Oracle character types (ORACHARCHAROID, ORACHARBYTEOID, ORAVARCHARCHAROID, ORAVARCHARBYTEOID). NCHAR/NVARCHAR types are not defined in the codebase, so no additional case coverage is needed.
The negative-value guard is a reasonable defensive improvement. If added, validate that
intVal(v) >= 0before theptypmodcalculation:+ Integer *v = (Integer *) list_nth(dostmt_plength, paramno); + int len = intVal(v); + if (len < 0) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("invalid parameter length for position %d", paramno + 1))); switch(ptype) { case ORACHARCHAROID: case ORACHARBYTEOID: case ORAVARCHARCHAROID: case ORAVARCHARBYTEOID: - /* Hard-code typmod for Oracle char/varchar types to avoid ArrayType construction */ - params->params[paramno].ptypmod = intVal(v) + VARHDRSZ; + /* typmod = declared length + VARHDRSZ (varlena header) */ + params->params[paramno].ptypmod = len + VARHDRSZ; break;src/bin/psql/common.c (2)
4021-4189: Good encoding-aware memory management.The function correctly uses
pg_encoding_max_lengthto calculate buffer sizes for character types (lines 4095-4109), which properly handles multi-byte encodings.Consider extracting type-to-size mapping logic.
The large switch statement (lines 4080-4124) could be extracted into a separate helper function for better readability and reusability:
static size_t get_bind_variable_size(Oid typoid, int typmod, int encoding);
3211-3305: Complex conditional logic for command status.The function has deeply nested conditionals (lines 3230-3247) checking for DO/CALL statements. Consider extracting this logic into a helper function:
static bool should_suppress_tuples_for_oracle(const char *cmdstatus, bool quiet, bool isoracall); static const char* get_oracle_status_message(const char *cmdstatus, bool quiet, bool isoracall);src/interfaces/libpq/ivy-exec.c (1)
1751-2018: Encoding-aware parameter length tracking is correct.The function properly calculates parameter lengths for character types using
pg_encoding_max_length(lines 1846-1859, 1936-1949), which correctly handles the difference between character and byte semantics in Oracle types.Consider documenting the paramslength clause format.
The
paramslengthclause appended to the query (lines 1822, 1888) is not standard SQL. Add a comment explaining its purpose and format for future maintainers.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (32)
contrib/file_fdw/expected/ivy_file_fdw.outis excluded by!**/*.outcontrib/pg_stat_statements/expected/ivy_squashing.outis excluded by!**/*.outcontrib/pg_stat_statements/expected/ivy_utility.outis excluded by!**/*.outcontrib/pg_stat_statements/expected/planning.outis excluded by!**/*.outcontrib/pg_stat_statements/expected/select.outis excluded by!**/*.outsrc/include/catalog/pg_proc.datis excluded by!**/*.datsrc/interfaces/libpq/ivytest/expected/testlibpq_call.outis excluded by!**/*.outsrc/interfaces/libpq/ivytest/expected/testlibpq_prepare_call.outis excluded by!**/*.outsrc/interfaces/libpq/ivytest/expected/testlibpq_prepare_plsql.outis excluded by!**/*.outsrc/interfaces/libpq/ivytest/expected/testlibpqstmt2_call.outis excluded by!**/*.outsrc/oracle_test/regress/expected/constraints.outis excluded by!**/*.outsrc/oracle_test/regress/expected/domain.outis excluded by!**/*.outsrc/oracle_test/regress/expected/functional_deps.outis excluded by!**/*.outsrc/oracle_test/regress/expected/functional_deps_1.outis excluded by!**/*.outsrc/oracle_test/regress/expected/invisible.outis excluded by!**/*.outsrc/oracle_test/regress/expected/join.outis excluded by!**/*.outsrc/oracle_test/regress/expected/ora_plisql.outis excluded by!**/*.outsrc/oracle_test/regress/expected/ora_psql.outis excluded by!**/*.outsrc/oracle_test/regress/expected/partition_prune.outis excluded by!**/*.outsrc/oracle_test/regress/expected/plancache.outis excluded by!**/*.outsrc/oracle_test/regress/expected/portals.outis excluded by!**/*.outsrc/oracle_test/regress/expected/prepare.outis excluded by!**/*.outsrc/oracle_test/regress/expected/psql.outis excluded by!**/*.outsrc/oracle_test/regress/expected/rowsecurity.outis excluded by!**/*.outsrc/oracle_test/regress/expected/select_parallel.outis excluded by!**/*.outsrc/oracle_test/regress/expected/select_views.outis excluded by!**/*.outsrc/oracle_test/regress/expected/transactions.outis excluded by!**/*.outsrc/oracle_test/regress/expected/updatable_views.outis excluded by!**/*.outsrc/oracle_test/regress/expected/xml.outis excluded by!**/*.outsrc/oracle_test/regress/expected/xml_1.outis excluded by!**/*.outsrc/oracle_test/regress/expected/xml_2.outis excluded by!**/*.outsrc/pl/plisql/src/expected/plisql_out_parameter.outis excluded by!**/*.out
📒 Files selected for processing (66)
contrib/file_fdw/sql/ivy_file_fdw.sql(1 hunks)contrib/ivorysql_ora/src/sysview/sysview--1.0.sql(1 hunks)contrib/pg_stat_statements/sql/ivy_squashing.sql(1 hunks)contrib/pg_stat_statements/sql/ivy_utility.sql(1 hunks)contrib/pg_stat_statements/sql/planning.sql(1 hunks)contrib/pg_stat_statements/sql/select.sql(1 hunks)src/backend/commands/functioncmds.c(1 hunks)src/backend/nodes/params.c(1 hunks)src/backend/oracle_parser/ora_gram.y(8 hunks)src/backend/parser/analyze.c(1 hunks)src/backend/parser/parse_param.c(6 hunks)src/backend/tcop/postgres.c(6 hunks)src/backend/utils/adt/rowtypes.c(5 hunks)src/backend/utils/fmgr/funcapi.c(1 hunks)src/bin/psql/common.c(4 hunks)src/bin/psql/common.h(2 hunks)src/bin/psql/mainloop.c(7 hunks)src/bin/psql/psqlplus.h(1 hunks)src/bin/psql/psqlplusparse.y(9 hunks)src/bin/psql/psqlplusscan.l(11 hunks)src/bin/psql/settings.h(1 hunks)src/bin/psql/startup.c(3 hunks)src/bin/psql/variables.c(3 hunks)src/bin/psql/variables.h(1 hunks)src/include/catalog/dependency.h(1 hunks)src/include/fe_utils/psqlscan_int.h(2 hunks)src/include/nodes/params.h(1 hunks)src/include/nodes/parsenodes.h(3 hunks)src/include/oracle_parser/ora_kwlist.h(1 hunks)src/include/parser/parse_node.h(1 hunks)src/include/parser/parse_param.h(1 hunks)src/interfaces/libpq/exports.txt(1 hunks)src/interfaces/libpq/ivy-exec.c(37 hunks)src/interfaces/libpq/ivytest/Makefile(1 hunks)src/interfaces/libpq/ivytest/regression.txt(1 hunks)src/interfaces/libpq/ivytest/testlibpq.c(7 hunks)src/interfaces/libpq/ivytest/testlibpq_call.c(1 hunks)src/interfaces/libpq/ivytest/testlibpq_prepare_call.c(1 hunks)src/interfaces/libpq/ivytest/testlibpq_prepare_plsql.c(1 hunks)src/interfaces/libpq/ivytest/testlibpqstmt2_call.c(1 hunks)src/interfaces/libpq/libpq-ivy.h(3 hunks)src/interfaces/libpq/meson.build(1 hunks)src/oracle_fe_utils/ora_psqlscan.l(6 hunks)src/oracle_test/regress/parallel_schedule(1 hunks)src/oracle_test/regress/sql/constraints.sql(1 hunks)src/oracle_test/regress/sql/domain.sql(1 hunks)src/oracle_test/regress/sql/functional_deps.sql(1 hunks)src/oracle_test/regress/sql/invisible.sql(1 hunks)src/oracle_test/regress/sql/join.sql(1 hunks)src/oracle_test/regress/sql/ora_plisql.sql(3 hunks)src/oracle_test/regress/sql/ora_psql.sql(3 hunks)src/oracle_test/regress/sql/partition_prune.sql(1 hunks)src/oracle_test/regress/sql/plancache.sql(1 hunks)src/oracle_test/regress/sql/portals.sql(1 hunks)src/oracle_test/regress/sql/prepare.sql(1 hunks)src/oracle_test/regress/sql/psql.sql(1 hunks)src/oracle_test/regress/sql/rowsecurity.sql(1 hunks)src/oracle_test/regress/sql/select_parallel.sql(1 hunks)src/oracle_test/regress/sql/select_views.sql(1 hunks)src/oracle_test/regress/sql/transactions.sql(1 hunks)src/oracle_test/regress/sql/updatable_views.sql(1 hunks)src/oracle_test/regress/sql/xml.sql(1 hunks)src/pl/plisql/src/pl_comp.c(4 hunks)src/pl/plisql/src/pl_exec.c(2 hunks)src/pl/plisql/src/pl_handler.c(3 hunks)src/pl/plisql/src/plisql.h(2 hunks)
🧰 Additional context used
🧬 Code graph analysis (18)
src/bin/psql/variables.h (1)
src/bin/psql/variables.c (1)
BindVariableExist(1080-1108)
src/include/parser/parse_param.h (1)
src/backend/parser/parse_param.c (1)
setdynamic_callparser(2617-2621)
src/backend/parser/analyze.c (1)
src/backend/parser/parse_coerce.c (1)
coerce_to_target_type(84-138)
src/interfaces/libpq/ivytest/testlibpqstmt2_call.c (1)
src/interfaces/libpq/ivy-exec.c (7)
Ivyfinish(943-973)Ivyexec(990-1023)Ivyclear(925-937)Ivyconnectdb(127-164)Ivystatus(978-985)IvyFreePreparedStatement(837-918)IvyexecPreparedStatement2(551-832)
src/bin/psql/startup.c (1)
src/bin/psql/variables.c (3)
SetVariable(493-589)ParseVariableBool(318-356)SetVariableHooks(607-662)
src/pl/plisql/src/pl_exec.c (2)
src/backend/parser/parse_param.c (1)
ParseParamVariable(437-470)src/backend/parser/parse_coerce.c (1)
coerce_to_target_type(84-138)
src/bin/psql/common.h (1)
src/bin/psql/common.c (3)
psqlplus_skip_space(3534-3588)get_hostvariables(3596-3684)SendQuery_PBE(3690-4014)
src/bin/psql/mainloop.c (1)
src/bin/psql/common.c (5)
psqlplus_skip_space(3534-3588)standard_strings(2601-2615)get_hostvariables(3596-3684)SendQuery_PBE(3690-4014)SendQuery(1210-1431)
src/backend/utils/adt/rowtypes.c (5)
src/backend/parser/parse_param.c (4)
backward_oraparam_stack(636-645)pop_oraparam_stack(593-621)set_ParseDynSql(2528-2532)calculate_oraparamname(2698-2716)src/backend/utils/mmgr/mcxt.c (2)
palloc(1320-1348)pstrdup(1702-1706)src/backend/utils/cache/syscache.c (2)
SearchSysCache1(220-229)ReleaseSysCache(268-272)src/backend/commands/extension.c (1)
extension_file_exists(2468-2522)src/backend/utils/fmgr/fmgr.c (1)
fmgr_info(129-133)
src/backend/tcop/postgres.c (2)
src/backend/utils/error/elog.c (2)
errcode(853-864)errmsg(1070-1086)src/include/nodes/pg_list.h (2)
list_length(151-155)list_nth(298-303)
src/backend/parser/parse_param.c (1)
src/backend/utils/error/elog.c (2)
errcode(853-864)errmsg(1070-1086)
src/pl/plisql/src/plisql.h (1)
src/pl/plisql/src/pl_comp.c (1)
plisql_compile_inline(1256-1481)
src/interfaces/libpq/ivytest/testlibpq_prepare_call.c (2)
src/interfaces/libpq/ivytest/testlibpq_call.c (2)
exit_nicely(27-32)exec_prepare_func(34-111)src/interfaces/libpq/ivy-exec.c (13)
Ivyfinish(943-973)IvyHandleAlloc(1149-1218)IvyFreeHandle(1223-1242)IvyStmtPrepare(1245-1279)IvyBindByName(2059-2165)IvyBindByPos(2024-2053)IvyStmtExecute(2171-2460)IvyresultStatus(1028-1035)Ivyclear(925-937)Ivyconnectdb(127-164)Ivystatus(978-985)IvyerrorMessage(1091-1098)Ivyexec(990-1023)
src/interfaces/libpq/ivytest/testlibpq_call.c (1)
src/interfaces/libpq/ivy-exec.c (10)
Ivyfinish(943-973)IvyCreatePreparedStatement(251-307)IvybindOutParameterByPos(1123-1144)IvyexecPreparedStatement(318-543)Ivyclear(925-937)IvyFreePreparedStatement(837-918)Ivyconnectdb(127-164)Ivystatus(978-985)IvyerrorMessage(1091-1098)Ivyexec(990-1023)
src/interfaces/libpq/libpq-ivy.h (1)
src/interfaces/libpq/ivy-exec.c (4)
Ivyconnectdb(127-164)Ivyconnectdb2(170-205)Ivyfinish2(210-240)IvyStmtExecute2(2475-2742)
src/bin/psql/common.c (7)
src/interfaces/libpq/fe-exec.c (11)
PQresultStatus(3407-3413)PQexec(2259-2267)PQntuples(3477-3483)PQclear(717-768)PQcmdStatus(3748-3754)PQoidValue(3789-3807)PQbinaryTuples(3493-3499)PQgetResult(2058-2215)PQfnumber(3585-3680)PQgetvalue(3872-3878)PQgetisnull(3897-3906)src/interfaces/libpq/fe-connect.c (3)
PQerrorMessage(7629-7644)PQtransactionStatus(7574-7582)PQclientEncoding(7719-7725)src/fe_utils/print.c (6)
disable_sigpipe_trap(3037-3043)ClosePager(3139-3158)PageOutput(3087-3132)printQuery(3547-3610)restore_sigpipe_trap(3060-3066)html_escaped_print(1950-1988)src/bin/psql/variables.c (3)
SetVariable(493-589)BindVariableExist(1080-1108)AssignBindVariable(974-1031)src/bin/psql/copy.c (2)
handleCopyOut(433-491)handleCopyIn(510-736)src/interfaces/libpq/ivy-exec.c (11)
Ivyconnectdb2(170-205)Ivystatus(978-985)IvyerrorMessage(1091-1098)Ivyfinish2(210-240)IvyHandleAlloc(1149-1218)IvyFreeHandle(1223-1242)IvyStmtPrepare(1245-1279)IvyBindByPos(2024-2053)IvyStmtExecute2(2475-2742)IvyresultStatus(1028-1035)Ivyclear(925-937)src/common/wchar.c (1)
pg_encoding_max_length(2301-2313)
src/interfaces/libpq/ivy-exec.c (3)
src/common/wchar.c (1)
pg_encoding_max_length(2301-2313)src/interfaces/libpq/fe-connect.c (1)
PQerrorMessage(7629-7644)src/interfaces/libpq/fe-exec.c (7)
PQexecStart(2341-2402)PQsendPrepare(1532-1622)PQexecFinish(2407-2437)PQresultStatus(3407-3413)PQclear(717-768)PQsendQueryPrepared(1629-1663)PQgetisnull(3897-3906)
src/pl/plisql/src/pl_handler.c (3)
src/pl/plisql/src/pl_comp.c (1)
plisql_compile_inline(1256-1481)src/include/utils/palloc.h (1)
MemoryContextSwitchTo(123-130)src/backend/utils/error/elog.c (4)
CopyErrorData(1750-1814)FlushErrorState(1871-1884)ThrowErrorData(1899-1948)FreeErrorData(1822-1827)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
- GitHub Check: oracle_pg_regression (ubuntu-latest)
- GitHub Check: contrib_regression
- GitHub Check: pg_regression (ubuntu-latest)
- GitHub Check: meson_build (ubuntu-latest)
- GitHub Check: oracle_regression (ubuntu-latest)
- GitHub Check: build (ubuntu-latest)
| decode(bitand(s.flags, 2048), 2048, 'Y', 'N') AS extend_flag,null AS shared_flag, | ||
| decode(bitand(s.flags, 64), 64, 'Y', 'N') AS session_flag,null AS keep_value | ||
| FROM PG_SEQUENCE s,pg_class c where s.seqrelid = c.oid and c.relowner::regrole = current_user::regrole; | ||
| FROM PG_SEQUENCE s,pg_class c where s.seqrelid = c.oid and pg_get_userbyid(c.relowner) = current_user; |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
🧩 Analysis chain
Inconsistent ownership filter patterns across USER_ views.*
The change to SYS.USER_SEQUENCES introduces pg_get_userbyid(c.relowner) = current_user, but SYS.USER_PROCEDURES (line 262) and SYS.USER_ARGUMENTS (line 1038) still use the older ::REGROLE pattern. This creates maintenance burden and semantic drift. Either all similar USER_* views should be updated consistently, or there should be documented rationale for the mixed approaches.
Additionally, line 1089 uses lowercase keywords/functions (where, and, pg_get_userbyid, current_user) which conflicts with the uppercase convention used elsewhere in the file (see line 1192: PG_GET_USERBYID(C.RELOWNER) = CURRENT_USER).
Please verify:
- Are
SYS.USER_PROCEDURESandSYS.USER_ARGUMENTSintended to remain using the::REGROLEpattern, or should they also be updated topg_get_userbyid()for consistency with this change? - Should line 1089 use uppercase keywords and function names to match the file's style conventions?
I'll verify the review comment by examining the actual file content to confirm the claimed inconsistencies.
🏁 Script executed:
#!/bin/bash
# Extract and examine ownership filter patterns at the claimed lines
echo "=== Line 262 (USER_PROCEDURES) ==="
sed -n '260,265p' contrib/ivorysql_ora/src/sysview/sysview--1.0.sql
echo ""
echo "=== Line 1038 (USER_ARGUMENTS) ==="
sed -n '1036,1041p' contrib/ivorysql_ora/src/sysview/sysview--1.0.sql
echo ""
echo "=== Line 1089 (USER_SEQUENCES) ==="
sed -n '1087,1092p' contrib/ivorysql_ora/src/sysview/sysview--1.0.sql
echo ""
echo "=== Line 1192 (USER_VIEWS) ==="
sed -n '1190,1195p' contrib/ivorysql_ora/src/sysview/sysview--1.0.sqlLength of output: 1015
🏁 Script executed:
#!/bin/bash
# Search for WHERE clauses in USER_* views to understand the full context
echo "=== Searching for ownership/relowner patterns in the file ==="
rg -n 'relowner|RELOWNER|::regrole|REGROLE|pg_get_userbyid|PG_GET_USERBYID' contrib/ivorysql_ora/src/sysview/sysview--1.0.sql -A 1 -B 1Length of output: 2494
🏁 Script executed:
#!/bin/bash
# Extract content around specified lines to verify the patterns claimed in review
echo "=== Line 262 context (USER_PROCEDURES) ==="
sed -n '255,270p' contrib/ivorysql_ora/src/sysview/sysview--1.0.sql
echo ""
echo "=== Line 1038 context (USER_ARGUMENTS) ==="
sed -n '1032,1048p' contrib/ivorysql_ora/src/sysview/sysview--1.0.sql
echo ""
echo "=== Line 1089 context (USER_SEQUENCES) ==="
sed -n '1082,1095p' contrib/ivorysql_ora/src/sysview/sysview--1.0.sql
echo ""
echo "=== Line 1192 context (USER_VIEWS) ==="
sed -n '1185,1200p' contrib/ivorysql_ora/src/sysview/sysview--1.0.sqlLength of output: 2088
🏁 Script executed:
#!/bin/bash
# Search for all ownership comparison patterns to identify inconsistencies
echo "=== All ownership filter patterns in file ==="
rg -n 'relowner|RELOWNER' contrib/ivorysql_ora/src/sysview/sysview--1.0.sql -C 2Length of output: 1542
Inconsistent ownership filter patterns and formatting across USER_ views require standardization.*
The change on line 1089 introduces pg_get_userbyid(c.relowner) = current_user, but this approach is inconsistently applied:
- USER_PROCEDURES (line 262), USER_ARGUMENTS (line 1038), and ALL_FUNCTIONS (line 407) still use
P.PROOWNER::REGROLE = CURRENT_USER::REGROLE - USER_SEQUENCES (line 1089) and USER_VIEWS (line 1192) use
pg_get_userbyid()
These patterns are semantically different (OID comparison vs. name-based comparison) and mixed usage creates maintenance burden. Additionally, line 1089 uses lowercase keywords/functions (where, and, pg_get_userbyid, current_user) conflicting with the file's uppercase convention used in line 1192 and throughout the file.
Either standardize all ownership filters to one approach, or document the rationale for mixed patterns. Ensure line 1089 formatting aligns with file conventions.
🤖 Prompt for AI Agents
In contrib/ivorysql_ora/src/sysview/sysview--1.0.sql around line 1089, the
ownership filter uses pg_get_userbyid(c.relowner) = current_user and lowercase
SQL which is inconsistent with other views that compare role OIDs (e.g.,
P.PROOWNER::REGROLE = CURRENT_USER::REGROLE) and the file's uppercase style;
replace the pg_get_userbyid-based comparison with the same OID/REGROLE
comparison used by USER_PROCEDURES/USER_ARGUMENTS/ALL_FUNCTIONS (e.g., use the
appropriate relation alias's owner cast to ::REGROLE compared to
CURRENT_USER::REGROLE) and update keywords/functions to uppercase to match file
conventions.
| if (dostmt->paramslen) | ||
| dostmt_plength = dostmt->paramslen; | ||
| } |
There was a problem hiding this comment.
Validate parameter-length list values.
You check list length matches numParams — good. Also guard against negative lengths early to avoid invalid typmods later.
- if (dostmt->paramslen)
- dostmt_plength = dostmt->paramslen;
+ if (dostmt->paramslen)
+ dostmt_plength = dostmt->paramslen;
...
- if (dostmt_plength != NIL && list_length(dostmt_plength) != numParams)
+ if (dostmt_plength != NIL && list_length(dostmt_plength) != numParams)
elog(ERROR, "the specified parameter length list does not match the number of parameters");
+ /* basic validation of individual lengths */
+ if (dostmt_plength != NIL)
+ {
+ for (int i = 0; i < numParams; i++)
+ {
+ Integer *iv = (Integer *) list_nth(dostmt_plength, i);
+ if (iv == NULL || intVal(iv) < 0)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("invalid parameter length for position %d", i + 1)));
+ }
+ }Also applies to: 1930-1933
🤖 Prompt for AI Agents
In src/backend/tcop/postgres.c around lines 1899-1901 (and similarly at
1930-1933), the current code only checks that the parameter-length list length
matches numParams but does not validate the individual length values; iterate
the parameter-length array and reject any invalid/negative length values early
(return an error or set a safe default) before they are used as typmods, and
apply the same validation at the second location (lines 1930-1933).
| /* | ||
| * If the guc pararmeter out_parameter_column_position is set to true, | ||
| * make out parameter column name to special, | ||
| * so we can distinguish it from the return value | ||
| */ |
There was a problem hiding this comment.
Fix typo in comment.
Line 2075 contains a typo: "pararmeter" should be "parameter".
Apply this diff to fix the typo:
/*
- * If the guc pararmeter out_parameter_column_position is set to true,
+ * If the guc parameter out_parameter_column_position is set to true,
* make out parameter column name to special,
* so we can distinguish it from the return value
*/📝 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.
| /* | |
| * If the guc pararmeter out_parameter_column_position is set to true, | |
| * make out parameter column name to special, | |
| * so we can distinguish it from the return value | |
| */ | |
| /* | |
| * If the guc parameter out_parameter_column_position is set to true, | |
| * make out parameter column name to special, | |
| * so we can distinguish it from the return value | |
| */ |
🤖 Prompt for AI Agents
In src/backend/utils/fmgr/funcapi.c around lines 2074 to 2078, there's a typo in
the comment: change "pararmeter" to "parameter" so the comment reads correctly;
update the comment text accordingly and ensure spelling is corrected without
altering surrounding formatting or punctuation.
There was a problem hiding this comment.
@OreoYang, thank you for confirming! The typo fix can be applied when you're ready to commit the changes. 👍
| static bool | ||
| IvyAcceptResult(const PGresult *result) | ||
| { | ||
| bool OK; | ||
|
|
||
| if (!result) | ||
| OK = false; | ||
| else | ||
| switch (PQresultStatus(result)) | ||
| { | ||
| case PGRES_COMMAND_OK: | ||
| case PGRES_TUPLES_OK: | ||
| case PGRES_EMPTY_QUERY: | ||
| case PGRES_COPY_IN: | ||
| case PGRES_COPY_OUT: | ||
| /* Fine, do nothing */ | ||
| OK = true; | ||
| break; | ||
|
|
||
| case PGRES_BAD_RESPONSE: | ||
| case PGRES_NONFATAL_ERROR: | ||
| case PGRES_FATAL_ERROR: | ||
| OK = false; | ||
| break; | ||
|
|
||
| default: | ||
| OK = false; | ||
| pg_log_error("unexpected PQresultStatus: %d", | ||
| PQresultStatus(result)); | ||
| break; | ||
| } | ||
|
|
||
| if (!OK) | ||
| { | ||
| const char *error = PQerrorMessage(pset.db); | ||
|
|
||
| if (strlen(error)) | ||
| pg_log_info("%s", error); | ||
|
|
||
| CheckConnection(); | ||
| } | ||
|
|
||
| return OK; | ||
| } |
There was a problem hiding this comment.
Missing status cases compared to AcceptResult.
IvyAcceptResult doesn't handle PGRES_TUPLES_CHUNK and PGRES_PIPELINE_SYNC status codes that are present in the original AcceptResult function (lines 520, 524). This inconsistency could cause issues if these statuses are encountered in Oracle mode.
Consider adding these cases:
case PGRES_EMPTY_QUERY:
case PGRES_COPY_IN:
case PGRES_COPY_OUT:
+ case PGRES_TUPLES_CHUNK:
+ case PGRES_PIPELINE_SYNC:
/* Fine, do nothing */
OK = true;
break;Code duplication with AcceptResult.
Consider refactoring AcceptResult to accept a parameter controlling error display behavior, rather than duplicating the entire function.
📝 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.
| static bool | |
| IvyAcceptResult(const PGresult *result) | |
| { | |
| bool OK; | |
| if (!result) | |
| OK = false; | |
| else | |
| switch (PQresultStatus(result)) | |
| { | |
| case PGRES_COMMAND_OK: | |
| case PGRES_TUPLES_OK: | |
| case PGRES_EMPTY_QUERY: | |
| case PGRES_COPY_IN: | |
| case PGRES_COPY_OUT: | |
| /* Fine, do nothing */ | |
| OK = true; | |
| break; | |
| case PGRES_BAD_RESPONSE: | |
| case PGRES_NONFATAL_ERROR: | |
| case PGRES_FATAL_ERROR: | |
| OK = false; | |
| break; | |
| default: | |
| OK = false; | |
| pg_log_error("unexpected PQresultStatus: %d", | |
| PQresultStatus(result)); | |
| break; | |
| } | |
| if (!OK) | |
| { | |
| const char *error = PQerrorMessage(pset.db); | |
| if (strlen(error)) | |
| pg_log_info("%s", error); | |
| CheckConnection(); | |
| } | |
| return OK; | |
| } | |
| static bool | |
| IvyAcceptResult(const PGresult *result) | |
| { | |
| bool OK; | |
| if (!result) | |
| OK = false; | |
| else | |
| switch (PQresultStatus(result)) | |
| { | |
| case PGRES_COMMAND_OK: | |
| case PGRES_TUPLES_OK: | |
| case PGRES_EMPTY_QUERY: | |
| case PGRES_COPY_IN: | |
| case PGRES_COPY_OUT: | |
| case PGRES_TUPLES_CHUNK: | |
| case PGRES_PIPELINE_SYNC: | |
| /* Fine, do nothing */ | |
| OK = true; | |
| break; | |
| case PGRES_BAD_RESPONSE: | |
| case PGRES_NONFATAL_ERROR: | |
| case PGRES_FATAL_ERROR: | |
| OK = false; | |
| break; | |
| default: | |
| OK = false; | |
| pg_log_error("unexpected PQresultStatus: %d", | |
| PQresultStatus(result)); | |
| break; | |
| } | |
| if (!OK) | |
| { | |
| const char *error = PQerrorMessage(pset.db); | |
| if (strlen(error)) | |
| pg_log_info("%s", error); | |
| CheckConnection(); | |
| } | |
| return OK; | |
| } |
🤖 Prompt for AI Agents
In src/bin/psql/common.c around lines 2787 to 2830, IvyAcceptResult is missing
handling for PGRES_TUPLES_CHUNK and PGRES_PIPELINE_SYNC (present in
AcceptResult) and duplicates AcceptResult logic; update IvyAcceptResult to
include case labels for PGRES_TUPLES_CHUNK and PGRES_PIPELINE_SYNC so those
statuses are treated as OK, and refactor by consolidating AcceptResult and
IvyAcceptResult into a single function that accepts a flag (e.g., show_error or
use_pset_db) to control whether to fetch/log PQerrorMessage and call
CheckConnection, replacing duplicated bodies with calls to this shared function.
| HostVariable * | ||
| get_hostvariables(const char *sql, bool *error) | ||
| { | ||
| PQExpBuffer query = createPQExpBuffer(); | ||
| PGresult *res; | ||
| HostVariable *host = NULL; | ||
| char *newsql = NULL; | ||
| char *ptr = NULL; | ||
| int i = 0; | ||
|
|
||
| *error = false; | ||
| if (!sql) | ||
| return NULL; | ||
|
|
||
| /* double write quote */ | ||
| newsql = pg_malloc0(strlen(sql) * 2); /* enough */ | ||
| ptr = newsql; | ||
| while (sql[i] != '\0') | ||
| { | ||
| if (sql[i] == '\'') | ||
| *ptr++ = sql[i]; | ||
| *ptr++ = sql[i]; | ||
| i++; | ||
| } | ||
| *ptr = '\0'; | ||
|
|
||
| appendPQExpBuffer(query, "select * from get_parameter_description('%s');", newsql); | ||
| res = PQexec(pset.db, query->data); | ||
|
|
||
| if (PQresultStatus(res) == PGRES_TUPLES_OK) | ||
| { | ||
| int ntuples = PQntuples(res); | ||
| int i_name; | ||
| int i_position; | ||
| int i_hint; | ||
|
|
||
| i_name = PQfnumber(res, "name"); | ||
| i_position = PQfnumber(res, "position"); | ||
| i_hint = PQfnumber(res, "hint"); | ||
|
|
||
| /* No placeholders do not need to use PBE */ | ||
| if (ntuples == 1) | ||
| return NULL; | ||
|
|
||
| /* is an anonymous block and has placeholders */ | ||
| if (ntuples > 1) | ||
| { | ||
| char *cmdtag = NULL; | ||
| int i; | ||
|
|
||
| host = pg_malloc0(sizeof(HostVariable)); | ||
| host->hostvars = (HostVariableEntry *) pg_malloc((ntuples - 1) * sizeof(HostVariableEntry)); | ||
| host->length = ntuples - 1; | ||
|
|
||
| cmdtag = PQgetvalue(res, 0, i_name); | ||
| if (pg_strcasecmp(cmdtag, "DO")== 0) | ||
| host->isdostmt = true; | ||
| else if (pg_strcasecmp(cmdtag, "CALL")== 0) | ||
| { | ||
| host->iscallstmt = true; | ||
| host->convertcall = PQgetisnull(res, 0, i_hint) ? NULL : pg_strdup(PQgetvalue(res, 0, i_hint)); | ||
| } | ||
| else | ||
| { | ||
| host->isdostmt = false; | ||
| host->iscallstmt = false; | ||
| host->convertcall = NULL; | ||
| } | ||
|
|
||
| /* First tuple is not a placeholder info tuple, start with 1 */ | ||
| for (i = 1; i < ntuples; i++) | ||
| { | ||
| host->hostvars[i-1].name = pg_strdup(PQgetvalue(res, i, i_name)); | ||
| host->hostvars[i-1].position = atoi(PQgetvalue(res, i, i_position)); | ||
| } | ||
| } | ||
| } | ||
| else | ||
| { | ||
| pg_log_info("%s", PQerrorMessage(pset.db)); | ||
| *error = true; | ||
| } | ||
|
|
||
| PQclear(res); | ||
| destroyPQExpBuffer(query); | ||
| pg_free(newsql); | ||
|
|
||
| return host; | ||
| } |
There was a problem hiding this comment.
Potential memory leak on error paths.
The function allocates newsql (line 3611) but does not free it on all error paths. If PQexec fails or returns an unexpected status, the function returns without freeing newsql.
Apply this diff to fix the memory leak:
appendPQExpBuffer(query, "select * from get_parameter_description('%s');", newsql);
+ pg_free(newsql);
+ newsql = NULL;
+
res = PQexec(pset.db, query->data);
if (PQresultStatus(res) == PGRES_TUPLES_OK)Also, move the cleanup code (lines 3679-3681) to ensure it runs on all paths:
+cleanup:
PQclear(res);
destroyPQExpBuffer(query);
- pg_free(newsql);
+ if (newsql)
+ pg_free(newsql);
return host;🤖 Prompt for AI Agents
In src/bin/psql/common.c around lines 3596-3684, the function allocates newsql
but returns early in some branches (e.g. when ntuples == 1) without freeing
newsql or cleaning up the PGresult and PQExpBuffer; move the cleanup
(PQclear(res), destroyPQExpBuffer(query), pg_free(newsql)) into a single common
exit path and ensure every early return (including the ntuples == 1 case and any
other return-before-end branch) first frees newsql, clears res if set, and
destroys the query buffer; specifically, replace direct early returns with
setting a local result variable (or goto/cleanup label) so the function always
performs PQclear(res) if res != NULL, destroyPQExpBuffer(query) if query !=
NULL, and pg_free(newsql) before returning.
There was a problem hiding this comment.
@OreoYang, thank you! I'm glad the review was helpful. Let me know if you need any assistance with implementing the fix or if you'd like me to review the changes once you've addressed the memory leak issue.
🐰✨
| res = IvyexecPreparedStatement2(tconn, stmt, 5, param_values, param_lengths, | ||
| param_formats, argmodes, | ||
| bindinfos, 1, errmsg, 256); | ||
|
|
||
| Ivyclear(res); | ||
| return; | ||
| } |
There was a problem hiding this comment.
Guard against NULL result before Ivyclear.
IvyexecPreparedStatement2 can return NULL on error; Ivyclear handles NULL, but checking and printing errmsg improves diagnosis.
- res = IvyexecPreparedStatement2(...);
- Ivyclear(res);
+ res = IvyexecPreparedStatement2(...);
+ if (!res) {
+ fprintf(stderr, "IvyexecPreparedStatement2 failed\n");
+ return;
+ }
+ Ivyclear(res);📝 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.
| res = IvyexecPreparedStatement2(tconn, stmt, 5, param_values, param_lengths, | |
| param_formats, argmodes, | |
| bindinfos, 1, errmsg, 256); | |
| Ivyclear(res); | |
| return; | |
| } | |
| res = IvyexecPreparedStatement2(tconn, stmt, 5, param_values, param_lengths, | |
| param_formats, argmodes, | |
| bindinfos, 1, errmsg, 256); | |
| if (!res) { | |
| fprintf(stderr, "IvyexecPreparedStatement2 failed\n"); | |
| return; | |
| } | |
| Ivyclear(res); | |
| return; | |
| } |
🤖 Prompt for AI Agents
In src/interfaces/libpq/ivytest/testlibpqstmt2_call.c around lines 208 to 214,
guard against a NULL result from IvyexecPreparedStatement2 by checking if res ==
NULL; if NULL, print the errmsg buffer (e.g., fprintf to stderr or use the test
logging function) to surface the failure, then return without calling Ivyclear;
otherwise call Ivyclear(res) and return as before.
| 'ivy-exec.c', | ||
| 'ivy_sema.c', |
There was a problem hiding this comment.
🧩 Analysis chain
Build/link coverage: verify across targets.
New sources compile into both static/shared via libpq_sources; confirm:
- symbols exported as needed (exports.txt) on Windows
- no missing feature-guarded deps (SSL/GSSAPI off)
- meson default-library=shared and static-only builds succeed
🏁 Script executed:
#!/bin/bash
# Sanity: files present and referenced once
fd -a 'ivy-(exec|sema)\.c' src | nl
rg -n --fixed-strings "ivy-exec.c|ivy_sema.c" src/interfaces/libpq/meson.build
# Check exports (Windows) presence of any Ivy* symbols (if applicable)
rg -nP 'Ivy\w+2?' src/interfaces/libpq/exports.txt || true
# Quick scan for platform guards in new files (names only)
fd -a 'ivy-*.c' src/interfaces/libpq | xargs -I{} sh -c 'echo "--- {}"; rg -nP "#if|#ifdef|#include" "{}" | sed -n "1,120p"'Length of output: 950
---
🏁 Script executed:
```shell
#!/bin/bash
# Verify meson.build exists and show lines 19-20 directly
echo "=== Checking lines 19-20 of meson.build ==="
head -30 src/interfaces/libpq/meson.build | tail -15
echo ""
echo "=== Full search for ivy references in meson.build ==="
rg -in 'ivy' src/interfaces/libpq/meson.build || echo "No ivy references found"
echo ""
echo "=== Check if files exist under different names ==="
fd -a 'ivy' src/interfaces/libpq/ || echo "No ivy files found"
Length of output: 467
---
🏁 Script executed:
```shell
#!/bin/bash
# Check overall repository structure
echo "=== Repository root contents ==="
ls -la | head -20
echo ""
echo "=== Does src/ exist? ==="
ls -ld src 2>&1 || echo "src/ not found"
echo ""
echo "=== All meson.build files in repo ==="
fd -a 'meson.build' . || echo "No meson.build files found"
echo ""
echo "=== Directory structure under src (if exists) ==="
find src -maxdepth 3 -type d 2>/dev/null | head -30 || echo "src/ structure unavailable"
Length of output: 21973
🏁 Script executed:
#!/bin/bash
# Use absolute path from repository root
echo "=== Lines 15-30 of meson.build (context around 19-20) ==="
sed -n '15,30p' /home/jailuser/git/src/interfaces/libpq/meson.build
echo ""
echo "=== Full search for ivy references in interfaces/libpq ==="
rg -in 'ivy' /home/jailuser/git/src/interfaces/libpq/meson.build
echo ""
echo "=== Check if ivy-exec.c and ivy_sema.c exist ==="
fd -a 'ivy-(exec|sema)\.c' /home/jailuser/git/src/interfaces/libpq/
echo ""
echo "=== Check exports.txt for ivy symbols ==="
head -240 /home/jailuser/git/src/interfaces/libpq/exports.txt | tail -30Length of output: 1633
---
🏁 Script executed:
```shell
#!/bin/bash
# Find both files
echo "=== Search all ivy source files ==="
fd -a 'ivy.*\.c' /home/jailuser/git/src/interfaces/libpq/
echo ""
echo "=== Inspect ivy-exec.c for platform guards ==="
head -50 /home/jailuser/git/src/interfaces/libpq/ivy-exec.c | grep -E '#if|#ifdef|#include|^[^/]*ssl|gssapi'
echo ""
echo "=== Full header inspection (first 80 lines) ==="
head -80 /home/jailuser/git/src/interfaces/libpq/ivy-exec.c
Length of output: 3228
🏁 Script executed:
#!/bin/bash
# Check ivy_sema.c structure
echo "=== ivy_sema.c (first 50 lines) ==="
head -50 /home/jailuser/git/src/interfaces/libpq/ivy_sema.c
echo ""
echo "=== Platform-specific implementations presence ==="
ls -lh /home/jailuser/git/src/interfaces/libpq/*ivysema.c
echo ""
echo "=== Check meson.build for platform-specific source selection ==="
grep -A 10 -B 5 'ivysema\|WIN32\|host_system' /home/jailuser/git/src/interfaces/libpq/meson.build | head -60
echo ""
echo "=== Check for SSL/GSSAPI feature gates in meson.build ==="
rg -n 'openssl|gssapi|ssl|krb' /home/jailuser/git/src/interfaces/libpq/meson.build || echo "No SSL/GSSAPI gates found"Length of output: 2938
🏁 Script executed:
#!/bin/bash
# Check full ivy_sema.c to see if it's a dispatcher
echo "=== Complete ivy_sema.c ==="
cat /home/jailuser/git/src/interfaces/libpq/ivy_sema.c
echo ""
echo "=== win32_ivysema.c header (first 30 lines) ==="
head -30 /home/jailuser/git/src/interfaces/libpq/win32_ivysema.c
echo ""
echo "=== posix_ivysema.c header (first 30 lines) ==="
head -30 /home/jailuser/git/src/interfaces/libpq/posix_ivysema.c
echo ""
echo "=== Check if meson.build has any conditional includes for platform sema files ==="
cat /home/jailuser/git/src/interfaces/libpq/meson.build | grep -A 50 "libpq_sources = \["Length of output: 5528
🏁 Script executed:
#!/bin/bash
# Determine what ivy_sema.c actually is
echo "=== File info and type ==="
file /home/jailuser/git/src/interfaces/libpq/ivy_sema.c
ls -lh /home/jailuser/git/src/interfaces/libpq/ivy_sema.c
echo ""
echo "=== Full meson.build file ==="
cat /home/jailuser/git/src/interfaces/libpq/meson.build
echo ""
echo "=== Check posix_ivysema.c first line ==="
head -1 /home/jailuser/git/src/interfaces/libpq/posix_ivysema.cLength of output: 4136
Windows build will fail: platform-specific semaphore implementation not conditionally selected.
Verified findings:
- Export symbols (Ivy*) present in exports.txt with ordinals ✓
- SSL/GSSAPI properly feature-guarded ✓
- Static and shared builds include new sources ✓
Critical issue: ivy_sema.c is a symlink to posix_ivysema.c (hardwired). On Windows, this compiles POSIX semaphore code (sem_open, sem_post) which will fail—must use win32_ivysema.c instead (CloseHandle, CreateSemaphore).
Fix: Add conditional in meson.build (after line 22) to select correct platform implementation:
if host_system == 'windows'
libpq_sources -= files('ivy_sema.c')
libpq_sources += files('win32_ivysema.c')
else
libpq_sources -= files('ivy_sema.c')
libpq_sources += files('posix_ivysema.c') # or sysv_ivysema.c for SYSV systems
endif
Alternatively: Replace symlink with dispatcher ivy_sema.c that #includes the correct platform-specific implementation.
🤖 Prompt for AI Agents
In src/interfaces/libpq/meson.build around lines 19–20, the build
unconditionally includes ivy_sema.c (a symlink to posix_ivysema.c) which causes
Windows builds to compile POSIX semaphore APIs and fail; modify meson.build to
detect host_system == 'windows' and, if so, remove ivy_sema.c from libpq_sources
and add win32_ivysema.c, otherwise remove ivy_sema.c and add the POSIX (or SYSV)
implementation; alternatively replace the symlink with a small ivy_sema.c
dispatcher that includes the appropriate platform-specific implementation via
conditional compilation.
| -- ok | ||
| variable x varchar2(5 char) | ||
| call f_proc('123456789', :x); | ||
|
|
||
| -- ok | ||
| variable x varchar2(5 byte) | ||
| call f_proc('123456789', :x); | ||
|
|
||
| -- error | ||
| variable x char(5 char) | ||
| call f_proc('123456789', :x); | ||
|
|
||
| -- error | ||
| variable x char(5 byte) | ||
| call f_proc('123456789', :x); | ||
|
|
There was a problem hiding this comment.
Likely failure: bare print without variable names
In these blocks you call print without specifying variables (Lines 1339, 1343, 1349, 1353). Elsewhere in this file you use print x or print x y z. To avoid parser errors, change to the intended variable, e.g.:
- print
+ print xRepeat for each instance.
📝 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.
| -- ok | |
| variable x varchar2(5 char) | |
| call f_proc('123456789', :x); | |
| -- ok | |
| variable x varchar2(5 byte) | |
| call f_proc('123456789', :x); | |
| -- error | |
| variable x char(5 char) | |
| call f_proc('123456789', :x); | |
| -- error | |
| variable x char(5 byte) | |
| call f_proc('123456789', :x); | |
| -- ok | |
| variable x varchar2(5 char) | |
| call f_proc('123456789', :x); | |
| print x | |
| -- ok | |
| variable x varchar2(5 byte) | |
| call f_proc('123456789', :x); | |
| print x | |
| -- error | |
| variable x char(5 char) | |
| call f_proc('123456789', :x); | |
| print x | |
| -- error | |
| variable x char(5 byte) | |
| call f_proc('123456789', :x); | |
| print x | |
🤖 Prompt for AI Agents
In src/oracle_test/regress/sql/ora_plisql.sql around lines 1335 to 1354, the
script uses bare "print" on lines 1339, 1343, 1349 and 1353 which should
reference the variable; replace each bare "print" with "print x" (or the correct
variable name used in that block) so the CLI prints the intended variable and
avoids parser errors.
| { | ||
| /* | ||
| * The SQL CALL statement compatible with Oracle is implicitly converted to | ||
| * DoStmt on the client side (libpq). According to the behavior of Oracle 21c, | ||
| * if the parameter type declared by the subprogram is the same as the datatype | ||
| * of the bind variable, the behavior of exceeding precision is truncated, | ||
| * otherwise an error will be reported. | ||
| */ | ||
| if (estate->func && | ||
| estate->func->do_from_call && | ||
| strcmp(estate->func->fn_signature, "inline_code_block") == 0 && | ||
| (((srctype == ORACHARCHAROID || srctype == ORACHARBYTEOID) && | ||
| (dsttype == ORACHARCHAROID || dsttype == ORACHARBYTEOID)) || | ||
| ((srctype == ORAVARCHARCHAROID || srctype == ORAVARCHARBYTEOID) && | ||
| (dsttype == ORAVARCHARCHAROID || dsttype == ORAVARCHARBYTEOID)))) | ||
| cast_expr = coerce_to_target_type(NULL, | ||
| (Node *) placeholder, srctype, | ||
| dsttype, dsttypmod, | ||
| COERCION_EXPLICIT, | ||
| COERCE_IMPLICIT_CAST, | ||
| -1); | ||
| else | ||
| cast_expr = coerce_to_target_type(NULL, | ||
| (Node *) placeholder, srctype, | ||
| dsttype, dsttypmod, | ||
| COERCION_PLPGSQL, | ||
| COERCE_IMPLICIT_CAST, | ||
| -1); | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
Cache-key mismatch can leak EXPLICIT-cast semantics beyond DO-from-CALL (session-wide cast cache).
You switch to COERCION_EXPLICIT for Oracle CHAR/VARCHAR families when do_from_call+inline_code_block. However, cast_expr_hash is session-wide and keyed only by (srctype,dsttype,srctypmod,dsttypmod). Once this EXPLICIT-path expression is cached, subsequent non-DO PL/iSQL casts for the same type pair will reuse it, altering behavior globally (e.g., truncation vs error). This is a correctness risk.
Action options (pick one to avoid cross-context reuse):
- Option A (preferred): Include a context flag in plisql_CastHashKey (e.g., cast_flags with a DO_FROM_CALL_INLINE bit) so EXPLICIT and PLPGSQL variants do not collide in cast_expr_hash. Update both cast_expr_hash and estate->cast_hash keying. Mind the “no padding bytes” note when extending the struct.
- Option B: For the DO-from-CALL special-case, bypass the session-wide cast_expr_hash: build the expression and only cache the ExprState in the per-estate cast_hash (DO blocks use a private one). Do not persist a CachedExpression in cast_expr_hash for this path.
- Option C: Maintain a separate cast_expr_hash for DO blocks (heavier).
Additionally, the EXPLICIT path should use an explicit CoercionForm for clarity.
Minimal tweak for the CoercionForm:
- cast_expr = coerce_to_target_type(NULL,
- (Node *) placeholder, srctype,
- dsttype, dsttypmod,
- COERCION_EXPLICIT,
- COERCE_IMPLICIT_CAST,
- -1);
+ cast_expr = coerce_to_target_type(NULL,
+ (Node *) placeholder, srctype,
+ dsttype, dsttypmod,
+ COERCION_EXPLICIT,
+ COERCE_EXPLICIT_CAST,
+ -1);If you choose Option A, introduce a flags field in the key and set it here; happy to draft that change.
Please run targeted regressions to ensure casts outside DO-from-CALL aren’t affected:
- Prepare/execute the same char/varchar cast both inside a CALL rewritten to DO and in a plain PL/iSQL function, verifying length overflow behavior differs only where intended.
- Confirm that repeated execution order (DO first vs function first) does not change outcomes (detects cache poisoning).
Based on learnings.
I'll verify this cache-key mismatch concern by examining the codebase implementation. Let me start by searching for the cast_expr_hash and related structures.
---
🏁 Script executed:
```shell
#!/bin/bash
# Find cast_expr_hash definition and usage
rg -n "cast_expr_hash" --type=c -C 3
Length of output: 5609
🏁 Script executed:
#!/bin/bash
# Find plisql_CastHashKey structure definition
rg -n "plisql_CastHashKey" --type=c -A 10Length of output: 4384
🏁 Script executed:
#!/bin/bash
# Find do_from_call flag usage
rg -n "do_from_call" --type=c -C 2Length of output: 4073
🏁 Script executed:
#!/bin/bash
# Search for inline_code_block references in pl_exec.c context
rg -n "inline_code_block" --type=c -C 3Length of output: 2729
🏁 Script executed:
#!/bin/bash
# Find coerce_to_target_type signature to understand COERCE_ flags
rg -n "coerce_to_target_type" --type=c -B 2 -A 8 | head -100Length of output: 6619
I need to verify the exact caching flow and whether the session-wide cache is populated before or after the context-dependent conditional. Let me search deeper.
---
🏁 Script executed:
```shell
#!/bin/bash
# Find where cast_expr is stored in the hash entry
rg -n "expr_entry->cast_expr" --type=c -B 5 -A 5
Length of output: 4393
🏁 Script executed:
#!/bin/bash
# Find the complete plisql_coerce_variable_type function to see full flow
sed -n '8560,8750p' src/pl/plisql/src/pl_exec.cLength of output: 6594
🏁 Script executed:
#!/bin/bash
# Check if lookup precedes the context check
rg -n "hash_search.*cast_expr_hash" --type=c -B 15 -A 5Length of output: 2858
🏁 Script executed:
#!/bin/bash
# Search for COERCE_EXPLICIT_CAST vs COERCE_IMPLICIT_CAST definitions
rg -n "COERCE_EXPLICIT_CAST\|COERCE_IMPLICIT_CAST" --type=c -C 2Length of output: 0
Let me check for cache invalidation logic and the COERCE enum definitions:
---
🏁 Script executed:
```shell
#!/bin/bash
# Search for COERCE enum in header files
rg -n "COERCE_" --type=h | grep -E "COERCE_EXPLICIT_CAST|COERCE_IMPLICIT_CAST" | head -20
Length of output: 181
🏁 Script executed:
#!/bin/bash
# Find CoerceFormat or similar enum definitions
find src/include -name "*.h" -exec grep -l "COERCE_" {} \;Length of output: 95
🏁 Script executed:
#!/bin/bash
# Check for cache invalidation on transaction boundaries or context changes
rg -n "cast_expr_hash.*=.*NULL\|FreeCachedExpression" --type=c -B 2 -A 2Length of output: 0
🏁 Script executed:
#!/bin/bash
# Examine the complete validity check logic
sed -n '8605,8620p' src/pl/plisql/src/pl_exec.cLength of output: 404
🏁 Script executed:
#!/bin/bash
# Check pg_cast changes or invalidation triggers mentioned in comments
rg -n "pg_cast\|invalidat" src/pl/plisql/src/pl_exec.c | head -20Length of output: 0
Address cache-key collision between DO-from-CALL and regular PL/iSQL contexts.
The review concern is valid and critical. The cache key (srctype, dsttype, srctypmod, dsttypmod) does not account for execution context, enabling semantic pollution:
-
Cache poisoning mechanism: When
do_from_call=truefor inline Oracle CALL statements, the code usesCOERCION_EXPLICIT(lines 8683–8688), which permits Oracle-compatible truncation. Whendo_from_call=falsein regular PL/iSQL, it usesCOERCION_PLPGSQL(lines 8690–8695), which may apply I/O coercion fallback instead. Both paths share an identical cache key, so the first context to execute bakes its semantics intocast_expr_hash, which is session-wide and reused by all subsequent contexts. -
Why the validity check doesn't prevent this: The
is_validflag (line 8614) checks catalog consistency (e.g.,pg_castchanges), not context suitability. A cached expression remains valid across unrelated contexts. -
The proposed diff is insufficient: Changing
COERCE_IMPLICIT_CASTtoCOERCE_EXPLICIT_CASTaffects only the display format flag; it does not resolve the collision betweenCOERCION_EXPLICITandCOERCION_PLPGSQLsemantics embedded in the Expr tree itself.
Action required: Implement one of the three options:
- Option A (preferred): Extend
plisql_CastHashKeywith a context flag (e.g.,cast_contextordo_from_call_bit) and update bothcast_expr_hashandestate->cast_hashkeying to include it. - Option B: Bypass
cast_expr_hashfor DO-from-CALL paths; build and cache theExprStateonly in the per-estatecast_hash(which is private to each DO block). - Option C: Maintain a separate session-wide cache for DO blocks.
Regardless of which option you choose, the COERCE format flag adjustment can be applied separately for clarity.
🤖 Prompt for AI Agents
In src/pl/plisql/src/pl_exec.c around lines 8668–8696, the cast_expr cache key
omits execution context (do_from_call), causing DO-from-CALL semantics to
contaminate regular PL/iSQL casts; fix by including a context bit in the cache
key: add a do_from_call (or cast_context) field to plisql_CastHashKey, include
it when creating/looking up entries in the session cast_expr_hash and when
populating estate->cast_hash, update the hash/equality functions and any key
construction sites to set that bit from estate->func->do_from_call, and run
tests; alternatively (if simpler) bypass the global cast_expr_hash for
DO-from-CALL by skipping global cache inserts/lookups when do_from_call is true
and only use the per-estate cast_hash for those cases.
| if (codeblock->do_from_call && oldcontext != ErrorContext) | ||
| { | ||
| ErrorData *edata; | ||
|
|
||
| /* Save error info */ | ||
| MemoryContextSwitchTo(oldcontext); | ||
| edata = CopyErrorData(); | ||
| FlushErrorState(); | ||
|
|
||
| /* For CALL statements expect only primary error message */ | ||
| if (edata->message) | ||
| elog(ERROR, "%s", edata->message); | ||
| else | ||
| ThrowErrorData(edata); | ||
| FreeErrorData(edata); | ||
| } | ||
|
|
There was a problem hiding this comment.
Critical: early rethrow drops cleanup and SQLSTATE
- Early elog(ERROR, "%s", ...) both loses original SQLSTATE/details and bypasses cleanup below (oraparam pop, FreeExecutorState, ResourceOwnerDelete, func use_count--, free function memory). This leaks resources and may corrupt state on repeated DO/CALLs.
- FreeErrorData after a throw is unreachable.
Proposed fix: capture edata, perform full cleanup, then rethrow preserving SQLSTATE (ThrowErrorData). If you must show only the primary message, still preserve sqlstate via ereport(ERROR, (errcode(edata->sqlerrcode), errmsg_internal("%s", edata->message)))—but prefer ThrowErrorData.
Apply this diff inside the PG_CATCH block:
- if (codeblock->do_from_call && oldcontext != ErrorContext)
- {
- ErrorData *edata;
- /* Save error info */
- MemoryContextSwitchTo(oldcontext);
- edata = CopyErrorData();
- FlushErrorState();
-
- /* For CALL statements expect only primary error message */
- if (edata->message)
- elog(ERROR, "%s", edata->message);
- else
- ThrowErrorData(edata);
- FreeErrorData(edata);
- }
+ /* Save error info first */
+ ErrorData *edata = NULL;
+ MemoryContextSwitchTo(oldcontext);
+ edata = CopyErrorData();
+ FlushErrorState();
+
+ /* Common cleanup before rethrow */
+ pop_oraparam_stack(oraparam_top_level - 1, oraparam_cur_level);
+ if (ora_forward)
+ backward_oraparam_stack();
+ set_bindByName(false);
+
+ plisql_subxact_cb(SUBXACT_EVENT_ABORT_SUB,
+ GetCurrentSubTransactionId(),
+ 0, NULL);
+ FreeExecutorState(simple_eval_estate);
+ ReleaseAllPlanCacheRefsInOwner(simple_eval_resowner);
+ ResourceOwnerDelete(simple_eval_resowner);
+ func->use_count--;
+ plisql_free_function_memory(func, 0, 0);
+
+ /* Preserve original SQLSTATE/details */
+ ThrowErrorData(edata); /* no return */Committable suggestion skipped: line range outside the PR's diff.
|
no comments. |
Summary by CodeRabbit
New Features
Bug Fixes