Skip to content

Commit fc27d9c

Browse files
authored
Added dialects mysql dialects json fuction (#171)
* added : git ignore * add JSON_Array,object,qoute * add json{array_append,array_insert,contains,contains_path,depth,insert,keys * 📚add json{length,merge,merge_patch,merge_preserve * build dialects * Added Json fuction document
1 parent 5c5eb43 commit fc27d9c

39 files changed

+3202
-328
lines changed

package-lock.json

Lines changed: 469 additions & 281 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

release/app/package-lock.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/dialects/mysql/dialect.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,6 @@
77
"spaceAfterDashes": true,
88
"specialVar": "@?",
99
"identifierQuotes": "`",
10-
"keywords": "absolute action add after all allocate alter and any are as asc assertion at authorization before begin between both breadth by call cascade cascaded case cast catalog check close collate collation column commit condition connect connection constraint constraints constructor continue corresponding count create cross cube current current_date current_default_transform_group current_transform_group_for_type current_path current_role current_time current_timestamp current_user cursor cycle data day deallocate declare default deferrable deferred delete depth deref desc describe descriptor deterministic diagnostics disconnect distinct do domain drop dynamic each else elseif end end-exec equals escape except exception exec execute exists exit external fetch first for foreign found from free full function general get global go goto grant group grouping handle having hold hour identity if immediate in indicator initially inner inout input insert intersect into is isolation join key language last lateral leading leave left level like limit local localtime localtimestamp locator loop map match method minute modifies module month names natural nesting new next no none not of old on only open option or order ordinality out outer output overlaps pad parameter partial path prepare preserve primary prior privileges procedure public read reads recursive redo ref references referencing relative release repeat resignal restrict result return returns revoke right role rollback rollup routine row rows savepoint schema scroll search second section select session session_user set sets signal similar size some space specific specifictype sql sqlexception sqlstate sqlwarning start state static system_user table temporary then timezone_hour timezone_minute to trailing transaction translation treat trigger under undo union unique unnest until update usage user using value values view when whenever where while with without work write year zone accessible algorithm analyze asensitive authors auto_increment autocommit avg avg_row_length binlog btree cache catalog_name chain change changed checkpoint checksum class_origin client_statistics coalesce code collations columns comment committed completion concurrent consistent contains contributors convert database databases day_hour day_microsecond day_minute day_second delay_key_write delayed delimiter des_key_file dev_pop dev_samp deviance directory disable discard distinctrow div dual dumpfile enable enclosed ends engine engines enum errors escaped even event events every explain extended fast field fields flush force found_rows fulltext grants group_concat handler hash high_priority hosts hour_microsecond hour_minute hour_second ignore ignore_server_ids import index index_statistics infile innodb insensitive insert_method install invoker iterate keys kill linear lines list load lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modify mutex mysql_errno no_write_to_binlog offline offset one online optimize optionally outfile pack_keys parser partition partitions password phase plugin plugins prev processlist profile profiles purge query quick range read_write rebuild recover regexp relaylog remove rename reorganize repair repeatable replace require resume rlike row_format rtree schedule schema_name schemas second_microsecond security sensitive separator serializable server share show slave slow snapshot soname spatial sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result ssl starting starts std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace terminated triggers truncate uncommitted uninstall unlock upgrade use use_frm user_resources user_statistics utc_date utc_time utc_timestamp variables views warnings xa xor year_month zerofill abs acos adddate addtime ascii asin atan atan2 bin bit_length ceil ceiling char char_length character_length concat concat_ws conv convert_tz cos cot crc32 curdate curtime date date_add date_format date_sub datediff dayofmonth dayofweek dayofyear degrees elt exp export_set extract find_in_set floor format from_base64 from_days from_unixtime get_format hex instr last_day lcase length ln load_file locate log log10 log2 lower lpad ltrim make_set makedate maketime microsecond mid monthname now oct octet_length ord period_add period_diff pi position pow power quarter quote rand randians reverse round rpad rtrim sec_to_time sign sin soundex sqrt str_to_date subdate substr substring substring_index subtime sysdate tan time time_format time_to_sec timediff timestamp timestampadd timestampdiff to_base64 to_days to_seconds unix_timestamp week weekday weekofyear yearweek",
10+
"keywords": "absolute action add after all allocate alter and any are as asc assertion at authorization before begin between both breadth by call cascade cascaded case cast catalog check close collate collation column commit condition connect connection constraint constraints constructor continue corresponding count create cross cube current current_date current_default_transform_group current_transform_group_for_type current_path current_role current_time current_timestamp current_user cursor cycle data day deallocate declare default deferrable deferred delete depth deref desc describe descriptor deterministic diagnostics disconnect distinct do domain drop dynamic each else elseif end end-exec equals escape except exception exec execute exists exit external fetch first for foreign found from free full function general get global go goto grant group grouping handle having hold hour identity if immediate in indicator initially inner inout input insert intersect into is isolation join key language last lateral leading leave left level like limit local localtime localtimestamp locator loop map match method minute modifies module month names natural nesting new next no none not of old on only open option or order ordinality out outer output overlaps pad parameter partial path prepare preserve primary prior privileges procedure public read reads recursive redo ref references referencing relative release repeat resignal restrict result return returns revoke right role rollback rollup routine row rows savepoint schema scroll search second section select session session_user set sets signal similar size some space specific specifictype sql sqlexception sqlstate sqlwarning start state static system_user table temporary then timezone_hour timezone_minute to trailing transaction translation treat trigger under undo union unique unnest until update usage user using value values view when whenever where while with without work write year zone accessible algorithm analyze asensitive authors auto_increment autocommit avg avg_row_length binlog btree cache catalog_name chain change changed checkpoint checksum class_origin client_statistics coalesce code collations columns comment committed completion concurrent consistent contains contributors convert database databases day_hour day_microsecond day_minute day_second delay_key_write delayed delimiter des_key_file dev_pop dev_samp deviance directory disable discard distinctrow div dual dumpfile enable enclosed ends engine engines enum errors escaped even event events every explain extended fast field fields flush force found_rows fulltext grants group_concat handler hash high_priority hosts hour_microsecond hour_minute hour_second ignore ignore_server_ids import index index_statistics infile innodb insensitive insert_method install invoker iterate keys kill linear lines list load lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modify mutex mysql_errno no_write_to_binlog offline offset one online optimize optionally outfile pack_keys parser partition partitions password phase plugin plugins prev processlist profile profiles purge query quick range read_write rebuild recover regexp relaylog remove rename reorganize repair repeatable replace require resume rlike row_format rtree schedule schema_name schemas second_microsecond security sensitive separator serializable server share show slave slow snapshot soname spatial sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result ssl starting starts std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace terminated triggers truncate uncommitted uninstall unlock upgrade use use_frm user_resources user_statistics utc_date utc_time utc_timestamp variables views warnings xa xor year_month zerofill abs acos adddate addtime ascii asin atan atan2 bin bit_length ceil ceiling char char_length character_length concat concat_ws conv convert_tz cos cot crc32 curdate curtime date date_add date_format date_sub datediff dayofmonth dayofweek dayofyear degrees elt exp export_set extract find_in_set floor format from_base64 from_days from_unixtime get_format hex instr json_array json_array_append json_array_insert json_contains json_contains_path json_depth json_extract json_insert json_keys json_length json_merge json_merge_patch json_merge_preserve json_object json_overlaps json_pretty json_quote json_remove json_replace json_schema_valid json_schema_validation_report json_search json_set json_storage_free json_storage_size json_table json_type json_unquote json_valid json_value last_day lcase length ln load_file locate log log10 log2 lower lpad ltrim make_set makedate maketime member_of microsecond mid monthname now oct octet_length ord period_add period_diff pi position pow power quarter quote rand randians reverse round rpad rtrim sec_to_time sign sin soundex sqrt str_to_date subdate substr substring substring_index subtime sysdate tan time time_format time_to_sec timediff timestamp timestampadd timestampdiff to_base64 to_days to_seconds unix_timestamp week weekday weekofyear yearweek",
1111
"types": "array binary bit boolean char character clob date decimal double float int integer interval large national nchar nclob numeric object precision real smallint time timestamp varchar varying bool blob long longblob longtext medium mediumblob mediumint mediumtext tinyblob tinyint tinytext text bigint int1 int2 int3 int4 int8 float4 float8 varbinary varcharacter datetime unsigned signed"
1212
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
JSON_ARRAY([val[, val] ...])
2+
3+
Evaluates a (possibly empty) list of values and returns a JSON array containing those values.
4+
5+
```
6+
mysql> SELECT JSON_ARRAY(1, "abc", NULL, TRUE, CURTIME());
7+
+---------------------------------------------+
8+
| JSON_ARRAY(1, "abc", NULL, TRUE, CURTIME()) |
9+
+---------------------------------------------+
10+
| [1, "abc", null, true, "11:30:24.000000"] |
11+
+---------------------------------------------+
12+
```
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
JSON_ARRAY_APPEND(json_doc, path, val[, path, val] ...)
2+
3+
Appends values to the end of the indicated arrays within a JSON document and returns the result. Returns NULL if any argument is NULL. An error occurs if the json_doc argument is not a valid JSON document or any path argument is not a valid path expression or contains a * or ** wildcard.
4+
5+
The path-value pairs are evaluated left to right. The document produced by evaluating one pair becomes the new value against which the next pair is evaluated.
6+
7+
If a path selects a scalar or object value, that value is autowrapped within an array and the new value is added to that array. Pairs for which the path does not identify any value in the JSON document are ignored.
8+
9+
```
10+
mysql> SET @j = '["a", ["b", "c"], "d"]';
11+
mysql> SELECT JSON_ARRAY_APPEND(@j, '$[1]', 1);
12+
+----------------------------------+
13+
| JSON_ARRAY_APPEND(@j, '$[1]', 1) |
14+
+----------------------------------+
15+
| ["a", ["b", "c", 1], "d"] |
16+
+----------------------------------+
17+
mysql> SELECT JSON_ARRAY_APPEND(@j, '$[0]', 2);
18+
+----------------------------------+
19+
| JSON_ARRAY_APPEND(@j, '$[0]', 2) |
20+
+----------------------------------+
21+
| [["a", 2], ["b", "c"], "d"] |
22+
+----------------------------------+
23+
mysql> SELECT JSON_ARRAY_APPEND(@j, '$[1][0]', 3);
24+
+-------------------------------------+
25+
| JSON_ARRAY_APPEND(@j, '$[1][0]', 3) |
26+
+-------------------------------------+
27+
| ["a", [["b", 3], "c"], "d"] |
28+
+-------------------------------------+
29+
30+
mysql> SET @j = '{"a": 1, "b": [2, 3], "c": 4}';
31+
mysql> SELECT JSON_ARRAY_APPEND(@j, '$.b', 'x');
32+
+------------------------------------+
33+
| JSON_ARRAY_APPEND(@j, '$.b', 'x') |
34+
+------------------------------------+
35+
| {"a": 1, "b": [2, 3, "x"], "c": 4} |
36+
+------------------------------------+
37+
mysql> SELECT JSON_ARRAY_APPEND(@j, '$.c', 'y');
38+
+--------------------------------------+
39+
| JSON_ARRAY_APPEND(@j, '$.c', 'y') |
40+
+--------------------------------------+
41+
| {"a": 1, "b": [2, 3], "c": [4, "y"]} |
42+
+--------------------------------------+
43+
44+
mysql> SET @j = '{"a": 1}';
45+
mysql> SELECT JSON_ARRAY_APPEND(@j, '$', 'z');
46+
+---------------------------------+
47+
| JSON_ARRAY_APPEND(@j, '$', 'z') |
48+
+---------------------------------+
49+
| [{"a": 1}, "z"] |
50+
+---------------------------------+
51+
```
52+
53+
In MySQL 5.7, this function was named JSON_APPEND(). That name is no longer supported in MySQL 8.0.
54+
55+
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
JSON_ARRAY_INSERT(json_doc, path, val[, path, val] ...)
2+
3+
Updates a JSON document, inserting into an array within the document and returning the modified document. Returns NULL if any argument is NULL. An error occurs if the json_doc argument is not a valid JSON document or any path argument is not a valid path expression or contains a * or ** wildcard or does not end with an array element identifier.
4+
5+
The path-value pairs are evaluated left to right. The document produced by evaluating one pair becomes the new value against which the next pair is evaluated.
6+
7+
Pairs for which the path does not identify any array in the JSON document are ignored. If a path identifies an array element, the corresponding value is inserted at that element position, shifting any following values to the right. If a path identifies an array position past the end of an array, the value is inserted at the end of the array.
8+
9+
```
10+
mysql> SET @j = '["a", {"b": [1, 2]}, [3, 4]]';
11+
mysql> SELECT JSON_ARRAY_INSERT(@j, '$[1]', 'x');
12+
+------------------------------------+
13+
| JSON_ARRAY_INSERT(@j, '$[1]', 'x') |
14+
+------------------------------------+
15+
| ["a", "x", {"b": [1, 2]}, [3, 4]] |
16+
+------------------------------------+
17+
mysql> SELECT JSON_ARRAY_INSERT(@j, '$[100]', 'x');
18+
+--------------------------------------+
19+
| JSON_ARRAY_INSERT(@j, '$[100]', 'x') |
20+
+--------------------------------------+
21+
| ["a", {"b": [1, 2]}, [3, 4], "x"] |
22+
+--------------------------------------+
23+
mysql> SELECT JSON_ARRAY_INSERT(@j, '$[1].b[0]', 'x');
24+
+-----------------------------------------+
25+
| JSON_ARRAY_INSERT(@j, '$[1].b[0]', 'x') |
26+
+-----------------------------------------+
27+
| ["a", {"b": ["x", 1, 2]}, [3, 4]] |
28+
+-----------------------------------------+
29+
mysql> SELECT JSON_ARRAY_INSERT(@j, '$[2][1]', 'y');
30+
+---------------------------------------+
31+
| JSON_ARRAY_INSERT(@j, '$[2][1]', 'y') |
32+
+---------------------------------------+
33+
| ["a", {"b": [1, 2]}, [3, "y", 4]] |
34+
+---------------------------------------+
35+
mysql> SELECT JSON_ARRAY_INSERT(@j, '$[0]', 'x', '$[2][1]', 'y');
36+
+----------------------------------------------------+
37+
| JSON_ARRAY_INSERT(@j, '$[0]', 'x', '$[2][1]', 'y') |
38+
+----------------------------------------------------+
39+
| ["x", "a", {"b": [1, 2]}, [3, 4]] |
40+
+----------------------------------------------------+
41+
```
42+
43+
Earlier modifications affect the positions of the following elements in the array, so subsequent paths in the same `JSON_ARRAY_INSERT()` call should take this into account. In the final example, the second path inserts nothing because the path no longer matches anything after the first insert.
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
JSON_CONTAINS(target, candidate[, path])
2+
3+
Indicates by returning 1 or 0 whether a given candidate JSON document is contained within a target JSON document, or—if a path argument was supplied—whether the candidate is found at a specific path within the target. Returns NULL if any argument is NULL, or if the path argument does not identify a section of the target document. An error occurs if target or candidate is not a valid JSON document, or if the path argument is not a valid path expression or contains a * or ** wildcard.
4+
5+
To check only whether any data exists at the path, use `JSON_CONTAINS_PATH()` instead.
6+
7+
The following rules define containment:
8+
- A candidate scalar is contained in a target scalar if and only if they are comparable and are equal. Two scalar values are comparable if they have the same `JSON_TYPE()` types, with the exception that values of types `INTEGER` and `DECIMAL` are also comparable to each other.
9+
- A candidate array is contained in a target array if and only if every element in the candidate is contained in some element of the target.
10+
- A candidate nonarray is contained in a target array if and only if the candidate is contained in some element of the target.
11+
- A candidate object is contained in a target object if and only if for each key in the candidate there is a key with the same name in the target and the value associated with the candidate key is contained in the value associated with the target key.
12+
13+
Otherwise, the candidate value is not contained in the target document.
14+
15+
Starting with MySQL 8.0.17, queries using JSON_CONTAINS() on `InnoDB` tables can be optimized using multi-valued indexes; see [Multi-Valued Indexes](https://dev.mysql.com/doc/refman/8.0/en/create-index.html#create-index-multi-valued), for more information.
16+
17+
```
18+
mysql> SET @j = '{"a": 1, "b": 2, "c": {"d": 4}}';
19+
mysql> SET @j2 = '1';
20+
mysql> SELECT JSON_CONTAINS(@j, @j2, '$.a');
21+
+-------------------------------+
22+
| JSON_CONTAINS(@j, @j2, '$.a') |
23+
+-------------------------------+
24+
| 1 |
25+
+-------------------------------+
26+
mysql> SELECT JSON_CONTAINS(@j, @j2, '$.b');
27+
+-------------------------------+
28+
| JSON_CONTAINS(@j, @j2, '$.b') |
29+
+-------------------------------+
30+
| 0 |
31+
+-------------------------------+
32+
33+
mysql> SET @j2 = '{"d": 4}';
34+
mysql> SELECT JSON_CONTAINS(@j, @j2, '$.a');
35+
+-------------------------------+
36+
| JSON_CONTAINS(@j, @j2, '$.a') |
37+
+-------------------------------+
38+
| 0 |
39+
+-------------------------------+
40+
mysql> SELECT JSON_CONTAINS(@j, @j2, '$.c');
41+
+-------------------------------+
42+
| JSON_CONTAINS(@j, @j2, '$.c') |
43+
+-------------------------------+
44+
| 1 |
45+
+-------------------------------+
46+
```
47+
48+
49+

0 commit comments

Comments
 (0)