Skip to content

Commit

Permalink
Fix crash due to null current memory context after error in openjson …
Browse files Browse the repository at this point in the history
…WITH (#3339) (#3342)

Any variable we set in try, may not be visible to catch block.
Fix such a case where we set oldcontext variable in try block
the use it in catch block, which leads to setting current 
memory context as NULL.

Task: BABEL-5020
Signed-off-by: Tanzeel Khan <[email protected]>
  • Loading branch information
tanscorpio7 authored Jan 3, 2025
1 parent 5e774aa commit 7b3e322
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
5 changes: 3 additions & 2 deletions contrib/babelfishpg_tsql/src/json_funcs.c
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,7 @@ tsql_openjson_with_internal(PG_FUNCTION_ARGS)

funcctx = SRF_FIRSTCALL_INIT();
prev_sql_dialect = sql_dialect;
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
PG_TRY();
{
Jsonb *sub_jb;
Expand All @@ -317,7 +318,6 @@ tsql_openjson_with_internal(PG_FUNCTION_ARGS)
* processing
*/
sql_dialect = SQL_DIALECT_TSQL;
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);

/*
* Get information about return type. Used to build return message
Expand Down Expand Up @@ -377,9 +377,10 @@ tsql_openjson_with_internal(PG_FUNCTION_ARGS)
PG_FINALLY();
{
sql_dialect = prev_sql_dialect;
MemoryContextSwitchTo(oldcontext);
}
PG_END_TRY();

MemoryContextSwitchTo(oldcontext);
}

funcctx = SRF_PERCALL_SETUP();
Expand Down
19 changes: 19 additions & 0 deletions test/JDBC/expected/BABEL-OPENJSON.out
Original file line number Diff line number Diff line change
Expand Up @@ -316,3 +316,22 @@ int#!#nvarchar#!#nvarchar#!#int#!#datetime2
5#!#Jane#!#Smith#!#<NULL>#!#2005-11-04 12:00:00.0000000
~~END~~


-- BABEL-5020
CREATE PROC babel_5020_p
AS
SELECT * INTO babel_5020_t FROM openjson(N'{"a":1}', 'strict $.a') with (a nvarchar(20))
GO

EXEC babel_5020_p
GO
~~ERROR (Code: 33557097)~~

~~ERROR (Message: Value referenced by JSON path is not an array or object and cannot be opened with OPENJSON.)~~


DROP PROC babel_5020_p
GO

DROP TABLE IF EXISTS babel_5020_t
GO
15 changes: 15 additions & 0 deletions test/JDBC/input/BABEL-OPENJSON.sql
Original file line number Diff line number Diff line change
Expand Up @@ -139,3 +139,18 @@ SELECT *
FROM OPENJSON(@json)
WITH ( id INT 'strict $.id', firstName NVARCHAR(50) '$.info.name', lastName NVARCHAR(50) '$.info.surname', age INT, dateOfBirth DATETIME2 '$.dob' );
go

-- BABEL-5020
CREATE PROC babel_5020_p
AS
SELECT * INTO babel_5020_t FROM openjson(N'{"a":1}', 'strict $.a') with (a nvarchar(20))
GO

EXEC babel_5020_p
GO

DROP PROC babel_5020_p
GO

DROP TABLE IF EXISTS babel_5020_t
GO

0 comments on commit 7b3e322

Please sign in to comment.