Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(expr): add jsonb_populate_record(set) function #13421

Merged
merged 10 commits into from
Apr 16, 2024

Conversation

wangrunji0408
Copy link
Contributor

I hereby agree to the terms of the RisingWave Labs, Inc. Contributor License Agreement.

What's changed and what's your intention?

This PR adds the jsonb_populate_record function and its set-returning form:

jsonb_populate_record ( base anyelement, from_json jsonb ) → anyelement
jsonb_populate_recordset ( base anyelement, from_json jsonb ) → setof anyelement

To support jsonb_populate_recordset, some improvements have been made to the #[function] macro, in order to support Option inputs and the Context argument for table functions.

Remaining issue

Calling the scalar function jsonb_populate_record in the FROM clause triggers a panic in the planner.

dev=> select * from jsonb_populate_record(
    null::struct<a int, b int>,
    '{"a": 1, "b": 2}' 
);
ERROR:  Panicked when processing: insert at index 1 exceeds fixbitset size 1

Although calling it in the SELECT list is normal, it seems that the above form is more commonly used.

dev=> select jsonb_populate_record(
    null::struct<a int, b int>,
    '{"a": 1, "b": 2}'
);
 jsonb_populate_record 
-----------------------
 (1,2)

This PR also implements a similar function jsonb_to_record(set) on the backend. However, they are not enabled due to lack of frontend support.

These functions are designed to be called in the FROM clause, with type defined by an AS clause.

postgres=# select * from jsonb_to_record('{"a":1,"b":"foo","c":"bar"}')
    as x(a int, b text, d text);
 a |  b  | d 
---+-----+---
 1 | foo | 

It seems that we don't support such usage in both parser and frontend.

-- risingwave
dev=> select * from jsonb_to_record('{"a":1,"b":"foo","c":"bar"}')
    as x(a int, b text, d text);
ERROR:  QueryError

Caused by:
  sql parser error: Expected ), found: int at line:2, column:15
Near "
    as x(a"

Checklist

  • I have written necessary rustdoc comments
  • I have added necessary unit tests and integration tests
  • I have added fuzzing tests or opened an issue to track them. (Optional, recommended for new SQL features Sqlsmith: Sql feature generation #7934).
  • My PR contains breaking changes. (If it deprecates some features, please create a tracking issue to remove them in the future).
  • All checks passed in ./risedev check (or alias, ./risedev c)
  • My PR changes performance-critical code. (Please run macro/micro-benchmarks and show the results.)
  • My PR contains critical fixes that are necessary to be merged into the latest release. (Please check out the details)

Documentation

  • My PR needs documentation updates. (Please use the Release note section below to summarize the impact on users)

Release note

Add 2 functions:

jsonb_populate_record ( base anyelement, from_json jsonb ) → anyelement
jsonb_populate_recordset ( base anyelement, from_json jsonb ) → setof anyelement

See postgres documents for detailed descriptions.

Note that we have different usages compared to pg.

-- risingwave
select (jsonb_populate_record(
    null::struct<a int, b text[], c struct<d int, e text>>,
    '{"a": 1, "b": ["2", "a b"], "c": {"d": 4, "e": "a b c"}, "x": "foo"}'
)).*;
----
1 {2,"a b"} (4,"a b c")

select * from jsonb_populate_recordset(
    null::struct<a int, b int>,
    '[{"a":1,"b":2}, {"a":3,"b":4}]'::jsonb
);
----
1 2
3 4

In Postgres, users need to define a composite type using CREATE TYPE before calling these functions.
In RisingWave, users should use inline struct type instead.

@fuyufjh
Copy link
Member

fuyufjh commented Nov 15, 2023

Regarding of the remaining issue: I think it's okay to keep the status quo i.e. do not support this usage now. I can't see any real benefit or use cases. What do you think? cc. @xiangjinwu


Did some quick experiments on PG and here is the result:

test=# select * from md5('hello');
               md5
----------------------------------
 5d41402abc4b2a76b9719d911017c592
(1 row) 

-- this is equivalent to
test=# select md5('hello');
               md5
----------------------------------
 5d41402abc4b2a76b9719d911017c592
(1 row)

While operators can't

test=# select * from 1+1;
ERROR:  syntax error at or near "1"

@wangrunji0408
Copy link
Contributor Author

select * from a_scalar_function_that_returns_record() seems to be useful.
But we support an equivalent way: select (a_scalar_function_that_returns_record()).*;
So I also agree to leave this issue to the future.

@xiangjinwu
Copy link
Contributor

xiangjinwu commented Nov 15, 2023

Regarding of the remaining issue: I think it's okay to keep the status quo i.e. do not support this usage now. I can't see any real benefit or use cases. What do you think? cc. @xiangjinwu

Its major usage is to convert from a loosely typed jsonb to strongly typed struct, as we have discussed on the map type issue #13387 (comment) . According to PostgreSQL:

typical use would be to reference a json or jsonb column laterally from another table in the query's FROM clause. Writing json_populate_record in the FROM clause is good practice, since all of the extracted columns are available for use without duplicate function calls.

I will give an example on how it could help if we decided to use jsonb for proto map<string, Location>:

select (lookup(col1, 'SFO')).latitude from t; -- if we had a `lookup` function on native `map` or `struct[]`
select col1 -> 'SFO' ->> 'latitude' from t; -- if we used `jsonb`

select
  latitude
from
  t,
  json_populate_record(null::struct<latitude float8, longitude float8>, col1 -> 'SFO');
-- if we used `jsonb`, and `json_populate_record` helps use convert inner `jsonb` back to strongly typed struct `Location`.

It is true that we can do (...).* in select-list as well. But the lateral-from syntax is more convenient if we want to process further immediately, for example select tand(latitude) * sind(longitude) from ...

That being said, it is always possible to implement a functionality that can only be used in limited cases, and then improved in future iterations.

Copy link
Contributor

This PR has been open for 60 days with no activity. Could you please update the status? Feel free to ping a reviewer if you are waiting for review.

Copy link

gitguardian bot commented Apr 16, 2024

⚠️ GitGuardian has uncovered 1 secret following the scan of your pull request.

Please consider investigating the findings and remediating the incidents. Failure to do so may lead to compromising the associated services or software components.

🔎 Detected hardcoded secret in your pull request
GitGuardian id GitGuardian status Secret Commit Filename
9425213 Triggered Generic Password 505790f ci/scripts/regress-test.sh View secret
🛠 Guidelines to remediate hardcoded secrets
  1. Understand the implications of revoking this secret by investigating where it is used in your code.
  2. Replace and store your secret safely. Learn here the best practices.
  3. Revoke and rotate this secret.
  4. If possible, rewrite git history. Rewriting git history is not a trivial act. You might completely break other contributing developers' workflow and you risk accidentally deleting legitimate data.

To avoid such incidents in the future consider


🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.

Our GitHub checks need improvements? Share your feedbacks!

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

license-eye has totally checked 5010 files.

Valid Invalid Ignored Fixed
2150 1 2859 0
Click to see the invalid file list
  • src/expr/impl/src/scalar/jsonb_record.rs

src/expr/impl/src/scalar/jsonb_record.rs Outdated Show resolved Hide resolved
Signed-off-by: Runji Wang <[email protected]>
@wangrunji0408 wangrunji0408 marked this pull request as ready for review April 16, 2024 09:02
Signed-off-by: Runji Wang <[email protected]>
Copy link
Contributor

@TennyZhuang TennyZhuang left a comment

Choose a reason for hiding this comment

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

LGTM

Signed-off-by: Runji Wang <[email protected]>
Copy link
Contributor

@xiangjinwu xiangjinwu left a comment

Choose a reason for hiding this comment

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

Just wondering the following:

  • How is frontend agg name jsonb_populate_recordset mapped to the proto enum, by the macro?
  • How does frontend infer the return type is same as first argument for jsonb_populate_record?

src/common/src/types/jsonb.rs Outdated Show resolved Hide resolved
@wangrunji0408
Copy link
Contributor Author

How is frontend agg name jsonb_populate_recordset mapped to the proto enum, by the macro?

by the PbType::from_str_name function generated by prost:

impl FromStr for crate::expr::table_function::PbType {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::from_str_name(&s.to_uppercase()).ok_or(())
}
}

How does frontend infer the return type is same as first argument for jsonb_populate_record?

The #[function] macro generates a type inference function for this function.

} else if self.ret == "struct" {
if let Some(i) = self.args.iter().position(|t| t == "struct") {
// infer as the type of "struct" argument
return Ok(quote! { |args| Ok(args[#i].clone()) });
}

and frontend will call this function at the end of infer_type.

let return_type = (sig.type_infer)(&input_types)?;

@wangrunji0408 wangrunji0408 enabled auto-merge April 16, 2024 11:29
@wangrunji0408 wangrunji0408 added this pull request to the merge queue Apr 16, 2024
Merged via the queue into main with commit 4ba80c9 Apr 16, 2024
28 of 30 checks passed
@wangrunji0408 wangrunji0408 deleted the wrj/jsonb-to-record branch April 16, 2024 12:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants